diff --git a/yamerge.py b/yamerge.py new file mode 100755 index 0000000..51c20f5 --- /dev/null +++ b/yamerge.py @@ -0,0 +1,43 @@ +#!/bin/env python3 + +import argparse +from sys import stdout +from yaml import load, dump +try: + from yaml import CLoader as Loader, CDumper as Dumper +except ImportError: + from yaml import Loader, Dumper + +def deepmerge(source, destination): + for key, value in source.items(): + if isinstance(value, dict): + merge(value, destination.setdefault(key, {})) + else: + destination[key] = value + return destination + +def deepsort(dictionary): + result = {} + for k, v in sorted(dictionary.items()): + if isinstance(v, dict): + result[k] = deepsort(v) + else: + result[k] = v + return result + +parser = argparse.ArgumentParser( + prog='yamerge', + description='Merges all YAML files listed on the CLI and outputs the resulting YAML to stdout.') +parser.add_argument('files', metavar='filename', type=str, nargs='+') +args = parser.parse_args() + +y = {} +for file in args.files: + f = open(file) + data = load(f, Loader=Loader) + f.close() + merged = deepmerge(y, data) + y = merged + +y = deepsort(y) +print(dump(y, Dumper=Dumper))