-
Notifications
You must be signed in to change notification settings - Fork 1
/
hiera_sorter.py
51 lines (41 loc) · 1.51 KB
/
hiera_sorter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/python
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap
import os.path
import argparse
class HieraSorter:
def run(self):
options = self.parse_args()
self.start(options)
def start(self, options):
for file_path in options.files:
self.sort_file(file_path)
def sort_anything(self, v):
if isinstance(v, CommentedMap):
v = self.sort_dict(v)
elif v is list:
v = sorted(v)
return v
def sort_dict(self, initial_dict):
result = []
for k, v in sorted(initial_dict.iteritems()):
v = self.sort_anything(v)
result.append((k,v))
cm = CommentedMap(result)
if hasattr(initial_dict, '_yaml_comment'):
cm._yaml_comment = initial_dict._yaml_comment
return cm
def sort_file(self, file_path):
if not os.path.isfile(file_path):
raise Exception('%s is not a file' % file_path)
with open(file_path, 'r') as stream:
data = ruamel.yaml.load(stream, ruamel.yaml.RoundTripLoader)
data = self.sort_dict(data)
print ruamel.yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper),
def parse_args(self):
parser = argparse.ArgumentParser(description='Sort a YAML file, respecting its comments')
parser.add_argument('files', metavar='file', nargs='+',
help='a file to be sorted')
return parser.parse_args()
if __name__ == "__main__":
HieraSorter().run()