1. Eric Larson
  2. Dad

Source

Dad / dad / lib / config.py

'''
The config spec for the dad server itself. This defines the config
object, not the format, for providing a configuration to the dad
server. Any config language can be used to construct this config
object.

The intial config language uses Python's built in ConfigParser.
'''
from ConfigParser import ConfigParser, NoSectionError
from pprint import pprint


def parse_config(conf):
    cp = ConfigParser()
    if hasattr(conf, 'read'):
        conf = open(conf)
    if not cp.read(conf):
        raise Exception('Invalid config format')

    return Config.from_parser(cp)


class Config(dict):
    @classmethod
    def from_parser(cls, cp):
        config = cls()
        for section in cp.sections():

            if section.endswith(':config'):
                continue

            app = AppConfig.from_parser(dict(cp.items(section)))

            # look for a config section
            conf_section = '%s:config' % section
            try:
                app['config'] = dict(cp.items(conf_section))
            except NoSectionError as e:
                pass
        
            config[section] = app

        return config

        
class AppConfig(dict):
    
    @classmethod
    def from_dict(cls, d):
        app = cls()
        app['instances'] = 1
        app['config'] = {}
        app['env'] = {}
        app.update(d)
        return app

    @classmethod
    def from_parser(cls, section):
        app = cls(command=section['command'],
                  instances=int(section.get('instances', 1)),
                  config={})

        app['env'] = dict((k.upper(), v) for k, v in section.iteritems()
                          if k not in app)

        return app