utils/yamerge.py

44 lines
1.1 KiB
Python
Raw Normal View History

2023-06-29 00:22:04 +00:00
#!/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))