| 1 |
|
| 2 |
from __future__ import unicode_literals |
| 3 |
""" |
| 4 |
ODYLDo - Ordered Dict Yaml Loader / Dumper |
| 5 |
------------------------------------------ |
| 6 |
|
| 7 |
a simple implementation of a Ordered Dict Loader for PyYAML; |
| 8 |
because chaos is fun but order matters on loading dicts from a yaml file; |
| 9 |
|
| 10 |
(c) 2014 - 2024 Klaus Zerwes zero-sys.net |
| 11 |
This package is free software. |
| 12 |
This software is licensed under the terms of the |
| 13 |
GNU GENERAL PUBLIC LICENSE version 3 or later, |
| 14 |
as published by the Free Software Foundation. |
| 15 |
See https://www.gnu.org/licenses/gpl.html |
| 16 |
""" |
| 17 |
|
| 18 |
import yaml |
| 19 |
import yaml.loader |
| 20 |
import yaml.dumper |
| 21 |
import yaml.representer |
| 22 |
from collections import OrderedDict |
| 23 |
|
| 24 |
|
| 25 |
ODYLDoYAMLMAPS = [ |
| 26 |
'tag:yaml.org,2002:map', |
| 27 |
'tag:yaml.org,2002:omap', |
| 28 |
] |
| 29 |
|
| 30 |
class ODYL(yaml.SafeLoader): |
| 31 |
"""Ordered Dict Yaml Loader""" |
| 32 |
def __init__(self, *args, **kwargs): |
| 33 |
yaml.SafeLoader.__init__(self, *args, **kwargs) |
| 34 |
for mapping in ODYLDoYAMLMAPS: |
| 35 |
self.add_constructor(mapping, type(self)._odyload) |
| 36 |
|
| 37 |
|
| 38 |
def _odyload(self, node): |
| 39 |
if node.tag not in ODYLDoYAMLMAPS: |
| 40 |
raise Exception('called ODYLoad for unregistered mapping mode "%s" aka. "%s"' % (node.tag, node.id,)) |
| 41 |
data = OrderedDict() |
| 42 |
yield data |
| 43 |
data.update(self.construct_mapping(node)) |
| 44 |
|
| 45 |
|
| 46 |
def construct_mapping(self, node, deep=False): |
| 47 |
self.flatten_mapping(node) |
| 48 |
m = OrderedDict() |
| 49 |
for k, v in node.value: |
| 50 |
m[self.construct_object(k, deep=deep)] = self.construct_object(v, deep=deep) |
| 51 |
return m |
| 52 |
|
| 53 |
class ODYD(yaml.SafeDumper): |
| 54 |
"""Ordered Dict Yaml Dumper""" |
| 55 |
def __init__(self, *args, **kwargs): |
| 56 |
yaml.SafeDumper.__init__(self, *args, **kwargs) |
| 57 |
yaml.representer.SafeRepresenter.add_representer(OrderedDict, type(self)._odyrepr) |
| 58 |
def _odyrepr(self, data): |
| 59 |
"""see: yaml.representer.represent_mapping""" |
| 60 |
return self.represent_mapping('tag:yaml.org,2002:map', data.items()) |
| 61 |
|
| 62 |
def safe_load(stream): |
| 63 |
"""implementation of safe loader using Ordered Dict Yaml Loader""" |
| 64 |
return yaml.load(stream, ODYL) |
| 65 |
|
| 66 |
def safe_load_all(stream): |
| 67 |
"""safe parse all YAML documents in a stream using Ordered Dict Yaml Loader""" |
| 68 |
return yaml.load_all(stream, ODYL) |
| 69 |
|
| 70 |
def safe_dump(data, stream=None, **kwds): |
| 71 |
"""implementation of safe dumper using Ordered Dict Yaml Dumper""" |
| 72 |
return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds) |
| 73 |
|