configfile.py

Sun, 09 Nov 2014 20:01:06 +0200

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Sun, 09 Nov 2014 20:01:06 +0200
changeset 68
ecc161d4a6fa
parent 65
20bd76353eb5
child 73
d67cc4fbc3f1
permissions
-rw-r--r--

- fixed bad channel config addressing

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()

mercurial