Debian Codegraph @

cylc/flow/unicode_rules.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 """Module for unicode restrictions"""
18
19 import re
20
21 from cylc.flow.task_id import (
22 _TASK_NAME_CHARACTERS,
23 _TASK_NAME_PREFIX,
24 )
25 from cylc.flow.run_modes import RunMode
26 from cylc.flow.task_qualifiers import TASK_QUALIFIERS
27 from cylc.flow.task_state import TASK_STATUSES_ORDERED
28
29 ENGLISH_REGEX_MAP = {
30 r'\w': r'alphanumeric (regex word characters - ``\w``)',
31 r'a-zA-Z0-9': 'latin letters and numbers',
32 r'\d': 'numbers',
33 r'\-': '``-``',
34 r'\.': '``.``',
35 r'\/': '``/``'
36 }
37
38
39 def regex_chars_to_text(chars):
40 r"""Return a string representing a regex component.
41
42 Examples:
43 >>> regex_chars_to_text(['a', 'b', 'c'])
44 ['``a``', '``b``', '``c``']
45 >>> regex_chars_to_text([r'\-', r'\.', r'\/'])
46 ['``-``', '``.``', '``/``']
47 >>> regex_chars_to_text([r'\w'])
48 ['alphanumeric (regex word characters - ``\\w``)']
49 >>> regex_chars_to_text(['not_in_map'])
50 ['``not_in_map``']
51
52 """
53 return [
54 ENGLISH_REGEX_MAP.get(char, f'``{char}``')
55 for char in chars
56 ]
57
58
59 def length(minimum, maximum):
60 """Restrict character length.
61
62 Example:
63 >>> regex, message = length(0, 5)
64 >>> message
65 'must be between 0 and 5 characters long'
66 >>> bool(regex.match('abcde'))
67 True
68 >>> bool(regex.match('abcdef'))
69 False
70
71 """
72 return (
73 re.compile(r'^.{%d,%d}$' % (minimum, maximum)),
74 f'must be between {minimum} and {maximum} characters long'
75 )
76
77
78 def allowed_characters(*chars):
79 """Restrict permitted characters.
80
81 Example:
82 >>> regex, message = allowed_characters('a', 'b', 'c')
83 >>> message
84 'can only contain: ``a``, ``b``, ``c``'
85 >>> bool(regex.match('abc'))
86 True
87 >>> bool(regex.match('def'))
88 False
89
90 """
91 return (
92 re.compile(r'^[%s]+$' % ''.join(chars)),
93 f'can only contain: {", ".join(regex_chars_to_text(chars))}'
94 )
95
96
97 def disallowed_characters(*chars):
98 """Restrict permitted characters.
99
100 Example:
101 >>> regex, message = disallowed_characters('&', '~')
102 >>> message
103 'cannot contain: ``&``, ``~``'
104 >>> bool(regex.match('abc01'))
105 True
106 >>> bool(regex.match('abc&01'))
107 False
108
109 """
110 return (
111 re.compile(r'^[^%s]*$' % ''.join(chars)),
112 f'cannot contain: {", ".join(regex_chars_to_text(chars))}'
113 )
114
115
116 def starts_with(*chars):
117 """Restrict first character.
118
119 Example:
120 >>> regex, message = starts_with('a', 'b', 'c')
121 >>> message
122 'must start with: ``a``, ``b``, ``c``'
123 >>> bool(regex.match('def'))
124 False
125 >>> bool(regex.match('adef'))
126 True
127
128 """
129 return (
130 re.compile(r'^[%s]' % ''.join(chars)),
131 f'must start with: {", ".join(regex_chars_to_text(chars))}'
132 )
133
134
135 def not_starts_with_char(*chars):
136 """Restrict first character.
137
138 Example:
139 >>> regex, message = not_starts_with_char('a', 'b', 'c')
140 >>> message
141 'cannot start with: ``a``, ``b``, ``c``'
142 >>> bool(regex.match('def'))
143 True
144 >>> bool(regex.match('adef'))
145 False
146
147 """
148 return (
149 re.compile(r'^[^%s]' % ''.join(chars)),
150 f'cannot start with: {", ".join(regex_chars_to_text(chars))}'
151 )
152
153
154 def not_starts_with(string):
155 """Restrict strings starting with ___.
156
157 Example:
158 Regular usage:
159 >>> regex, message = not_starts_with('foo')
160 >>> message
161 'cannot start with: ``foo``'
162 >>> bool(regex.match('tfoo'))
163 True
164 >>> bool(regex.match('foot'))
165 False
166
167 Note regex chars are escaped automatically:
168 >>> regex, message = not_starts_with('...')
169 >>> bool(regex.match('aaa b'))
170 True
171 >>> bool(regex.match('... b'))
172 False
173
174 """
175 return (
176 re.compile(rf'^(?!{re.escape(string)})'),
177 f'cannot start with: ``{string}``'
178 )
179
180
181 def _human_format_list(lst):
182 """Write a list in plain text.
183
184 Examples:
185 >>> _human_format_list(['a'])
186 'a'
187 >>> _human_format_list(['a', 'b'])
188 'a or b'
189 >>> _human_format_list(['a', 'b', 'c'])
190 'a, b or c'
191
192 """
193 if len(lst) > 1:
194 return ', '.join(lst[:-1]) + f' or {lst[-1]}'
195 return lst[0]
196
197
198 def _re_format_list(lst):
199 """Write a list in regex format.
200
201 Examples:
202 >>> _re_format_list('a')
203 '(a)'
204 >>> _re_format_list(['a', 'b'])
205 '(a|b)'
206 >>> _re_format_list(['a', 'b', 'c'])
207 '(a|b|c)'
208
209 """
210 return f"({'|'.join(map(re.escape, lst))})"
211
212
213 def not_equals(*strings):
214 r"""Restrict entire string.
215
216 Example:
217 Regular usage:
218 >>> regex, message = not_equals('foo')
219 >>> message
220 'cannot be: ``foo``'
221 >>> bool(regex.match('foot')) # "foot" shouldn't match
222 True
223 >>> bool(regex.match('a\nb')) # newlines should be tolerated
224 True
225 >>> bool(regex.match('foo')) # "foo" should match
226 False
227
228 Regular use (multi):
229 >>> regex, message = not_equals('foo', 'bar', 'baz')
230 >>> regex.pattern
231 '^(?!^(foo|bar|baz)$).*$'
232 >>> message
233 'cannot be: ``foo``, ``bar`` or ``baz``'
234
235 Note regex chars are escaped automatically:
236 >>> regex, message = not_equals('...')
237 >>> bool(regex.match('...'))
238 False
239 >>> bool(regex.match('aaa'))
240 True
241
242 """
243 return (
244 re.compile(rf'^(?!^{_re_format_list(strings)}$).*$', re.M),
245 'cannot be: ' + _human_format_list([f'``{s}``' for s in strings])
246 )
247
248
249 def disallow_char_if_not_at_end_of_first_word(char):
250 """Prevent use of a (non-alphanumeric) character unless it occurs directly
251 after first word (in which case there is no limit on subsequent
252 occurances).
253
254 Example:
255 >>> regex, message = disallow_char_if_not_at_end_of_first_word(':')
256 >>> message
257 'cannot contain ``:`` unless it occurs at the end of the first word'
258 >>> bool(regex.match('Foo: bar'))
259 True
260 >>> bool(regex.match('INFO: Foo: bar'))
261 True
262 >>> bool(regex.match('Foo bar: baz'))
263 False
264 >>> bool(regex.match('Foo bar'))
265 True
266
267 """
268 return (
269 re.compile(fr'^(\w+{char}.*|[^{char}]+)$', flags=re.S),
270 f'cannot contain ``{char}`` unless it occurs at the end of the '
271 'first word'
272 )
273
274
275 class UnicodeRuleChecker():
276
277 RULES: list = []
278
279 @classmethod
280 def __init_subclass__(cls):
281 cls.__doc__ = cls.__doc__ + '\n' if cls.__doc__ else ''
282 cls.__doc__ += '\n' + '\n'.join([
283 f'* {message}'
284 for regex, message in cls.RULES
285 ])
286
287 @classmethod
288 def validate(cls, string):
289 """Run this collection of rules against the given string.
290
291 Args:
292 string (str):
293 String to validate.
294
295 Returns:
296 tuple - (outcome, message)
297 outcome (bool) - True if all patterns match.
298 message (str) - User-friendly error message.
299
300 """
301 for rule, message in cls.RULES:
302 if not rule.match(string):
303 return (
304 False,
305 # convert RST style literals to Markdown for error messages
306 # (RST used in docs)
307 message.replace('``', '`'),
308 )
309 return (True, None)
310
311
312 class WorkflowNameValidator(UnicodeRuleChecker):
313 """The rules for valid workflow names:"""
314
315 RULES = [
316 length(1, 254),
317 not_starts_with_char(r'\.', r'\-', r'\d'),
318 allowed_characters(r'\w', r'\/', '_', '+', r'\-', r'\.', '@'),
319 ]
320
321
322 class XtriggerNameValidator(UnicodeRuleChecker):
323 """The rules for valid xtrigger labels:"""
324
325 RULES = [
326 allowed_characters(r'a-zA-Z0-9', '_'),
327 not_starts_with('_cylc'),
328 ]
329
330
331 class TaskMessageValidator(UnicodeRuleChecker):
332 """The rules for valid task messages:"""
333
334 RULES = [
335 # <severity>:<message> e.g. "WARN: something went wrong
336 disallow_char_if_not_at_end_of_first_word(':'),
337 # blacklist built-in qualifiers
338 # (technically we need only blacklist task messages, however, to avoid
339 # confusion it's best to blacklist qualifiers too)
340 not_equals(*TASK_QUALIFIERS),
341 not_starts_with('_cylc'),
342 ]
343
344
345 class TaskOutputValidator(UnicodeRuleChecker):
346 """The rules for valid task outputs/message triggers:"""
347
348 RULES = [
349 # restrict outputs to sensible characters
350 allowed_characters(r'\w', r'\d', r'\-'),
351 # blacklist the _cylc prefix
352 not_starts_with('_cylc'),
353 # blacklist keywords
354 not_equals('required', 'optional', 'all', 'and', 'or'),
355 # blacklist Run Modes:
356 not_equals(RunMode.SKIP.value),
357 # blacklist built-in task qualifiers and statuses (e.g. "waiting")
358 not_equals(*sorted({*TASK_QUALIFIERS, *TASK_STATUSES_ORDERED})),
359 ]
360
361
362 class TaskNameValidator(UnicodeRuleChecker):
363 """The rules for valid task and family names:"""
364
365 RULES = [
366 starts_with(_TASK_NAME_PREFIX),
367 allowed_characters(*_TASK_NAME_CHARACTERS),
368 not_starts_with('_cylc'),
369 not_equals('root'),
370 ]