|
1 import json |
|
2 |
|
3 class ConfigNode: |
|
4 def __init__ (self, obj, name, parent): |
|
5 self.obj = obj |
|
6 self.name = name |
|
7 self.root = parent if parent == None or parent.root == None else parent.root |
|
8 |
|
9 def keyname (self, key): |
|
10 if self.name == None: |
|
11 return key |
|
12 return self.name + ':' + key |
|
13 |
|
14 def get_value (self, key, default=None): |
|
15 i = 0 |
|
16 needSave = False |
|
17 |
|
18 if not key in self.obj: |
|
19 if default == None: |
|
20 raise ValueError ('Mandatory key \'%s\' not found' % self.keyname (key)) |
|
21 self.obj[key] = default |
|
22 self.save() |
|
23 |
|
24 return self.obj[key] |
|
25 |
|
26 def set_value (self, key, value): |
|
27 self.obj[key] = value |
|
28 self.save() |
|
29 |
|
30 def get_node (self, key): |
|
31 return ConfigNode (obj=self.get_value (key, {}), name=self.keyname (key), parent=self) |
|
32 |
|
33 def get_nodelist (self, key): |
|
34 data = self.get_value (key) |
|
35 result = [] |
|
36 |
|
37 for entry in data: |
|
38 node = ConfigNode (obj=entry, name=self.keyname (key), parent=self) |
|
39 result.append (node) |
|
40 |
|
41 return result |
|
42 |
|
43 def save (self): |
|
44 if self.root != None: |
|
45 self.root.save() |
|
46 return |
|
47 |
|
48 with open ('cobalt.json', 'w') as fp: |
|
49 json.dump (self.obj, fp, sort_keys = True, indent = 1) |
|
50 |
|
51 print "Config saved." |
|
52 |
|
53 def init(): |
|
54 print 'Loading configuration...' |
|
55 |
|
56 try: |
|
57 with open ('cobalt.json', 'r') as fp: |
|
58 jsondata = json.loads (fp.read()) |
|
59 except IOError as e: |
|
60 print 'couldn\'t open cobalt.json: %s' % e |
|
61 quit() |
|
62 |
|
63 global Config |
|
64 Config = ConfigNode (jsondata, name=None, parent=None) |
|
65 |
|
66 init() |