| 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 |
"""Utility functions for printing and manipulating PARSEC NESTED DICTS. |
| 17 |
|
| 18 |
The copy and override functions below assume values are either dicts |
| 19 |
(nesting) or shallow collections of simple types. |
| 20 |
""" |
| 21 |
|
| 22 |
from copy import copy |
| 23 |
from collections import deque |
| 24 |
import re |
| 25 |
import sys |
| 26 |
|
| 27 |
from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults |
| 28 |
|
| 29 |
|
| 30 |
def intlistjoin(lst): |
| 31 |
"""Return dump string for int list. |
| 32 |
|
| 33 |
Attempt grouping on sequences with 3 or more numbers: |
| 34 |
* Consider sequential int values in list, group them together in |
| 35 |
`START..END[..STEP]` syntax where relevant. |
| 36 |
* Consider same numbers in list, group them together in `N*INT` syntax. |
| 37 |
|
| 38 |
Arguments: |
| 39 |
lst (list): a list of int numbers. |
| 40 |
|
| 41 |
Return (str): |
| 42 |
The (hopefully) nicely formatted dump string. |
| 43 |
|
| 44 |
Examples: |
| 45 |
>>> intlistjoin([]) |
| 46 |
'' |
| 47 |
>>> intlistjoin([10]) |
| 48 |
'10' |
| 49 |
>>> intlistjoin([10, 10]) |
| 50 |
'10, 10' |
| 51 |
>>> intlistjoin([10, 10, 10]) |
| 52 |
'3*10' |
| 53 |
>>> intlistjoin([10, 11]) |
| 54 |
'10, 11' |
| 55 |
>>> intlistjoin([10, 11, 12]) |
| 56 |
'10..12' |
| 57 |
>>> intlistjoin([-1, 1, 3, 5, 0, 0, 0, 8, 9, 11, -1, 0, 1, 2]) |
| 58 |
'-1..5..2, 3*0, 8, 9, 11, -1..2' |
| 59 |
>>> intlistjoin([-1, 1, 3, 5, 0, 0, 0, 8, 9, 11, 11, 12]) |
| 60 |
'-1..5..2, 3*0, 8, 9, 11, 11, 12' |
| 61 |
>>> intlistjoin( |
| 62 |
... [-10, -10, -1, 1, 3, 5, 0, 0, 0, 8, 9, 11, -1, 0, 1, 2]) |
| 63 |
'-10, -10, -1..5..2, 3*0, 8, 9, 11, -1..2' |
| 64 |
>>> intlistjoin( |
| 65 |
... [64747, -10, -10, -10, -1, 1, 3, 5, 0, 0, 0, 8, 9, 11, -1, 0, |
| 66 |
... 1, 2, 3, 4, 19, 19, 19, 20, 20, 20, 21, 22, 23]) |
| 67 |
'64747, 3*-10, -1..5..2, 3*0, 8, 9, 11, -1..4, 3*19, 3*20, 21..23' |
| 68 |
""" |
| 69 |
rets = [] |
| 70 |
items = list(lst) |
| 71 |
while items: |
| 72 |
group = [items.pop(0)] |
| 73 |
while items: |
| 74 |
if (len(group) == 1 or |
| 75 |
items[0] - group[-1] == group[-1] - group[-2]): |
| 76 |
group.append(items.pop(0)) |
| 77 |
else: |
| 78 |
# If 2 numbers only, return 1 back if grouping still possible |
| 79 |
# in subsequent lots. |
| 80 |
if len(group) == 2 and len(items) >= 2: |
| 81 |
items.insert(0, group.pop()) |
| 82 |
break |
| 83 |
if len(group) <= 2: |
| 84 |
# Less than 2 numbers |
| 85 |
rets += [str(item) for item in group] |
| 86 |
elif group[1] - group[0] > 1: |
| 87 |
# Sequence of numbers with equal steps > 1 |
| 88 |
rets.append( |
| 89 |
'%d..%d..%d' % (group[0], group[-1], group[1] - group[0])) |
| 90 |
elif group[1] - group[0] == 1: |
| 91 |
# Sequence of incremental numbers |
| 92 |
rets.append('%d..%d' % (group[0], group[-1])) |
| 93 |
else: |
| 94 |
# Sequence of same number |
| 95 |
rets.append('%d*%d' % (len(group), group[0])) |
| 96 |
return ', '.join(rets) |
| 97 |
|
| 98 |
|
| 99 |
def listjoin(lst, none_str=''): |
| 100 |
"""Return string from joined list. |
| 101 |
|
| 102 |
Quote all elements if any of them contain comment or list-delimiter |
| 103 |
characters (currently quoting must be consistent across all elements). |
| 104 |
|
| 105 |
Note: multi-line values in list is not handle. |
| 106 |
""" |
| 107 |
if not lst: |
| 108 |
# empty list |
| 109 |
return none_str |
| 110 |
if len(lst) > 2 and all(isinstance(item, int) for item in lst): |
| 111 |
return intlistjoin(lst) |
| 112 |
items = [] |
| 113 |
for item in lst: |
| 114 |
if item is None: |
| 115 |
items.append(none_str) |
| 116 |
elif any(char in str(item) for char in ',#"\''): |
| 117 |
items.append(repr(item)) # will be quoted |
| 118 |
else: |
| 119 |
items.append(str(item)) |
| 120 |
return ', '.join(items) |
| 121 |
|
| 122 |
|
| 123 |
def printcfg(cfg, level=0, indent=0, prefix='', none_str='', |
| 124 |
handle=None): |
| 125 |
"""Pretty-print a parsec config item or section (nested dict). |
| 126 |
|
| 127 |
Args: |
| 128 |
cfg: The config to be printed. |
| 129 |
level: Each level of the hierarchy is printed with this many extra |
| 130 |
square brackets: E.g. if ``indent=2`` then ``[runtime]`` will be |
| 131 |
printed as ``[[[runtime]]]. |
| 132 |
indent (int): Indentation of top level sections - if set the whole |
| 133 |
document will have a left margin this many 4 space indents wide. |
| 134 |
prefix (str): Prefix each line with this. |
| 135 |
none_str (str): Value to insert instead of blank if no value is set in |
| 136 |
config. |
| 137 |
handle (stream handler): Where to write the output. |
| 138 |
|
| 139 |
As returned by parse.config.get(). |
| 140 |
""" |
| 141 |
# Note: default handle=sys.stdout, but explicitly setting this as a kwarg |
| 142 |
# interferes with pytest capsys: |
| 143 |
# https://github.com/pytest-dev/pytest/issues/1132#issuecomment-147506107 |
| 144 |
if handle is None: |
| 145 |
handle = sys.stdout |
| 146 |
stack = [("", cfg, level, indent)] |
| 147 |
while stack: |
| 148 |
key_i, cfg_i, level_i, indent_i = stack.pop() |
| 149 |
spacer = " " * 4 * (indent_i - 1) |
| 150 |
if isinstance(cfg_i, dict): |
| 151 |
if not cfg_i and none_str is None: |
| 152 |
# Don't print empty sections if none_str is None. This does not |
| 153 |
# handle sections with no items printed because the values of |
| 154 |
# all items are empty or None. |
| 155 |
continue |
| 156 |
if key_i and level_i: |
| 157 |
# Print heading |
| 158 |
msg = "%s%s%s%s%s\n" % ( |
| 159 |
prefix, spacer, '[' * level_i, str(key_i), ']' * level_i) |
| 160 |
if hasattr(handle, 'mode') and 'b' in handle.mode: |
| 161 |
msg = msg.encode() |
| 162 |
handle.write(msg) |
| 163 |
|
| 164 |
# Nested sections are printed after normal settings |
| 165 |
subsections = [] |
| 166 |
values = [] |
| 167 |
for key, item in cfg_i.items(): |
| 168 |
if isinstance(item, dict): |
| 169 |
subsections.append((key, item, level_i + 1, indent_i + 1)) |
| 170 |
else: |
| 171 |
values.append((key, item, level_i + 1, indent_i + 1)) |
| 172 |
|
| 173 |
stack += reversed(subsections) |
| 174 |
stack += reversed(values) |
| 175 |
else: |
| 176 |
key = "" |
| 177 |
if key_i: |
| 178 |
key = "%s = " % key_i |
| 179 |
if cfg_i is None: |
| 180 |
value = none_str |
| 181 |
elif isinstance(cfg_i, list): |
| 182 |
value = listjoin(cfg_i, none_str) |
| 183 |
elif "\n" in str(cfg_i) and key: |
| 184 |
value = '"""\n' |
| 185 |
for line in str(cfg_i).splitlines(True): |
| 186 |
value += spacer + " " * 4 + line |
| 187 |
value += '\n' + spacer + '"""' |
| 188 |
else: |
| 189 |
value = str(cfg_i) |
| 190 |
if value is not None: |
| 191 |
msg = "%s%s%s%s\n" % (prefix, spacer, key, value) |
| 192 |
if hasattr(handle, 'mode') and 'b' in handle.mode: |
| 193 |
msg = msg.encode() |
| 194 |
handle.write(msg) |
| 195 |
|
| 196 |
|
| 197 |
def replicate(target, source): |
| 198 |
"""Replicate source *into* target. |
| 199 |
|
| 200 |
Source elements need not exist in target already, so source overrides |
| 201 |
common elements in target and otherwise adds elements to it. |
| 202 |
""" |
| 203 |
if not source: |
| 204 |
return |
| 205 |
if hasattr(source, "defaults_"): |
| 206 |
target.defaults_ = pdeepcopy(source.defaults_) |
| 207 |
for key, val in source.items(): |
| 208 |
if isinstance(val, dict): |
| 209 |
if key not in target: |
| 210 |
target[key] = OrderedDictWithDefaults() |
| 211 |
if hasattr(val, 'defaults_'): |
| 212 |
target[key].defaults_ = pdeepcopy(val.defaults_) |
| 213 |
replicate(target[key], val) |
| 214 |
elif isinstance(val, list): |
| 215 |
target[key] = val[:] |
| 216 |
else: |
| 217 |
target[key] = val |
| 218 |
|
| 219 |
|
| 220 |
def pdeepcopy(source): |
| 221 |
"""Make a deep copy of a pdict source""" |
| 222 |
target = OrderedDictWithDefaults() |
| 223 |
replicate(target, source) |
| 224 |
return target |
| 225 |
|
| 226 |
|
| 227 |
def poverride(target, sparse, prepend=False): |
| 228 |
"""Override or add items in a target pdict. |
| 229 |
|
| 230 |
Target sub-dicts must already exist. For keys that already exist in the |
| 231 |
target, the value is overridden in-place. New keys can be prepended in the |
| 232 |
target (Cylc use case: broadcast environment variables should be defined |
| 233 |
first in the user environment section, to allow use in subsequent variable |
| 234 |
definitions. |
| 235 |
|
| 236 |
""" |
| 237 |
if not sparse: |
| 238 |
return |
| 239 |
for key, val in sparse.items(): |
| 240 |
if isinstance(val, dict): |
| 241 |
poverride(target[key], val, prepend) |
| 242 |
else: |
| 243 |
if prepend and (key not in target): |
| 244 |
# Prepend new items in the target ordered dict. |
| 245 |
setitem = target.prepend |
| 246 |
else: |
| 247 |
# Override in-place in the target ordered dict. |
| 248 |
setitem = target.__setitem__ |
| 249 |
if isinstance(val, list): |
| 250 |
setitem(key, val[:]) |
| 251 |
else: |
| 252 |
setitem(key, val) |
| 253 |
|
| 254 |
|
| 255 |
def m_override(target, sparse): |
| 256 |
"""Override items in a target pdict. |
| 257 |
|
| 258 |
Target keys must already exist unless there is a "__MANY__" placeholder in |
| 259 |
the right position. |
| 260 |
""" |
| 261 |
if not sparse: |
| 262 |
return |
| 263 |
stack = deque([(sparse, target, [], OrderedDictWithDefaults())]) |
| 264 |
defaults_list = [] |
| 265 |
while stack: |
| 266 |
source, dest, keylist, many_defaults = stack.popleft() |
| 267 |
if many_defaults: |
| 268 |
defaults_list.append((dest, many_defaults)) |
| 269 |
for key, val in source.items(): |
| 270 |
if isinstance(val, dict): |
| 271 |
child_many_defaults = many_defaults.get( |
| 272 |
key, OrderedDictWithDefaults()) |
| 273 |
if key not in dest: |
| 274 |
if '__MANY__' in dest: |
| 275 |
dest[key] = OrderedDictWithDefaults() |
| 276 |
child_many_defaults = dest['__MANY__'] |
| 277 |
elif '__MANY__' in many_defaults: |
| 278 |
# A 'sub-many' dict - would it ever exist in real life? |
| 279 |
dest[key] = OrderedDictWithDefaults() |
| 280 |
child_many_defaults = many_defaults['__MANY__'] |
| 281 |
elif key not in many_defaults: |
| 282 |
# TODO - validation prevents this, but handle properly |
| 283 |
# for completeness. |
| 284 |
raise Exception( |
| 285 |
"parsec dict override: no __MANY__ placeholder" + |
| 286 |
"%s" % (keylist + [key]) |
| 287 |
) |
| 288 |
dest[key] = OrderedDictWithDefaults() |
| 289 |
|
| 290 |
stack.append( |
| 291 |
(val, dest[key], keylist + [key], child_many_defaults)) |
| 292 |
else: |
| 293 |
if key not in dest: |
| 294 |
if not ( |
| 295 |
'__MANY__' in dest |
| 296 |
or key in many_defaults |
| 297 |
or '__MANY__' in many_defaults |
| 298 |
): |
| 299 |
# TODO - validation prevents this, but handle properly |
| 300 |
# for completeness. |
| 301 |
raise Exception( |
| 302 |
"parsec dict override: no __MANY__ placeholder" + |
| 303 |
"%s" % (keylist + [key]) |
| 304 |
) |
| 305 |
if isinstance(val, list): |
| 306 |
dest[key] = val[:] |
| 307 |
else: |
| 308 |
dest[key] = val |
| 309 |
|
| 310 |
if isinstance(val, list): |
| 311 |
dest[key] = val[:] |
| 312 |
else: |
| 313 |
dest[key] = val |
| 314 |
for dest_dict, defaults in defaults_list: |
| 315 |
dest_dict.defaults_ = defaults |
| 316 |
|
| 317 |
|
| 318 |
def un_many(cfig): |
| 319 |
"""Remove any '__MANY__' items from a nested dict, in-place.""" |
| 320 |
if not cfig: |
| 321 |
return |
| 322 |
for key, val in list(cfig.items()): |
| 323 |
if key == '__MANY__': |
| 324 |
try: |
| 325 |
del cfig[key] |
| 326 |
except KeyError: |
| 327 |
if ( |
| 328 |
not hasattr(cfig, 'defaults_') |
| 329 |
or key not in cfig.defaults_ |
| 330 |
): |
| 331 |
raise |
| 332 |
del cfig.defaults_[key] |
| 333 |
|
| 334 |
elif isinstance(val, dict): |
| 335 |
un_many(cfig[key]) |
| 336 |
|
| 337 |
|
| 338 |
def itemstr(parents=None, item=None, value=None): |
| 339 |
""" |
| 340 |
Pretty-print an item from list of sections, item name, and value |
| 341 |
E.g.: ([sec1, sec2], item, value) to '[sec1][sec2]item = value'. |
| 342 |
""" |
| 343 |
if parents: |
| 344 |
keys = copy(parents) |
| 345 |
if value and not item: |
| 346 |
# last parent is the item |
| 347 |
item = keys[-1] |
| 348 |
keys.remove(item) |
| 349 |
text = '[' + ']['.join(keys) + ']' |
| 350 |
else: |
| 351 |
text = '' |
| 352 |
if item: |
| 353 |
text += str(item) |
| 354 |
if value: |
| 355 |
text += " = " + str(value) |
| 356 |
if not text: |
| 357 |
text = str(value) |
| 358 |
|
| 359 |
return text |
| 360 |
|
| 361 |
|
| 362 |
# pattern for picking out comma separated items which does not split commas |
| 363 |
# inside of quotes |
| 364 |
SECTION_EXPAND_PATTERN = re.compile( |
| 365 |
r''' |
| 366 |
(?: |
| 367 |
[^,"']+ |
| 368 |
| |
| 369 |
"[^"]*" |
| 370 |
| |
| 371 |
'[^']*' |
| 372 |
)+ |
| 373 |
''', |
| 374 |
re.X |
| 375 |
) |
| 376 |
|
| 377 |
|
| 378 |
def dequote(string: str, chars='"\'') -> str: |
| 379 |
"""Simple approach to strip quotes from strings. |
| 380 |
|
| 381 |
Examples: |
| 382 |
>>> dequote('"foo"') |
| 383 |
'foo' |
| 384 |
>>> dequote("'foo'") |
| 385 |
'foo' |
| 386 |
>>> dequote('a"b"c') |
| 387 |
'a"b"c' |
| 388 |
|
| 389 |
""" |
| 390 |
if len(string) < 2: |
| 391 |
return string |
| 392 |
for char in chars: |
| 393 |
if string[0] == char and string[-1] == char: |
| 394 |
return string[1:-1] |
| 395 |
return string |
| 396 |
|
| 397 |
|
| 398 |
def expand_many_section(config): |
| 399 |
"""Expand comma separated entries. |
| 400 |
|
| 401 |
Intended for use in __MANY__ sections i.e. ones in which headings are |
| 402 |
user defined. |
| 403 |
|
| 404 |
Returns the expanded config i.e. does not modify it in place (this is |
| 405 |
necessary to preserve definition order). |
| 406 |
""" |
| 407 |
ret = {} |
| 408 |
for section_name, section in config.items(): |
| 409 |
for name in SECTION_EXPAND_PATTERN.findall(section_name): |
| 410 |
name = dequote(name.strip()).strip() |
| 411 |
replicate(ret.setdefault(name, {}), section) |
| 412 |
return ret |