Last active
April 13, 2019 22:29
-
-
Save jamezrin/feafd4e79d2115f4045fa0077a138116 to your computer and use it in GitHub Desktop.
Script to map files with nested maps to a flat structure with paths separated by dots
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import sys | |
from ruamel.yaml import YAML, YAMLError | |
yaml = YAML() | |
yaml.allow_unicode = True | |
yaml.allow_duplicate_keys = True | |
def ParentPath(parent, current, sep='.'): | |
path = current | |
if parent is not None: | |
path = parent + sep + path | |
return path | |
def CollectScalars(node, parent=None): | |
scalars = [] | |
for key, value in node.items(): | |
if isinstance(value, dict): | |
scalars.extend(CollectScalars( | |
value, ParentPath(parent, key) | |
)) | |
else: | |
scalars.append({ | |
'path': ParentPath(parent, key), | |
'value': value | |
}) | |
return scalars | |
def AnalyzeFile(stream): | |
document = yaml.load(stream) | |
scalars = CollectScalars(document) | |
yaml.dump(scalars, sys.stdout) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser('yaml-scalar-mapper') | |
parser.add_argument('source', help="The path to the yaml file to process") | |
args = parser.parse_args() | |
with open(args.source, 'r') as stream: | |
AnalyzeFile(stream) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment