Debian Codegraph @

hiyapyco/__init__.py

raw symbols SCIP
1 #! /usr/bin/env python -tt
2 # vim: set fileencoding=utf-8
3 """
4 Hierarchical Yaml Python Config
5 ===============================
6
7 A simple python lib allowing hierarchical config files in YAML syntax.
8
9 License
10 -------
11
12 (c) 2014 - 2024 Klaus Zerwes zero-sys.net
13 This package is free software.
14 This software is licensed under the terms of the
15 GNU GENERAL PUBLIC LICENSE version 3 or later,
16 as published by the Free Software Foundation.
17 See https://www.gnu.org/licenses/gpl.html
18 """
19
20 from __future__ import unicode_literals
21
22 import os
23 import logging
24 import re
25 import io
26 import copy
27 import yaml
28 from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined, TemplateError
29
30 from . import odyldo
31
32 __all__ = [
33 'load',
34 'dump',
35 'HiYaPyCo',
36 'HiYaPyCoInvocationException',
37 'HiYaPyCoImplementationException',
38 ]
39
40 from . import version
41 __version__ = version.VERSION
42
43 logger = logging.getLogger(__name__)
44
45 _USEDEFAULTYAMLLOADER = False
46
47 class HiYaPyCoInvocationException(Exception):
48 """dummy Exception raised on wrong invocation"""
49 pass
50
51 class HiYaPyCoImplementationException(Exception):
52 """dummy Exception raised if we are unable to merge some YAML stuff"""
53 pass
54
55 primitiveTypes = (int, str, bool, float)
56 # pylint: disable=superfluous-parens
57 strTypes = (str)
58 listTypes = (list, tuple)
59
60 # you may set this to something suitable for you
61 jinja2env = Environment(undefined=Undefined)
62
63 METHODS = { 'METHOD_SIMPLE':0x0001, 'METHOD_MERGE':0x0002, 'METHOD_SUBSTITUTE':0x0003, }
64 METHOD_SIMPLE = METHODS['METHOD_SIMPLE']
65 METHOD_MERGE = METHODS['METHOD_MERGE']
66 METHOD_SUBSTITUTE = METHODS['METHOD_SUBSTITUTE']
67
68 NONE_BEHAVIORS = {"NONE_BEHAVIOR_DEFAULT": 0x0001, "NONE_BEHAVIOR_OVERRIDE": 0x0002}
69 NONE_BEHAVIOR_DEFAULT = NONE_BEHAVIORS["NONE_BEHAVIOR_DEFAULT"]
70 NONE_BEHAVIOR_OVERRIDE = NONE_BEHAVIORS["NONE_BEHAVIOR_OVERRIDE"]
71
72
73 class HiYaPyCo:
74 """Main class"""
75 # pylint: disable=too-many-instance-attributes disable=too-many-branches disable=too-many-statements
76 def __init__(self, *args, **kwargs):
77 """
78 args: YAMLfile(s)
79 kwargs:
80 * method: one of
81 hiyapyco.METHOD_SIMPLE | hiyapyco.METHOD_MERGE | hiyapyco.METHOD_SUBSTITUTE
82 * mergelists: boolean (default: True) try to merge lists
83 (only makes sense if hiyapyco.METHOD_MERGE or hiyapyco.METHOD_SUBSTITUTE)
84 * none_behavior: one of hiyapyco.NONE_BEHAVIOR_DEFAULT | hiyapyco.NONE_BEHAVIOR_OVERRIDE
85 * interpolate: boolean (default: False)
86 * castinterpolated: boolean (default: False) try to cast values after interpolating
87 * usedefaultyamlloader: boolean (default: False)
88 * dereferenceyamlanchors: boolean (default: True)
89 * encoding: (default: 'utf-8') encoding used to read yaml files
90 * loglevel: one of the valid levels from the logging module
91 * failonmissingfiles: boolean (default: True)
92 * loglevelmissingfiles
93 * mergeoverride: optional function to customize merge for primitive values
94 * loader_callback: optional custom callback function to load yaml files. The
95 callback function shall behave like `yaml.load_all`, taking a IO stream as
96 input and returning a list of objects.
97
98 Returns a representation of the merged and (if requested) interpolated config.
99 Will mostly be a OrderedDict (dict if usedefaultyamlloader), but can be of any other type,
100 depending on the yaml files.
101 """
102 self._data = None
103 self._files = []
104
105 self.method = None
106 self.loader_callback = kwargs.pop("loader_callback", None)
107
108 if 'method' in kwargs:
109 logger.debug('parse kwarg method: %s ...' % kwargs['method'])
110 if kwargs['method'] not in METHODS.values():
111 raise HiYaPyCoInvocationException(
112 'undefined method used, must be one of: %s' %
113 ' '.join(METHODS.keys())
114 )
115 self.method = kwargs['method']
116 del kwargs['method']
117 if self.method is None:
118 self.method = METHOD_SIMPLE
119
120 self.mergelists = True
121 if 'mergelists' in kwargs:
122 if not isinstance(kwargs['mergelists'], bool):
123 raise HiYaPyCoInvocationException(
124 'value of "mergelists" must be boolean (got: "%s" as %s)' %
125 (kwargs['mergelists'], type(kwargs['mergelists']),)
126 )
127 self.mergelists = kwargs['mergelists']
128 del kwargs['mergelists']
129
130 self.none_behavior = None
131 if "none_behavior" in kwargs:
132 logger.debug("parse kwarg method: %s ..." % kwargs["none_behavior"])
133 if kwargs["none_behavior"] not in NONE_BEHAVIORS.values():
134 raise HiYaPyCoInvocationException(
135 "undefined method used, must be one of: %s"
136 % " ".join(NONE_BEHAVIORS.keys())
137 )
138 self.none_behavior = kwargs["none_behavior"]
139 del kwargs["none_behavior"]
140 if self.none_behavior is None:
141 self.none_behavior = NONE_BEHAVIOR_DEFAULT
142
143 self.interpolate = False
144 self.castinterpolated = False
145 if 'interpolate' in kwargs:
146 if not isinstance(kwargs['interpolate'], bool):
147 raise HiYaPyCoInvocationException(
148 'value of "interpolate" must be boolean (got: "%s" as %s)' %
149 (kwargs['interpolate'], type(kwargs['interpolate']),)
150 )
151 self.interpolate = kwargs['interpolate']
152 del kwargs['interpolate']
153 if 'castinterpolated' in kwargs:
154 if not isinstance(kwargs['castinterpolated'], bool):
155 raise HiYaPyCoInvocationException(
156 'value of "castinterpolated" must be boolean (got: "%s" as %s)' %
157 (kwargs['castinterpolated'], type(kwargs['castinterpolated']),)
158 )
159 self.castinterpolated = kwargs['castinterpolated']
160 del kwargs['castinterpolated']
161
162 if 'usedefaultyamlloader' in kwargs:
163 if not isinstance(kwargs['usedefaultyamlloader'], bool):
164 raise HiYaPyCoInvocationException(
165 'value of "usedefaultyamlloader" must be boolean (got: "%s" as %s)' %
166 (kwargs['usedefaultyamlloader'], type(kwargs['usedefaultyamlloader']),)
167 )
168 global _USEDEFAULTYAMLLOADER
169 _USEDEFAULTYAMLLOADER = kwargs['usedefaultyamlloader']
170 del kwargs['usedefaultyamlloader']
171
172 self.dereferenceyamlanchors = True
173 if 'dereferenceyamlanchors' in kwargs:
174 if not isinstance(kwargs['dereferenceyamlanchors'], bool):
175 raise HiYaPyCoInvocationException(
176 'value of "dereferenceyamlanchors" must be boolean (got: "%s" as %s)' %
177 (kwargs['dereferenceyamlanchors'], type(kwargs['dereferenceyamlanchors']),)
178 )
179 self.dereferenceyamlanchors = bool(kwargs['dereferenceyamlanchors'])
180 del kwargs['dereferenceyamlanchors']
181
182 self.failonmissingfiles = True
183 if 'failonmissingfiles' in kwargs:
184 if not isinstance(kwargs['failonmissingfiles'], bool):
185 raise HiYaPyCoInvocationException(
186 'value of "failonmissingfiles" must be boolean (got: "%s" as %s)' %
187 (kwargs['failonmissingfiles'], type(kwargs['failonmissingfiles']),)
188 )
189 self.failonmissingfiles = bool(kwargs['failonmissingfiles'])
190 del kwargs['failonmissingfiles']
191
192 if 'loglevelmissingfiles' in kwargs:
193 logging.getLogger('testlevellogger').setLevel(kwargs['loglevelmissingfiles'])
194 self.loglevelonmissingfiles = logging.getLogger('testlevellogger').getEffectiveLevel()
195 del kwargs['loglevelmissingfiles']
196 else:
197 self.loglevelonmissingfiles = logging.ERROR
198 if not self.failonmissingfiles:
199 self.loglevelonmissingfiles = logging.WARN
200
201 if 'loglevel' in kwargs:
202 logger.setLevel(kwargs['loglevel'])
203 del kwargs['loglevel']
204
205 self.encoding = 'utf-8'
206 if 'encoding' in kwargs:
207 self.encoding = kwargs['encoding']
208 del kwargs['encoding']
209
210 self.mergeprimitive = None
211 if 'mergeoverride' in kwargs:
212 # DEBT: Compare to make sure function signature is right
213 self.mergeprimitive = kwargs['mergeoverride']
214 del kwargs['mergeoverride']
215
216 if kwargs:
217 raise HiYaPyCoInvocationException('undefined keywords: %s' % ' '.join(kwargs.keys()))
218
219 if not args:
220 raise HiYaPyCoInvocationException('no yaml files defined')
221
222 for arg in args:
223 self._updatefiles(arg)
224
225 for yamlfile in self._files[:]:
226 logger.debug('yamlfile: %s ...' % yamlfile)
227 try:
228 if '\n' in yamlfile:
229 logger.debug('loading yaml doc from str ...')
230 f = yamlfile
231 self._load_data(_USEDEFAULTYAMLLOADER, yamlfile)
232 else:
233 fn = yamlfile
234 if not os.path.isabs(yamlfile):
235 fn = os.path.join(os.getcwd(), yamlfile)
236 logger.debug('path extended for yamlfile: %s' % fn)
237 try:
238 with io.open(fn, 'r', encoding=self.encoding) as f:
239 logger.debug('open4reading: file %s' % f)
240 self._load_data(_USEDEFAULTYAMLLOADER, f)
241 except IOError as e:
242 logger.log(self.loglevelonmissingfiles, e)
243 if not fn == yamlfile:
244 logger.log(self.loglevelonmissingfiles,
245 'file not found: %s (%s)' % (yamlfile, fn,))
246 else:
247 logger.log(self.loglevelonmissingfiles,
248 'file not found: %s' % yamlfile)
249 if self.failonmissingfiles:
250 raise HiYaPyCoInvocationException(
251 'yaml file not found: \'%s\'' % yamlfile
252 )
253 self._files.remove(yamlfile)
254 continue
255 except yaml.parser.ParserError as e:
256 logger.log(self.loglevelonmissingfiles, e)
257 logger.log(self.loglevelonmissingfiles,
258 'error while parsing yaml %s' % f)
259 if self.failonmissingfiles:
260 raise HiYaPyCoInvocationException(
261 'error while parsing file: \'%s\'' % f
262 )
263 self._files.remove(yamlfile)
264 continue
265
266
267 if self.interpolate:
268 self._data = self._interpolate(self._data)
269
270 def _load_data(self, _USEDEFAULTYAMLLOADER, f):
271 if self.loader_callback is not None:
272 ydata_generator = self.loader_callback(f)
273 elif _USEDEFAULTYAMLLOADER:
274 ydata_generator = yaml.safe_load_all(f)
275 else:
276 ydata_generator = odyldo.safe_load_all(f)
277 for ydata in ydata_generator:
278 if logger.isEnabledFor(logging.DEBUG):
279 logger.debug('yaml data: %s' % ydata)
280 if self._data is None:
281 self._data = ydata
282 else:
283 if self.method == METHOD_SIMPLE:
284 self._data = self._simplemerge(self._data, ydata)
285 elif self.method == METHOD_MERGE:
286 self._data = self._deepmerge(self._data, ydata)
287 elif self.method == METHOD_SUBSTITUTE:
288 self._data = self._substmerge(self._data, ydata)
289 else:
290 raise HiYaPyCoInvocationException('unknown merge method \'%s\'' % self.method)
291 logger.debug('merged data: %s' % self._data)
292
293 def _updatefiles(self, arg):
294 if isinstance(arg, strTypes):
295 if arg in self._files:
296 logger.warning('ignoring duplicated file %s' % arg)
297 return
298 self._files.append(arg)
299 elif isinstance(arg, listTypes):
300 for larg in arg:
301 self._updatefiles(larg)
302 else:
303 raise HiYaPyCoInvocationException(
304 'unable to handle arg %s of type %s' % (arg, type(arg),)
305 )
306
307 def _interpolate(self, d):
308 logger.debug('interpolate "%s" of type %s ...' % (d, type(d),))
309 if d is None:
310 return None
311 if isinstance(d, strTypes):
312 return self._interpolatestr(d)
313 if isinstance(d, primitiveTypes):
314 return d
315 if isinstance(d, listTypes):
316 for k, v in enumerate(d):
317 d[k] = self._interpolate(v)
318 return d
319 if isinstance(d, dict):
320 for k in d.keys():
321 d[k] = self._interpolate(d[k])
322 return d
323 raise HiYaPyCoImplementationException('can not interpolate "%s" of type %s' % (d, type(d),))
324
325 def _interpolatestr(self, s):
326 try:
327 si = jinja2env.from_string(s).render(self._data)
328 except TemplateError as e:
329 # FIXME: this seems to be broken for unicode str?
330 raise HiYaPyCoImplementationException('error interpolating string "%s" : %s' % (s, e,))
331 if not s == si:
332 if self.castinterpolated:
333 if not re.match( r'^\d+\.*\d*$', si):
334 try:
335 si = bool(strtobool(si))
336 except ValueError:
337 pass
338 else:
339 try:
340 if '.' in si:
341 si = float(si)
342 else:
343 si = int(si)
344 except ValueError:
345 pass
346 logger.debug('interpolated "%s" to "%s" (type: %s)' % (s, si, type(si),))
347 return si
348
349 def _simplemerge(self, a, b):
350 if self.dereferenceyamlanchors:
351 a = copy.deepcopy(a)
352 b = copy.deepcopy(b)
353 logger.debug('simplemerge %s (%s) and %s (%s)' % (a, type(a), b, type(b),))
354 if b is None:
355 # override -> None replaces object, no matter what.
356 if self.none_behavior == NONE_BEHAVIOR_OVERRIDE:
357 logger.debug('b is None + none_behavior in use => return None')
358 return None
359 # default behavior is to attempt merge or fail
360 logger.debug('pass as b is None')
361 pass
362 elif isinstance(b, primitiveTypes):
363 logger.debug('simplemerge: primitiveTypes replace a "%s" w/ b "%s"' % (a, b,))
364 a = b
365 elif isinstance(b, listTypes):
366 logger.debug('simplemerge: listTypes a "%s" w/ b "%s"' % (a, b,))
367 if isinstance(a, listTypes):
368 # pylint: disable=unused-variable
369 for k, v in enumerate(b):
370 try:
371 a[k] = self._simplemerge(a[k], b[k])
372 except IndexError:
373 a[k] = b[k]
374 else:
375 logger.debug('simplemerge: replace %s w/ list %s' % (a, b,))
376 a = b
377 elif isinstance(b, dict):
378 if isinstance(a, dict):
379 logger.debug('simplemerge: update %s:"%s" by %s:"%s"' % (type(a), a, type(b), b,))
380 a.update(b)
381 else:
382 logger.debug('simplemerge: replace %s w/ dict %s' % (a, b,))
383 a = b
384 else:
385 raise HiYaPyCoImplementationException(
386 'can not (simple)merge %s to %s (@ "%s" try to merge "%s")' %
387 (type(b), type(a), a, b,)
388 )
389 return a
390
391 def _substmerge(self, a, b):
392 if self.dereferenceyamlanchors:
393 a = copy.deepcopy(a)
394 b = copy.deepcopy(b)
395 logger.debug('>' * 30)
396 logger.debug('substmerge %s and %s' % (a, b,))
397 # FIXME: make None usage configurable
398 if b is None:
399 logger.debug('pass as b is None')
400 # override -> None replaces object, no matter what.
401 if self.none_behavior == NONE_BEHAVIOR_OVERRIDE:
402 logger.debug('b is None + none_behavior in use => return None')
403 return None
404 # default behavior is to attempt merge or fail
405 logger.debug('pass as b is None')
406 pass
407
408 # treat listTypes as primitiveTypes in merge
409 # subsititues list, don't merge them
410
411 if a is None or isinstance(b, primitiveTypes) or isinstance(b, listTypes):
412 logger.debug('substmerge: replace a "%s" w/ b "%s"' % (a, b,))
413 a = b
414
415 elif isinstance(a, dict):
416 if isinstance(b, dict):
417 logger.debug('substmerge: dict ... "%s" and "%s"' % (a, b,))
418 for k in b:
419 if k in a:
420 logger.debug(
421 'substmerge dict: loop for key "%s": "%s" and "%s"' % (k, a[k], b[k],)
422 )
423 a[k] = self._substmerge(a[k], b[k])
424 else:
425 logger.debug('substmerge dict: set key %s' % k)
426 a[k] = b[k]
427 elif isinstance(b, listTypes):
428 logger.debug('substmerge: dict <- list ... "%s" <- "%s"' % (a, b,))
429 for bd in b:
430 if isinstance(bd, dict):
431 a = self._substmerge(a, bd)
432 else:
433 raise HiYaPyCoImplementationException(
434 'can not merge element from list of type %s to dict '
435 '(@ "%s" try to merge "%s")' %
436 (type(b), a, b,)
437 )
438 else:
439 raise HiYaPyCoImplementationException(
440 'can not merge %s to %s (@ "%s" try to merge "%s")' %
441 (type(b), type(a), a, b,)
442 )
443 logger.debug('end substmerge part: return: "%s"' % a)
444 logger.debug('<' * 30)
445 return a
446
447 def _deepmerge(self, a, b, context = None):
448 if context is None:
449 # DEBT: May be better to make this a class from the get go
450 # for better forward compatibility if we add things like file
451 # name, etc.
452 context = []
453 logger.debug('>'*30)
454 if self.dereferenceyamlanchors:
455 a = copy.deepcopy(a)
456 b = copy.deepcopy(b)
457 logger.debug('deepmerge %s and %s' % (a, b,))
458 # FIXME: make None usage configurable
459 if b is None:
460 logger.debug('pass as b is None')
461 # override -> None replaces object, no matter what.
462 if self.none_behavior == NONE_BEHAVIOR_OVERRIDE:
463 return None
464 # default behavior is to attempt merge or fail
465 logger.debug('pass as b is None')
466 pass
467 if a is None or isinstance(b, primitiveTypes):
468 if self.mergeprimitive is None:
469 logger.debug('deepmerge: replace a "%s" w/ b "%s"' % (a, b,))
470 a = b
471 else:
472 logger.debug(
473 'deepmerge: call mergeprimitive for a "%s", b "%s" with context' % (a, b,)
474 )
475 a = self.mergeprimitive(a, b, context)
476 elif isinstance(a, listTypes):
477 if isinstance(b, listTypes):
478 logger.debug(
479 'deepmerge: lists extend %s:"%s" by %s:"%s"' %
480 (type(a), a, type(b), b,)
481 )
482 a.extend(be for be in b if be not in a and
483 (isinstance(be, primitiveTypes) or isinstance(be, listTypes))
484 )
485 srcdicts = {}
486 for k, bd in enumerate(b):
487 if isinstance(bd, dict):
488 srcdicts.update({k:bd})
489 logger.debug('srcdicts: %s' % srcdicts)
490 for k, ad in enumerate(a):
491 logger.debug('deepmerge ad "%s" w/ k "%s" of type %s' % (ad, k, type(ad)))
492 if isinstance(ad, dict):
493 if k in srcdicts:
494 # we merge only if at least one key in dict is matching
495 merge = False
496 if self.mergelists:
497 for ak in ad.keys():
498 if ak in srcdicts[k].keys():
499 merge = True
500 break
501 if merge:
502 # pylint: disable=undefined-loop-variable
503 # FIXME undefined-loop-variable : this is not well readable !!!
504 logger.debug(
505 'deepmerge ad: deep merge list dict elem w/ '
506 'key:%s: "%s" and "%s"' %
507 (ak, ad, srcdicts[k],)
508 )
509 a[k] = self._deepmerge(ad, srcdicts[k], context)
510 del srcdicts[k]
511 logger.debug('deepmerge list: remaining srcdicts elems: %s' % srcdicts)
512 for k, v in srcdicts.items():
513 logger.debug('deepmerge list: new dict append %s:%s' % (k, v))
514 a.append(v)
515 else:
516 raise HiYaPyCoImplementationException(
517 'can not merge %s to %s (@ "%s" try to merge "%s")' %
518 (type(b), type(a), a, b,)
519 )
520 elif isinstance(a, dict):
521 if isinstance(b, dict):
522 logger.debug('deepmerge: dict ... "%s" and "%s"' % (a, b,))
523 for k in b:
524 if k in a:
525 logger.debug(
526 'deepmerge dict: loop for key "%s": "%s" and "%s"' %
527 (k, a[k], b[k],)
528 )
529 context.append(k)
530 a[k] = self._deepmerge(a[k], b[k], context)
531 context.pop()
532 else:
533 logger.debug('deepmerge dict: set key %s' % k)
534 a[k] = b[k]
535 elif isinstance(b, listTypes):
536 logger.debug('deepmerge: dict <- list ... "%s" <- "%s"' % (a, b,))
537 for bd in b:
538 if isinstance(bd, dict):
539 a = self._deepmerge(a, bd, context)
540 else:
541 raise HiYaPyCoImplementationException(
542 'can not merge element from list of type %s to dict '
543 '(@ "%s" try to merge "%s")' %
544 (type(b), a, b,)
545 )
546 else:
547 raise HiYaPyCoImplementationException(
548 'can not merge %s to %s (@ "%s" try to merge "%s")' %
549 (type(b), type(a), a, b,)
550 )
551 logger.debug('end deepmerge part: return: "%s"' % a)
552 logger.debug('<'*30)
553 return a
554
555 def yamlfiles(self):
556 """returns the list of parsed yaml files / strings"""
557 return self._files
558
559 def __str__(self):
560 """String representation of the class"""
561 return '%s [%s]' % (__name__, os.pathsep.join(self._files))
562
563 def data(self):
564 """return the data, merged and interpolated if required"""
565 return self._data
566
567 def dump(self, **kwds):
568 """dump the data as YAML"""
569 return dump(self._data, **kwds)
570
571 def dump(data, **kwds):
572 """dump the data as YAML"""
573 if _USEDEFAULTYAMLLOADER:
574 return yaml.safe_dump(data, **kwds)
575 return odyldo.safe_dump(data, **kwds)
576
577 def load(*args, **kwargs):
578 """
579 Load a Hierarchical Yaml Python Config
580 --------------------------------------
581
582 args: YAMLfile(s)
583 kwargs:
584 * method: one of hiyapyco.METHOD_SIMPLE | hiyapyco.METHOD_MERGE | hiyapyco.METHOD_SUBSTITUTE
585 * mergelists: boolean (default: True) try to merge lists
586 (only makes sense if hiyapyco.METHOD_MERGE or hiyapyco.METHOD_SUBSTITUTE)
587 * interpolate: boolean (default: False)
588 * castinterpolated: boolean (default: False) try to cast values after interpolating
589 * usedefaultyamlloader: boolean (default: False)
590 * encoding: (default: 'utf-8') encoding used to read yaml files
591 * loglevel: one of the valid levels from the logging module
592 * failonmissingfiles: boolean (default: True)
593 * loglevelmissingfiles
594
595 Returns a representation of the merged and (if requested) interpolated config.
596 Will mostly be a OrderedDict (dict if usedefaultyamlloader), but can be of any other type,
597 depending on the yaml files.
598 """
599 hiyapyco = HiYaPyCo(*args, **kwargs)
600 return hiyapyco.data()
601
602 def strtobool(val):
603 """
604 minimal implementation of the strtobool function (replaces deprecated distutils)
605 """
606 val = val.lower()
607 if val in ("y", "yes", "t", "true", "on", "1"):
608 return 1
609 if val in ("n", "no", "f", "false", "off", "0"):
610 return 0
611 raise ValueError("invalid truth value %r" % (val,))
612
613 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu