diff -r 384167adad2b -r 20bd76353eb5 configfile.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/configfile.py Sun Nov 09 19:13:08 2014 +0200 @@ -0,0 +1,66 @@ +import json + +class ConfigNode: + def __init__ (self, obj, name, parent): + self.obj = obj + self.name = name + self.root = parent if parent == None or parent.root == None else parent.root + + def keyname (self, key): + if self.name == None: + return key + return self.name + ':' + key + + def get_value (self, key, default=None): + i = 0 + needSave = False + + if not key in self.obj: + if default == None: + raise ValueError ('Mandatory key \'%s\' not found' % self.keyname (key)) + self.obj[key] = default + self.save() + + return self.obj[key] + + def set_value (self, key, value): + self.obj[key] = value + self.save() + + def get_node (self, key): + return ConfigNode (obj=self.get_value (key, {}), name=self.keyname (key), parent=self) + + def get_nodelist (self, key): + data = self.get_value (key) + result = [] + + for entry in data: + node = ConfigNode (obj=entry, name=self.keyname (key), parent=self) + result.append (node) + + return result + + def save (self): + if self.root != None: + self.root.save() + return + + with open ('cobalt.json', 'w') as fp: + json.dump (self.obj, fp, sort_keys = True, indent = 1) + + print "Config saved." + +def init(): + print 'Loading configuration...' + + try: + with open ('cobalt.json', 'r') as fp: + jsondata = json.loads (fp.read()) + except IOError as e: + print 'couldn\'t open cobalt.json: %s' % e + quit() + + global Config + Config = ConfigNode (jsondata, name=None, parent=None) + +init() \ No newline at end of file