Debian Codegraph @

cylc/flow/parsec/fileparse.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 parsec config file parsing:
18
19 1) inline include-files
20 2) process with Jinja2
21 3) join continuation lines
22 4) parse items into a nested ordered dict
23 * line-comments and blank lines are skipped
24 * trailing comments are stripped from section headings
25 * item value processing:
26 - original quoting is retained
27 - trailing comments are retained
28 (distinguishing between strings and string lists, with all quoting
29 and commenting options, is easier during validation when the item
30 value type is known).
31 """
32
33 from copy import deepcopy
34 import os
35 from pathlib import Path
36 import re
37 import sys
38 from typing import (
39 TYPE_CHECKING,
40 Any,
41 )
42 import warnings
43
44 from cylc.flow import (
45 LOG,
46 __version__,
47 )
48 from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults
49 from cylc.flow.parsec.exceptions import (
50 FileParseError,
51 ParsecError,
52 TemplateVarLanguageClash,
53 )
54 from cylc.flow.parsec.include import inline
55 from cylc.flow.parsec.util import itemstr
56 from cylc.flow.plugins import run_plugins
57 from cylc.flow.templatevars import get_template_vars_from_db
58 from cylc.flow.workflow_files import (
59 check_flow_file,
60 get_workflow_source_dir,
61 )
62
63
64 if TYPE_CHECKING:
65 from optparse import Values
66
67
68 # heading/sections can contain commas (namespace name lists) and any
69 # regex pattern characters (this was for pre cylc-6 satellite tasks).
70 # Proper task names are checked later in config.py.
71 _HEADING = re.compile(
72 r'''^
73 (\s*) # 1: indentation
74 ((?:\[)+) # 2: section marker open
75 \s*
76 (.+?) # 3: section name
77 \s*
78 ((?:\])+) # 4: section marker close
79 \s*(\#.*)? # 5: optional trailing comment
80 $''',
81 re.VERBOSE)
82
83 _KEY_VALUE = re.compile(
84 r'''^
85 (\s*) # indentation
86 ([\w+\-:.,!/()^$ ]+?(\s*<.*?>)?)
87 # key (and parameters, e.g. foo<m,n>)
88 \s*=\s* # =
89 (.*) # value (quoted any style + comment)
90 $ # line end
91 ''',
92 re.VERBOSE)
93
94 # Designed to match lines ending '\ ' without matching '\ comment'
95 _BAD_CONTINUATION_TRAILING_WHITESPACE = re.compile(
96 r'^([^#\n]+)?\\\s+$', re.VERBOSE)
97
98 # quoted value regex reference:
99 # http://stackoverflow.com/questions/5452655/
100 # python-regex-to-match-text-in-single-quotes-
101 # ignoring-escaped-quotes-and-tabs-n
102
103 _LINECOMMENT = re.compile(r'^\s*#')
104 _BLANKLINE = re.compile(r'^\s*$')
105
106 # triple quoted values on one line
107 _SINGLE_LINE_SINGLE = re.compile(r"^'''(.*?)'''\s*(#.*)?$")
108 _SINGLE_LINE_DOUBLE = re.compile(r'^"""(.*?)"""\s*(#.*)?$')
109 _MULTI_LINE_SINGLE = re.compile(r"^(.*?)'''\s*(#.*)?$")
110 _MULTI_LINE_DOUBLE = re.compile(r'^(.*?)"""\s*(#.*)?$')
111
112 _TRIPLE_QUOTE = {
113 "'''": (_SINGLE_LINE_SINGLE, _MULTI_LINE_SINGLE),
114 '"""': (_SINGLE_LINE_DOUBLE, _MULTI_LINE_DOUBLE),
115 }
116
117 _UNCLOSED_MULTILINE = re.compile(
118 r'(?<![\w>])\[.*\]'
119 )
120 TEMPLATING_DETECTED = 'templating_detected'
121 TEMPLATE_VARIABLES = 'template_variables'
122 EXTRA_VARS_TEMPLATE: dict[str, Any] = {
123 'env': {},
124 TEMPLATE_VARIABLES: {},
125 TEMPLATING_DETECTED: None
126 }
127
128 _J2_WARN_LOCS = re.compile(rf'jinja2{re.escape(os.sep)}(lexer|runtime)\.py$')
129
130
131 def get_cylc_env_vars() -> dict[str, str]:
132 """Return a restricted dict of CYLC_ environment variables for templating.
133
134 The following variables are ignored because the do not necessarily reflect
135 the running code version (I might not use the "cylc" wrapper, or it might
136 select a different version):
137
138 CYLC_VERSION
139 Set as a template variable elsewhere, from the hardwired code version.
140
141 CYLC_ENV_NAME
142 Providing it as a template variable would just be misleading.
143 """
144 return {
145 key: val
146 for key, val in os.environ.items()
147 if key.startswith('CYLC_')
148 if key not in ["CYLC_VERSION", "CYLC_ENV_NAME"]
149 }
150
151
152 def _concatenate(lines):
153 """concatenate continuation lines"""
154 index = 0
155 clines = []
156 maxline = len(lines)
157 while index < maxline:
158 line = lines[index]
159 # Raise an error if line has a whitespace after the line break
160 if re.match(_BAD_CONTINUATION_TRAILING_WHITESPACE, line):
161 msg = ("Syntax error line {0}: Whitespace after the line "
162 "continuation character (\\).")
163 raise FileParseError(msg.format(index + 1))
164 while line.endswith('\\'):
165 if index == maxline - 1:
166 # continuation char on the last line
167 # must be an error - safe to strip it
168 line = line[:-1]
169 else:
170 index += 1
171 line = line[:-1] + lines[index]
172 clines.append(line)
173 index += 1
174 return clines
175
176
177 def addsect(cfig, sname, parents):
178 """Add a new section to a nested dict, if it doesn't exist."""
179 for p in parents:
180 # drop down the parent list
181 cfig = cfig[p]
182 if sname not in cfig:
183 cfig[sname] = OrderedDictWithDefaults()
184
185
186 def addict(cfig, key, val, parents, index):
187 """Add a new [parents...]key=value pair to a nested dict."""
188 for p in parents:
189 # drop down the parent list
190 cfig = cfig[p]
191
192 if not isinstance(cfig, dict):
193 # an item of this name has already been encountered at this level
194 raise FileParseError(
195 'line %d: already encountered %s',
196 index, itemstr(parents, key, val))
197
198 if key in cfig:
199 oldval = cfig[key]
200 # this item already exists
201 if (
202 parents[0:2] == ['scheduling', 'graph'] or
203 # BACK COMPAT: [scheduling][dependencies]
204 # url:
205 # https://github.com/cylc/cylc-flow/pull/3191
206 # from:
207 # Cylc<=7
208 # to:
209 # Cylc8
210 # remove at:
211 # Cylc8.x
212 parents[0:2] == ['scheduling', 'dependencies']
213 ):
214 # append the new graph string to the existing one
215 if not isinstance(cfig, list):
216 cfig[key] = [cfig[key]]
217 cfig[key].append(val)
218 else:
219 cfig[key] = val
220 LOG.debug(
221 '%s: already exists in configuration:\nold: %s\nnew: %s',
222 key, repr(oldval), repr(cfig[key])) # repr preserves \n
223 else:
224 cfig[key] = val
225
226
227 def multiline(flines, value, index, maxline):
228 """Consume lines for multiline strings."""
229 o_index = index
230 quot = value[:3]
231 newvalue = value[3:]
232
233 # could be a triple-quoted single line:
234 single_line = _TRIPLE_QUOTE[quot][0]
235 multi_line = _TRIPLE_QUOTE[quot][1]
236 mat = single_line.match(value)
237 if mat:
238 return value, index
239 elif newvalue.find(quot) != -1:
240 # TODO - this should be handled by validation?:
241 # e.g. non-comment follows single-line triple-quoted string
242 raise FileParseError('Invalid line', o_index, flines[index])
243
244 while index < maxline:
245 index += 1
246 newvalue += '\n'
247 line = flines[index]
248 if line.find(quot) == -1:
249 newvalue += line
250 else:
251 # end of multiline, process it
252 break
253 else:
254 raise FileParseError(
255 'Multiline string not closed', o_index, flines[o_index])
256
257 mat = multi_line.match(line)
258 if not mat:
259 # e.g. end multi-line string followed by a non-comment
260 raise FileParseError('Invalid line', o_index, line)
261
262 # value, comment = mat.groups()
263 return quot + newvalue + line, index
264
265
266 def process_plugins(fpath: 'str | Path', opts: 'Values'):
267 """Run a Cylc pre-configuration plugin.
268
269 Plugins should return a dictionary containing:
270 'env': A dictionary of environment variables.
271 'template_variables': A dictionary of template variables.
272 'templating_detected': Where the plugin identifies a templating
273 language this is specified here.
274
275 args:
276 fpath: Path to a config file. Plugin will look at the parent
277 directory of this file.
278 opts: Command line options to be passed to the plugin.
279
280 Returns: Dictionary in the form:
281 extra_vars = {
282 'env': {},
283 'template_variables': {},
284 TEMPLATING_DETECTED: None
285 }
286 """
287 fpath = Path(fpath)
288
289 # Set out blank dictionary for return:
290 extra_vars = deepcopy(EXTRA_VARS_TEMPLATE)
291
292 # Don't run this on global configs:
293 if fpath.name == 'global.cylc':
294 return extra_vars
295
296 # Run entry point pre_configure items, trying to merge values with each.:
297 for entry_point, plugin_result in run_plugins(
298 'cylc.pre_configure',
299 srcdir=fpath.parent,
300 opts=opts,
301 ):
302 for section in ['env', TEMPLATE_VARIABLES]:
303 if section in plugin_result and plugin_result[section] is not None:
304 # Raise error if multiple plugins try to update the same keys.
305 section_update = plugin_result.get(section, {})
306 keys_collision = (
307 extra_vars[section].keys() & section_update.keys()
308 )
309 if keys_collision:
310 raise ParsecError(
311 f"{entry_point.name} is trying to alter "
312 f"[{section}]{', '.join(sorted(keys_collision))}."
313 )
314 extra_vars[section].update(section_update)
315
316 templating_detected = plugin_result.get(TEMPLATING_DETECTED, None)
317 if (
318 templating_detected is not None
319 and extra_vars[TEMPLATING_DETECTED] is not None
320 and extra_vars[TEMPLATING_DETECTED] != templating_detected
321 ):
322 # Don't allow subsequent plugins with different templating_detected
323 raise ParsecError(
324 "Can't merge templating languages "
325 f"{extra_vars[TEMPLATING_DETECTED]} and "
326 f"{templating_detected}"
327 )
328 else:
329 extra_vars[TEMPLATING_DETECTED] = templating_detected
330
331 return extra_vars
332
333
334 def merge_template_vars(
335 native_tvars: dict[str, Any],
336 plugin_result: dict[str, Any]
337 ) -> dict[str, Any]:
338 """Manage the merger of Cylc Native and Plugin template variables.
339
340 Args:
341 native_tvars: Template variables set on the Cylc command line
342 using ``-s`` or a template variable file.
343 plugin_result: Plugin result which should contain _at least_
344 "templating_detected" and "template_variable" keys.
345
346 Returns:
347 template_variables.
348
349 Strategy:
350 template variables set in a Cylc Native way should override
351 the results of plugins.
352
353 Examples:
354 >>> a = {'FOO': 42, 'BAR': 'Hello World'}
355 >>> tvars = {'FOO': 24, 'BAZ': 3.14159}
356 >>> b = {'templating_detected': 'any', 'template_variables': tvars}
357 >>> merge_template_vars(a, b)
358 {'FOO': 42, 'BAZ': 3.14159, 'BAR': 'Hello World'}
359 """
360 if plugin_result[TEMPLATING_DETECTED] is not None:
361 plugin_tvars = plugin_result[TEMPLATE_VARIABLES]
362 will_be_overwritten = (
363 native_tvars.keys() &
364 plugin_tvars.keys()
365 )
366 for key in will_be_overwritten:
367 if plugin_tvars[key] != native_tvars[key]:
368 LOG.warning(
369 f'Overriding {key}: {plugin_tvars[key]} ->'
370 f' {native_tvars[key]}'
371 )
372 plugin_tvars.update(native_tvars)
373 return plugin_tvars
374 else:
375 return native_tvars
376
377
378 def _prepend_old_templatevars(
379 fpath: str, template_vars: dict[str, Any]
380 ) -> dict[str, Any]:
381 """If the fpath is in a rundir, extract template variables from database.
382
383 Args:
384 fpath: filepath of workflow config file.
385 template_vars: Template vars to prepend old tvars to.
386 """
387 rundir = Path(fpath).parent
388 old_tvars = get_template_vars_from_db(rundir)
389 old_tvars.update(template_vars)
390 template_vars = old_tvars
391 return template_vars
392
393
394 def _get_fpath_for_source(fpath: str, opts: "Values") -> str:
395 """If `--against-source` is set and a sourcedir can be found, return
396 sourcedir.
397 Else return fpath unchanged.
398
399 Raises:
400 ParsecError: If validate against source is set and this is not
401 an installed workflow then we don't want to continue.
402 """
403 if getattr(opts, 'against_source', False):
404 thispath = Path(fpath)
405 source_dir = get_workflow_source_dir(thispath.parent)[0]
406 if source_dir:
407 retpath = check_flow_file(source_dir)
408 return str(retpath)
409 else:
410 raise ParsecError(
411 f'Cannot validate {thispath.parent} against source: '
412 'it is not an installed workflow.')
413 else:
414 return fpath
415
416
417 def read_and_proc(
418 fpath: str,
419 template_vars: dict[str, Any] | None = None,
420 viewcfg: Any = None,
421 opts: Any = None,
422 ) -> list[str]:
423 """
424 Read a cylc parsec config file (at fpath), inline any include files,
425 process with Jinja2, and concatenate continuation lines.
426 Jinja2 processing must be done before concatenation - it could be
427 used to generate continuation lines.
428 """
429 template_vars = template_vars if template_vars is not None else {}
430 template_vars = _prepend_old_templatevars(fpath, template_vars)
431 fpath = _get_fpath_for_source(fpath, opts)
432 fdir = os.path.dirname(fpath)
433
434 try:
435 original_cwd = os.getcwd()
436 except FileNotFoundError:
437 # User's current working directory does not actually exist, so we won't
438 # be able to change back to it later. (Note this might not be enough to
439 # prevent file parsing commands failing due to missing cwd elsewhere in
440 # the Python library).
441 original_cwd = None
442
443 # Move to the file location to give the template processor easy access to
444 # other files in the workflow directory (whether source or installed).
445 os.chdir(fdir)
446
447 # Allow Python modules in lib/python/ (e.g. for use by Jinja2 filters).
448 workflow_lib_python = os.path.join(fdir, "lib", "python")
449 if (
450 os.path.isdir(workflow_lib_python)
451 and workflow_lib_python not in sys.path
452 ):
453 sys.path.append(workflow_lib_python)
454
455 LOG.debug('Reading file %s', fpath)
456
457 # read the file into a list, stripping newlines
458 with open(fpath) as f:
459 flines = [line.rstrip('\n') for line in f]
460
461 do_inline = True
462 do_jinja2 = True
463 do_contin = True
464
465 extra_vars = process_plugins(fpath, opts)
466
467 if not template_vars:
468 template_vars = {}
469
470 if viewcfg:
471 if not viewcfg['jinja2']:
472 do_jinja2 = False
473 if not viewcfg['contin']:
474 do_contin = False
475 if not viewcfg['inline']:
476 do_inline = False
477
478 # inline any cylc include-files
479 if do_inline:
480 flines = inline(
481 flines, fdir, fpath, viewcfg=viewcfg)
482
483 # Add the hardwired code version to template vars as CYLC_VERSION
484 template_vars['CYLC_VERSION'] = __version__
485 template_vars = merge_template_vars(template_vars, extra_vars)
486 template_vars['CYLC_TEMPLATE_VARS'] = template_vars
487
488 # Add CYLC_WORKFLOW_SRC_DIR to template variables.
489 sourcepath = get_workflow_source_dir(Path(fpath).parent)[1]
490 template_vars['CYLC_WORKFLOW_SRC_DIR'] = (
491 sourcepath.readlink() if sourcepath else Path(fpath).parent)
492
493 # Fail if templating_detected ≠ hashbang
494 process_with = hashbang_and_plugin_templating_clash(
495 extra_vars[TEMPLATING_DETECTED], flines
496 )
497
498 # process with Jinja2
499 if do_jinja2:
500 if extra_vars[TEMPLATING_DETECTED] == 'jinja2' and not process_with:
501 flines.insert(0, '#!jinja2')
502
503 if flines and re.match(r'^#![jJ]inja2\s*', flines[0]):
504 LOG.debug('Processing with Jinja2')
505 try:
506 from cylc.flow.parsec.jinja2support import jinja2process
507 except ImportError:
508 raise ParsecError(
509 'Jinja2 Python package must be installed '
510 'to process file: ' + fpath
511 ) from None
512 with warnings.catch_warnings(
513 record=True, action='default'
514 ) as warns:
515 flines = jinja2process(
516 fpath, flines, fdir, template_vars
517 )
518 for w in warns:
519 if _J2_WARN_LOCS.search(w.filename):
520 # Warning originating from processing of a jinja2 template.
521 # Unfortunately, we can't know exactly where it originated,
522 # so just set the config filename and vague line "number":
523 w.filename = fpath
524 w.lineno = '<jinja2 template>' # type: ignore
525 if warns:
526 LOG.warning(
527 "The following warnings were raised during Jinja2 "
528 "preprocessing (note: any Jinja 3.1 deprecations will "
529 "break at Cylc 8.7):\n"
530 + "\n".join(
531 warnings.formatwarning(
532 w.message, w.category, w.filename, w.lineno
533 )
534 for w in warns
535 )
536 )
537
538 # concatenate continuation lines
539 if do_contin:
540 flines = _concatenate(flines)
541
542 # If the user's original working directory exists, change back to it.
543 if original_cwd is not None:
544 os.chdir(original_cwd)
545
546 # return rstripped lines
547 return [fl.rstrip() for fl in flines]
548
549
550 def hashbang_and_plugin_templating_clash(
551 templating: str, flines: list[str]
552 ) -> str | None:
553 """Return file's hashbang/shebang, but raise TemplateVarLanguageClash
554 if plugin-set template engine and hashbang do not match.
555
556 Args:
557 templating: Template engine set by a plugin.
558 flines: The lines of text from file.
559
560 Returns:
561 The hashbang, in lower case.
562
563 Examples:
564 - Hashbang and templating_detected match:
565 >>> thisfunc = hashbang_and_plugin_templating_clash
566 >>> thisfunc('jinja2', ['#!Jinja2', 'stuff'])
567 'jinja2'
568
569 - Function returns nothing:
570 >>> thisfunc('', [''])
571
572 - Function raises if templating engines clash:
573 >>> thisfunc('other', ['#!jinja2'])
574 Traceback (most recent call last):
575 ...
576 cylc.flow.parsec.exceptions.TemplateVarLanguageClash: ...
577 """
578 hashbang: str | None = None
579 # Get hashbang if possible:
580 if flines:
581 match = re.match(r'^#!(\S+)', flines[0])
582 if match:
583 hashbang = match[1].lower()
584 if (
585 hashbang and templating
586 and templating != 'template variables'
587 and hashbang != templating
588 ):
589 raise TemplateVarLanguageClash(
590 f"A plugin set the templating engine to {templating}"
591 f" which does not match {flines[0]} set in flow.cylc."
592 )
593 return hashbang
594
595
596 def parse(
597 fpath: str,
598 output_fname: str | None = None,
599 template_vars: dict[str, Any] | None = None,
600 opts: Any = None,
601 ) -> OrderedDictWithDefaults:
602 """Parse file items line-by-line into a corresponding nested dict."""
603
604 # read and process the file (jinja2, include-files, line continuation)
605 flines = read_and_proc(fpath, template_vars, opts=opts)
606 if output_fname:
607 with open(output_fname, 'w') as handle:
608 handle.write('\n'.join(flines) + '\n')
609 LOG.debug('Processed configuration dumped: %s', output_fname)
610
611 nesting_level = 0
612 config = OrderedDictWithDefaults()
613 parents: list[str] = []
614
615 maxline = len(flines) - 1
616 index = -1
617
618 while index < maxline:
619 index += 1
620 line = flines[index]
621
622 if re.match(_LINECOMMENT, line):
623 # skip full-line comments
624 continue
625
626 if re.match(_BLANKLINE, line):
627 # skip blank lines
628 continue
629
630 m = re.match(_HEADING, line)
631 if m:
632 # matched a section heading
633 s_open, sect_name, s_close = m.groups()[1:-1]
634 nb = len(s_open)
635
636 if nb != len(s_close):
637 raise FileParseError('bracket mismatch', index, line)
638 elif nb == nesting_level:
639 # sibling section
640 parents = parents[:-1] + [sect_name]
641 elif nb == nesting_level + 1:
642 # child section
643 parents = parents + [sect_name]
644 elif nb < nesting_level: # noqa: SIM106
645 # back up one or more levels
646 ndif = nesting_level - nb
647 parents = parents[:-ndif - 1] + [sect_name]
648 else:
649 raise FileParseError('Error line', index=index, line=line)
650 nesting_level = nb
651 addsect(config, sect_name, parents[:-1])
652
653 else:
654 m = re.match(_KEY_VALUE, line)
655 if m:
656 # matched a key=value item
657 key, _, val = m.groups()[1:]
658 if val.startswith('"""') or val.startswith("'''"):
659 # triple quoted - may be a multiline value
660 val, index = multiline(flines, val, index, maxline)
661 addict(config, key, val, parents, index)
662 else:
663 # no match
664 help_lines = None
665 if 'val' in locals() and _UNCLOSED_MULTILINE.search(val):
666 # this might be an unclosed multiline string
667 # provide a helpful error message
668 key_name = ''.join(
669 [f'[{parent}]' for parent in parents]
670 ) + key
671 help_lines = [f'Did you forget to close {key_name}?']
672 raise FileParseError(
673 'Invalid line',
674 index=index,
675 line=line,
676 help_lines=help_lines
677 )
678
679 return config