import sys import re def sort_yaml(filename): keys = [] blocks = {} with open(filename, "r") as f: current_block = "" current_key = None for line in f.readlines(): if line == "\n" and current_key is not None: if current_key in keys: raise RuntimeError("Duplicate key '" + current_key + "'!") keys.append(current_key) blocks[current_key] = current_block current_block = "" current_key = None continue else: m = re.match("^([a-z]+):\n$", line) if m: if current_key is None: current_key = m.group(1) else: raise RuntimeError("New block not separated from the previous block by a newline!") current_block += line keys.sort() for k in keys: print(blocks[k]) if __name__ == "__main__": for filename in sys.argv[1:]: sort_yaml(filename)