Debian Codegraph @

cylc/flow/parsec/exceptions.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 from copy import copy
18 import os
19 import textwrap
20 import typing as t
21
22 from cylc.flow.parsec.util import itemstr
23
24
25 TRACEBACK_WRAPPER = textwrap.TextWrapper()
26
27
28 class ParsecError(Exception):
29 """Generic exception for Parsec errors."""
30
31 schd_expected: bool = False
32 """Set this flag to True on the exception if it is anticipated during
33 Cylc Scheduler run (apart from loading of config we do not expect
34 ParsecErrors during runtime)."""
35
36
37 class ItemNotFoundError(ParsecError, KeyError):
38 """Error raised for missing configuration items."""
39
40 def __init__(self, item):
41 self.item = item
42
43 def __str__(self):
44 return f'You have not set \"{self.item}\" in this config.'
45
46
47 class InvalidConfigError(ParsecError, KeyError):
48 """Error raised for missing configuration items."""
49
50 def __init__(self, item, specname):
51 self.item = item
52 self.specname = specname
53
54 def __str__(self):
55 return (
56 f'"{self.item}" is not a valid '
57 f'configuration for {self.specname}.'
58 )
59
60
61 class NotSingleItemError(ParsecError, TypeError):
62 """Error raised if an iterable is given where an item is expected."""
63
64 def __init__(self, item):
65 self.item = item
66
67 def __str__(self):
68 return f'not a singular item: {self.item}'
69
70
71 class FileParseError(ParsecError):
72 """Error raised when attempting to read in the config file(s).
73
74 Args:
75 reason:
76 Description of error.
77 err_type:
78 Classification of error (e.g. Jinja2Error).
79 help_lines:
80 Additional info to include in the exception.
81 lines:
82 (preferred) Dictionary in the format
83 {filename: [context_line, ..., error_line]}
84 index:
85 The line number of the error in the config (counting from the
86 shebang line *not* the first line).
87 line:
88 The line of the error in the config.
89 fpath:
90 The path to the file containing the error.
91
92 """
93
94 def __init__(
95 self,
96 reason: str,
97 index: t.Optional[int] = None,
98 line: t.Optional[str] = None,
99 lines: t.Optional[t.Dict[str, t.List[str]]] = None,
100 err_type: t.Optional[str] = None,
101 fpath: t.Optional[str] = None,
102 help_lines: t.Optional[t.Iterable[str]] = None,
103 ):
104 self.reason = reason
105 self.line_num = index + 1 if index is not None else None
106 self.line = line
107 self.lines = lines
108 self.err_type = err_type
109 self.fpath = fpath
110 self.help_lines = help_lines or []
111
112 def __str__(self) -> str:
113 msg = ''
114 msg += self.reason
115
116 if self.line_num is not None or self.fpath:
117 temp = []
118 if self.fpath:
119 temp.append(f'in {self.fpath}')
120 if self.line_num is not None:
121 temp.append(f'line {self.line_num}')
122 msg += f' ({" ".join(temp)})'
123 if self.line:
124 msg += ":\n " + self.line.strip()
125 if self.lines:
126 for filename, lines in self.lines.items():
127 msg += f'\nFile {filename}\n ' + '\n '.join(lines)
128 msg += "\t<--"
129 if self.err_type:
130 msg += ' %s' % self.err_type
131 help_lines = list(self.help_lines)
132 if self.line_num:
133 # TODO - make 'view' function independent of cylc:
134 help_lines.append("line numbers match 'cylc view -p'")
135 for help_line in help_lines:
136 msg += f'\n({help_line})'
137 return msg
138
139
140 class TemplateVarLanguageClash(FileParseError):
141 """Multiple workflow configuration templating engines configured."""
142
143
144 class Jinja2Error(FileParseError):
145 """Wrapper class for Jinja2 exceptions.
146
147 Args:
148 exception:
149 The exception being re-raised
150 lines:
151 Dictionary in the format
152 {filename: [context_line, ..., error_line]}
153 filename:
154 Alternative to "lines" where less detail is available.
155
156 """
157
158 def __init__(
159 self,
160 exception: Exception,
161 lines: t.Optional[t.Dict[str, t.List[str]]] = None,
162 filename: t.Optional[str] = None,
163 ):
164 # extract the first sentence of exception
165 msg: str = str(exception)
166 try:
167 msg, tail = msg.split('. ', 1)
168 except ValueError:
169 tail = ''
170 else:
171 msg += '.'
172 tail = tail.strip()
173
174 # append the filename e.g. for a Jinja2 template
175 if filename:
176 msg += f'\nError in file "{filename}"'
177
178 # append the rest of the exception
179 if tail:
180 msg += '\n' + '\n'.join(TRACEBACK_WRAPPER.wrap(tail))
181
182 FileParseError.__init__(
183 self,
184 msg,
185 lines=lines,
186 err_type=exception.__class__.__name__
187 )
188
189
190 class IncludeFileNotFoundError(ParsecError):
191 """Error raised for missing include files."""
192
193 def __init__(self, flist):
194 """Missing include file error.
195
196 E.g. for [DIR/top.cylc, DIR/inc/sub.cylc, DIR/inc/gone.cylc]
197 "Include-file not found: inc/gone.cylc via inc/sub.cylc from
198 DIR/top.cylc"
199 """
200 rflist = copy(flist)
201 top_file = rflist[0]
202 top_dir = os.path.dirname(top_file) + '/'
203 rflist.reverse()
204 msg = rflist[0].replace(top_dir, '')
205 for f in rflist[1:-1]:
206 msg += ' via %s' % f.replace(top_dir, '')
207 msg += ' from %s' % top_file
208 ParsecError.__init__(self, msg)
209
210
211 class UpgradeError(ParsecError):
212 """Error raised upon fault in an upgrade operation."""
213
214
215 class ValidationError(ParsecError):
216 """Generic exception for invalid configurations."""
217
218 def __init__(self, keys, value=None, msg=None, exc=None, vtype=None,
219 key=None):
220 self.keys = keys
221 self.value = value
222 self.msg = msg
223 self.exc = exc
224 self.vtype = vtype
225 self.key = key
226
227 def __str__(self):
228 msg = ''
229 if self.vtype:
230 msg += f'(type={self.vtype}) '
231 if self.key:
232 msg += itemstr(self.keys, self.key)
233 elif self.value:
234 msg += itemstr(self.keys[:-1], self.keys[-1], value=self.value)
235 if self.msg or self.exc:
236 msg += (
237 f' - ({self.exc or ""}'
238 f'{": " if (self.exc and self.msg) else ""}'
239 f'{self.msg or ""})'
240 )
241 return msg
242
243
244 class IllegalValueError(ValidationError):
245 """Bad setting value."""
246
247 def __init__(self, vtype, keys, value, exc=None, msg=None):
248 ValidationError.__init__(
249 self, keys, vtype=vtype, value=value, exc=exc, msg=msg)
250
251
252 class ListValueError(IllegalValueError):
253 """Bad setting value, for a comma separated list."""
254
255 def __init__(self, keys, value, msg=None, exc=None):
256 IllegalValueError.__init__(
257 self, 'list', keys, value, exc=exc, msg=msg)
258
259
260 class IllegalItemError(ValidationError):
261 """Bad setting section or option name."""
262
263 def __init__(self, keys, key, msg=None, exc=None):
264 ValidationError.__init__(self, keys, key=key, exc=exc, msg=msg)