| 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 deepcopy |
| 18 |
import re |
| 19 |
from textwrap import dedent |
| 20 |
from typing import TYPE_CHECKING, Callable, Iterable, List, Optional |
| 21 |
|
| 22 |
from cylc.flow.context_node import ContextNode |
| 23 |
from cylc.flow.parsec.exceptions import ( |
| 24 |
ItemNotFoundError, |
| 25 |
NotSingleItemError, |
| 26 |
InvalidConfigError |
| 27 |
) |
| 28 |
from cylc.flow.parsec.fileparse import parse |
| 29 |
from cylc.flow.parsec.util import printcfg |
| 30 |
from cylc.flow.parsec.validate import parsec_validate, ParsecValidator as VDR |
| 31 |
from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults |
| 32 |
from cylc.flow.parsec.util import itemstr, m_override, replicate, un_many |
| 33 |
|
| 34 |
if TYPE_CHECKING: |
| 35 |
from optparse import Values |
| 36 |
|
| 37 |
|
| 38 |
class DefaultList(list): |
| 39 |
"""List subclass to indicate unassigned list values in expanded config.""" |
| 40 |
|
| 41 |
|
| 42 |
class ParsecConfig: |
| 43 |
"""Object wrapper for parsec functions.""" |
| 44 |
|
| 45 |
def __init__( |
| 46 |
self, |
| 47 |
spec: 'ConfigNode', |
| 48 |
upgrader: Callable | None = None, |
| 49 |
output_fname: str | None = None, |
| 50 |
tvars: dict | None = None, |
| 51 |
validator: Callable | None = None, |
| 52 |
options: 'Values | None' = None |
| 53 |
): |
| 54 |
"""Instatiate a parsec config object. |
| 55 |
|
| 56 |
Args: |
| 57 |
spec: Specification for the config. |
| 58 |
upgrader: An upgrader function, which converts old config items |
| 59 |
to new ones, or returns errors for obsolete items. |
| 60 |
output_fname: Filename to dump parsed config to. |
| 61 |
tvars: Template variables. |
| 62 |
validator: Function checkin that config is valid; defaults to |
| 63 |
``parsec_validate``. |
| 64 |
options: Command line options. |
| 65 |
""" |
| 66 |
self.sparse = OrderedDictWithDefaults() |
| 67 |
self.dense = OrderedDictWithDefaults() |
| 68 |
self.upgrader = upgrader |
| 69 |
self.tvars = tvars |
| 70 |
self.output_fname = output_fname |
| 71 |
self.spec = spec |
| 72 |
if validator is None: |
| 73 |
validator = parsec_validate |
| 74 |
self.validator = validator |
| 75 |
# Get a list of config items which have a private name ``__MANY__``: |
| 76 |
self.manyparents = self._get_namespace_parents() |
| 77 |
self.options = options |
| 78 |
|
| 79 |
def loadcfg(self, rcfile, title=""): |
| 80 |
"""Parse a config file, upgrade or deprecate items if necessary, |
| 81 |
validate it against the spec, and if this is not the first load, |
| 82 |
combine/override with the existing loaded config.""" |
| 83 |
|
| 84 |
sparse = parse( |
| 85 |
rcfile, self.output_fname, self.tvars, opts=self.options) |
| 86 |
|
| 87 |
if self.upgrader is not None: |
| 88 |
self.upgrader(sparse, title) |
| 89 |
|
| 90 |
self.validate(sparse) |
| 91 |
|
| 92 |
if not self.sparse: |
| 93 |
self.sparse = sparse |
| 94 |
else: |
| 95 |
# Already loaded, override with new items. |
| 96 |
replicate(self.sparse, sparse) |
| 97 |
|
| 98 |
def validate(self, sparse): |
| 99 |
"""Validate sparse config against the file spec.""" |
| 100 |
return self.validator(sparse, self.spec) |
| 101 |
|
| 102 |
def expand(self) -> None: |
| 103 |
"""Flesh out undefined items with defaults, if any, from the spec.""" |
| 104 |
if not self.dense: |
| 105 |
dense = OrderedDictWithDefaults() |
| 106 |
# Populate dict with default values from the spec |
| 107 |
stack = [(dense, self.spec)] |
| 108 |
while stack: |
| 109 |
defs, spec = stack.pop() |
| 110 |
node: ConfigNode |
| 111 |
for node in spec: |
| 112 |
if not node.is_leaf(): |
| 113 |
if node.name not in defs: |
| 114 |
defs[node.name] = OrderedDictWithDefaults() |
| 115 |
stack.append((defs[node.name], node)) |
| 116 |
else: |
| 117 |
if node.default == ConfigNode.UNSET: |
| 118 |
if node.vdr and node.vdr.endswith('_LIST'): |
| 119 |
defs[node.name] = DefaultList() |
| 120 |
else: |
| 121 |
defs[node.name] = None |
| 122 |
else: |
| 123 |
defs[node.name] = node.default |
| 124 |
# override defaults with sparse values |
| 125 |
m_override(dense, self.sparse) |
| 126 |
un_many(dense) |
| 127 |
self.dense = dense |
| 128 |
|
| 129 |
def get(self, keys: Optional[Iterable[str]] = None, sparse: bool = False): |
| 130 |
"""Retrieve items or sections, sparse or dense, by list of keys: |
| 131 |
[sec1,sec2,item] => |
| 132 |
[sec1] |
| 133 |
[[sec2]] |
| 134 |
item = value |
| 135 |
|
| 136 |
NOTE: Side effect when sparse is False: the config gets expanded |
| 137 |
(if not previously expanded). |
| 138 |
""" |
| 139 |
if sparse: |
| 140 |
cfg = self.sparse |
| 141 |
else: |
| 142 |
self.expand() |
| 143 |
cfg = self.dense |
| 144 |
|
| 145 |
parents: List[str] = [] |
| 146 |
if keys: |
| 147 |
for key in keys: |
| 148 |
try: |
| 149 |
cfg = cfg[key] |
| 150 |
except (KeyError, TypeError): |
| 151 |
if ( |
| 152 |
# __MANY__ setting not present: |
| 153 |
parents in self.manyparents or |
| 154 |
# setting not present in __MANY__ section: |
| 155 |
key in self.spec.get(*parents) |
| 156 |
): |
| 157 |
raise ItemNotFoundError( |
| 158 |
itemstr(parents, key) |
| 159 |
) from None |
| 160 |
raise InvalidConfigError( |
| 161 |
itemstr(parents, key), self.spec.name |
| 162 |
) from None |
| 163 |
else: |
| 164 |
parents.append(key) |
| 165 |
|
| 166 |
return cfg |
| 167 |
|
| 168 |
def idump(self, items=None, sparse=False, prefix='', |
| 169 |
oneline=False, none_str='', handle=None): |
| 170 |
""" |
| 171 |
items is a list of --item style inputs: |
| 172 |
'[runtime][foo]script'. |
| 173 |
""" |
| 174 |
mkeys = [] |
| 175 |
null = True |
| 176 |
if items: |
| 177 |
for i in items: |
| 178 |
null = False |
| 179 |
i = i.lstrip('[') |
| 180 |
i = i.rstrip(']') |
| 181 |
j = re.split(r'\]\[*', i) |
| 182 |
mkeys.append(j) |
| 183 |
if null: |
| 184 |
mkeys = [[]] |
| 185 |
self.mdump(mkeys, sparse, prefix, oneline, none_str, handle=handle) |
| 186 |
|
| 187 |
def mdump(self, mkeys=None, sparse=False, prefix='', |
| 188 |
oneline=False, none_str='', handle=None): |
| 189 |
if oneline: |
| 190 |
items = [] |
| 191 |
if mkeys: |
| 192 |
for keys in mkeys: |
| 193 |
item = self.get(keys, sparse) |
| 194 |
if isinstance(item, (list, dict)): |
| 195 |
raise NotSingleItemError(itemstr(keys)) |
| 196 |
if not item: |
| 197 |
item = none_str or "None" |
| 198 |
items.append(str(item)) |
| 199 |
# TODO - quote items if they contain spaces or comment delimiters? |
| 200 |
print(prefix + ' '.join(items)) |
| 201 |
elif mkeys: |
| 202 |
for keys in mkeys: |
| 203 |
self.dump(keys, sparse, prefix, none_str, handle=handle) |
| 204 |
|
| 205 |
def dump( |
| 206 |
self, keys=None, sparse=False, prefix='', none_str='', handle=None |
| 207 |
): |
| 208 |
if not keys: |
| 209 |
keys = [] |
| 210 |
cfg = self.get(keys, sparse) |
| 211 |
printcfg( |
| 212 |
cfg, prefix=prefix, level=len(keys), |
| 213 |
none_str=none_str, handle=handle |
| 214 |
) |
| 215 |
|
| 216 |
def _get_namespace_parents(self) -> List[List[str]]: |
| 217 |
"""Get a list of the parents of config items which can be user defined. |
| 218 |
|
| 219 |
For example, where |
| 220 |
|
| 221 |
.. code-block:: cylc |
| 222 |
|
| 223 |
[runtime] |
| 224 |
[[my_task]] # Custom task names. |
| 225 |
[[my_other_task]] |
| 226 |
|
| 227 |
this function will return ``[runtime]``. |
| 228 |
""" |
| 229 |
try: |
| 230 |
return [ |
| 231 |
[parent.name for parent in key.parents()][-2::-1] |
| 232 |
# that slice removes the top-level name and reverses |
| 233 |
for _, key in self.spec.walk() |
| 234 |
if key.name == '__MANY__' |
| 235 |
] |
| 236 |
except AttributeError: |
| 237 |
return [] |
| 238 |
|
| 239 |
|
| 240 |
class ConfigNode(ContextNode): |
| 241 |
"""A Cylc configuration schema, section, or setting. |
| 242 |
|
| 243 |
Attributes: |
| 244 |
vdr: |
| 245 |
The config type (i.e. parsec validator). |
| 246 |
options: |
| 247 |
List of possible options. |
| 248 |
TODO: allow this to be a dict with help info |
| 249 |
depr_options: |
| 250 |
List of deprecated options. These are not displayed in the docs |
| 251 |
but are used for backwards compatibility. |
| 252 |
warn_options: |
| 253 |
If True, parsec will warn if invalid options are present rather |
| 254 |
than raising an exception. Any invalid options will be stripped |
| 255 |
from the config. |
| 256 |
default: |
| 257 |
The default value. |
| 258 |
desc: |
| 259 |
A description of the config. |
| 260 |
Note this gets dedented and stripped. |
| 261 |
display_name: |
| 262 |
This is the user-facing name of the config. |
| 263 |
Note the regular ``name`` might be ``__MANY__``. |
| 264 |
meta: |
| 265 |
Another ConfigNode to use as a template for this one. |
| 266 |
|
| 267 |
This is useful if you want to create a specific instance of |
| 268 |
a generic configuration e.g. ``[elephant]`` from ``[<animal>]``. |
| 269 |
|
| 270 |
Leaf nodes inherited from the generic config wil have |
| 271 |
``meta=True``. |
| 272 |
|
| 273 |
""" |
| 274 |
|
| 275 |
ROOT_NAME_FMT = '{display_name}' |
| 276 |
NODE_NAME_FMT = '[{display_name}]' |
| 277 |
LEAF_NAME_FMT = '{display_name}' |
| 278 |
SEP = '' |
| 279 |
|
| 280 |
UNSET = '*value unset*' |
| 281 |
|
| 282 |
__slots__ = ContextNode.__slots__ + ( |
| 283 |
'vdr', |
| 284 |
'options', |
| 285 |
'depr_options', |
| 286 |
'warn_options', |
| 287 |
'default', |
| 288 |
'desc', |
| 289 |
'display_name', |
| 290 |
'meta', |
| 291 |
) |
| 292 |
|
| 293 |
def __init__( |
| 294 |
self, |
| 295 |
name: str, |
| 296 |
vdr: str = VDR.V_STRING, |
| 297 |
default: object = UNSET, |
| 298 |
options: Optional[list] = None, |
| 299 |
desc: Optional[str] = None, |
| 300 |
meta: Optional['ConfigNode'] = None, |
| 301 |
depr_options: Optional[list] = None, |
| 302 |
warn_options: bool = False, |
| 303 |
): |
| 304 |
display_name = name |
| 305 |
if name.startswith('<'): |
| 306 |
# if we use <...> as the name, this is a user-definable config |
| 307 |
# * we set the name (for internal use) to __MANY__ |
| 308 |
# * we leave the display_name (for external use) unchanged |
| 309 |
name = '__MANY__' |
| 310 |
|
| 311 |
ContextNode.__init__(self, name) |
| 312 |
|
| 313 |
if meta: |
| 314 |
# inherit items from the template configuration |
| 315 |
self._children = deepcopy(meta._children) |
| 316 |
if self._children: |
| 317 |
for child in self._children.values(): |
| 318 |
# record that these configurations have been inherited |
| 319 |
# (this is used to prevent documenting settings twice) |
| 320 |
child.meta = True |
| 321 |
|
| 322 |
self.display_name = display_name |
| 323 |
self.vdr = vdr |
| 324 |
self.default = default |
| 325 |
self.options = options or [] |
| 326 |
self.depr_options = depr_options or [] |
| 327 |
self.warn_options = warn_options |
| 328 |
self.desc = dedent(desc).strip() if desc else None |
| 329 |
self.meta = meta |
| 330 |
|
| 331 |
def __repr__(self): |
| 332 |
parents = list(self.parents()) |
| 333 |
itr = list(reversed(list(parents))) + [self] |
| 334 |
if len(parents) == 1 and self.is_leaf(): |
| 335 |
itr.insert(1, '|') |
| 336 |
return ''.join(map(str, itr)) |