Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aws
GitHub Repository: aws/aws-cli
Path: blob/develop/awscli/customizations/eks/ordered_yaml.py
1567 views
1
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License"). You
4
# may not use this file except in compliance with the License. A copy of
5
# the License is located at
6
#
7
# http://aws.amazon.com/apache2.0/
8
#
9
# or in the "license" file accompanying this file. This file is
10
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
# ANY KIND, either express or implied. See the License for the specific
12
# language governing permissions and limitations under the License.
13
14
import yaml
15
from botocore.compat import OrderedDict
16
17
18
class SafeOrderedLoader(yaml.SafeLoader):
19
""" Safely load a yaml file into an OrderedDict."""
20
21
22
class SafeOrderedDumper(yaml.SafeDumper):
23
""" Safely dump an OrderedDict as yaml."""
24
25
26
def _ordered_constructor(loader, node):
27
loader.flatten_mapping(node)
28
return OrderedDict(loader.construct_pairs(node))
29
30
31
SafeOrderedLoader.add_constructor(
32
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
33
_ordered_constructor)
34
35
36
def _ordered_representer(dumper, data):
37
return dumper.represent_mapping(
38
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
39
data.items())
40
41
42
SafeOrderedDumper.add_representer(OrderedDict, _ordered_representer)
43
44
45
def ordered_yaml_load(stream):
46
""" Load an OrderedDict object from a yaml stream."""
47
return yaml.load(stream, SafeOrderedLoader)
48
49
50
def ordered_yaml_dump(to_dump, stream=None):
51
"""
52
Dump an OrderedDict object to yaml.
53
54
:param to_dump: The OrderedDict to dump
55
:type to_dump: OrderedDict
56
57
:param stream: The file to dump to
58
If not given or if None, only return the value
59
:type stream: file
60
"""
61
return yaml.dump(to_dump, stream,
62
SafeOrderedDumper, default_flow_style=False)
63
64