blob: 17841fe0276c233d0fa5aa202b424de2bb51e5ca [file] [log] [blame]
piclosec4e65032017-02-21 14:52:45 +01001#!/usr/bin/env python3
2import json
3import os
4import 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
9def 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
22if len(sys.argv) < 2:
23 usage()
24 exit(1)
25
26if sys.argv[1] in ('--help','-h'):
27 usage()
28 exit(0)
29
30# get updates
31updates_json = sys.stdin.read()
32print(updates_json[81:])
33updates = json.loads(updates_json)
34
35# get file to update
36json_file_to_update = sys.argv[1]
37with open(json_file_to_update) as f:
38 to_update = json.load(f)
39
40# update config with updates
41def 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
58update(to_update, updates)
59
60# replace the file
61tmp_file = '%s.tmp' % (json_file_to_update,)
62with open(tmp_file, 'w') as f:
63 json.dump(to_update, f, sort_keys=True, indent=2)
64os.rename(tmp_file, json_file_to_update)
65