Add allotted resource recipe table
[so/docker-config.git] / json_updater.py
1 #!/usr/bin/env python3
2 import json
3 import os
4 import sys
5
6 #chef_update_string = '{"default_attributes": {"asdc-connections": {"asdc-controller1": {"environmentName": "test"}}}}'
7 #json_file_to_update="./volumes/mso/chef-config/mso-docker.json"
8
9 def usage():
10     print('Usage:')
11     print("    echo <json> | %s <file> " % ( sys.argv[0], ))
12     print()
13     print("file\tpath of the valid json file to update")
14     print("json\ta json string containing the values to update in <file>")
15     print("")
16     print("Example : ")
17     print(""" 
18     echo '{"default_attributes": {"asdc-connections": {"asdc-controller1": {"environmentName": "test"}}}}' | %s ./volumes/mso/chef-config/mso-docker.json
19     """ % (sys.argv[0]))
20
21     
22 if len(sys.argv) < 2:
23     usage()
24     exit(1)
25     
26 if sys.argv[1] in ('--help','-h'):
27     usage()
28     exit(0)
29     
30 # get updates
31 updates_json = sys.stdin.read()
32 print(updates_json[81:])
33 updates = json.loads(updates_json)
34
35 # get file to update
36 json_file_to_update = sys.argv[1]
37 with open(json_file_to_update) as f:
38     to_update = json.load(f)
39     
40 # update config with updates
41 def update(config, updates):
42     #assert isinstance(config, dict)
43     #assert isinstance(updates, dict)
44
45     # if key is a simple type, update it. Otherwise, update sub values
46
47
48     for update_key,update_value in updates.items():
49         if update_key not in config:
50             raise Exception('Incorrect parameter : %s' % (update_key,))        
51         if isinstance(update_value, (int, str)):
52             config[update_key] = update_value
53         elif isinstance (update_value,list) and isinstance (config[update_key],list):
54             config[update_key] = update_value
55         else:
56             update(config[update_key], update_value)
57
58 update(to_update, updates)
59
60 # replace the file
61 tmp_file = '%s.tmp' % (json_file_to_update,)
62 with open(tmp_file, 'w') as f:
63     json.dump(to_update, f,  sort_keys=True, indent=2)
64 os.rename(tmp_file, json_file_to_update)
65