Debian Codegraph @

cylc/flow/templatevars.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 """Load custom variables for template processor."""
17
18 from ast import literal_eval
19 from typing import Any, Dict, List, Optional, Set, Union, TYPE_CHECKING
20
21 from cylc.flow import LOG
22 from cylc.flow.exceptions import InputError
23 from cylc.flow.rundb import CylcWorkflowDAO
24 from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
25 from cylc.flow.workflow_files import WorkflowFiles
26
27 if TYPE_CHECKING:
28 from optparse import Values
29 from pathlib import Path
30
31
32 OVERWRITE_WARNING = (
33 'Template variable {} redefined:'
34 ' the previous value will be overwritten.'
35 )
36
37
38 def get_template_vars_from_db(run_dir: 'Path') -> dict:
39 """Get template vars stored in a workflow run database.
40 """
41 pub_db_file = (
42 run_dir / WorkflowFiles.LogDir.DIRNAME / WorkflowFiles.LogDir.DB
43 )
44 template_vars: dict = {}
45 if not pub_db_file.exists():
46 return template_vars
47 WorkflowDatabaseManager.check_db_compatibility(pub_db_file)
48 with CylcWorkflowDAO(pub_db_file, is_public=True) as dao:
49 dao.select_workflow_template_vars(
50 lambda _, row: template_vars.__setitem__(row[0], eval_var(row[1]))
51 )
52 return template_vars
53
54
55 def eval_var(var):
56 """Wrap ast.literal_eval to provide more helpful error.
57
58 Examples:
59 >>> eval_var('42')
60 42
61 >>> eval_var('"string"')
62 'string'
63 >>> eval_var('string')
64 Traceback (most recent call last):
65 cylc.flow.exceptions.InputError: Invalid template variable: string
66 (note string values must be quoted)
67 >>> eval_var('[')
68 Traceback (most recent call last):
69 cylc.flow.exceptions.InputError: Invalid template variable: [
70 (values must be valid Python literals)
71
72 """
73 try:
74 return literal_eval(var)
75 except ValueError:
76 raise InputError(
77 f'Invalid template variable: {var}'
78 '\n(note string values must be quoted)'
79 ) from None
80 except SyntaxError:
81 raise InputError(
82 f'Invalid template variable: {var}'
83 '\n(values must be valid Python literals)'
84 ) from None
85
86
87 def parse_string_list(stringlist: str) -> list[str]:
88 """Parse a comma separated string list into a Python string list.
89
90 Examples:
91 >>> parse_string_list('a,b,c')
92 ['a', 'b', 'c']
93 >>> parse_string_list('a,"b,b",c')
94 ['a', 'b,b', 'c']
95 >>> parse_string_list("a,'b,b','c'")
96 ['a', 'b,b', 'c']
97 """
98 list_ = []
99 in_quotes = False
100 buffer = ''
101 for char in stringlist:
102 if char in {'"', "'"}:
103 in_quotes = not in_quotes
104 elif not in_quotes and char == ',':
105 list_.append(buffer)
106 buffer = ''
107 else:
108 buffer += char
109 list_.append(buffer)
110 return list_
111
112
113 def load_template_vars(
114 template_vars: Optional[List[str]] = None,
115 template_vars_file: 'Union[Path, str, None]' = None,
116 templatevars_lists: Optional[List[str]] = None
117 ) -> Dict[str, Any]:
118 """Load template variables from key=value strings."""
119 keys: Set[str] = set()
120 invalid_vars: str = ''
121
122 # Parse Template vars set by file (-S)
123 file_tvars: Dict[str, Any] = {}
124 if template_vars_file:
125 with open(template_vars_file, 'r') as handle:
126 for line in handle:
127 line = line.strip().split("#", 1)[0]
128 if not line:
129 continue
130 try:
131 key, val = line.split("=", 1)
132 except ValueError:
133 invalid_vars += f'\n * {line}'
134 continue
135 file_tvars[key.strip()] = eval_var(val.strip())
136 keys.add(key.strip())
137
138 cli_tvars: Dict[str, Any] = {}
139 tvars_lists: dict[str, list[str]] = {}
140 for input_, result, func in (
141 (template_vars, cli_tvars, eval_var),
142 (templatevars_lists, tvars_lists, parse_string_list)
143 ):
144 for pair in input_ or []:
145 # Handle ValueError
146 try:
147 key, val = pair.split("=", 1)
148 except ValueError:
149 invalid_vars += f'\n * {pair}'
150 continue
151 key, val = key.strip(), val.strip()
152 if key in result:
153 LOG.warning(OVERWRITE_WARNING.format(key))
154 result[key] = func(val)
155 keys.add(key)
156
157 # Raise an error if there are any args without the form key=value.:
158 if invalid_vars:
159 raise InputError(
160 'Template variables must be set with key=value(s):'
161 + invalid_vars
162 )
163
164 # Explicitly record which source of tvars over-rides which.
165 res = {}
166 badkeys = ''
167 for key in keys:
168 if key in cli_tvars and key in tvars_lists:
169 badkeys += (
170 f"\n * {key}={cli_tvars[key]} and {key}={tvars_lists[key]}")
171 else:
172 res[key] = cli_tvars.get(
173 key, tvars_lists.get(
174 key, file_tvars.get(key)))
175
176 # Raise an error if there are any key-clashes between tvars and tvars_list
177 if badkeys:
178 raise InputError(
179 "You can't set the same template variable with both -s and -z:"
180 + badkeys
181 )
182
183 return res
184
185
186 def get_template_vars(options: 'Values') -> Dict[str, Any]:
187 """Convienence wrapper for ``load_template_vars``.
188
189 Args:
190 options: Options passed to the Cylc script which is using this
191 function.
192
193 Returns:
194 template_vars: Template variables to give to a Cylc config.
195 """
196 return load_template_vars(
197 options.templatevars,
198 options.templatevars_file,
199 options.templatevars_lists
200 )