view configuration/config.py @ 7:6e3cf8f05464

note TODO: reading JSON
author Jeff Hammel <jhammel@mozilla.com>
date Sat, 24 Mar 2012 23:15:21 -0700
parents dce954a3831f
children 975fbc45cfcd
line wrap: on
line source

#!/usr/bin/env python

"""
multi-level unified configuration
"""

import sys
import optparse

# imports for contigent configuration providers
try:
    import json
except ImportError:
    try:
        import simplejson as json
    except ImportError:
        json = None
try:
    import yaml
except ImportError:
    yaml = None

__all__ = ['Configuration', 'configuration_providers']

configuration_providers = []
if json:
    class JSON(object):
        extensions = ['json']
        def read(self, filename):
            raise NotImplementedError("TODO")
    configuration_providers.append(JSON)

if yaml:
    class YAML(object):
        extensions = ['yml']
        def read(self, filename):
            f = file(filename)
            config = yaml.load(f)
            f.close()
            return config

    configuration_providers.append(YAML)


class Configuration(object):
    options = {}

    def __init__(self, configuration_providers=configuration_providers):
        self.config = {}
        self.configuration_providers = configuration_providers

    def check(self, config):
        """check validity of configuration"""

        # TODO: ensure options in configuration are in self.options
        unknown_options = []

        #

    def __call__(self, *args):
        """add items to configuration and check it"""

    def add(self, config):
        """update configuration: not undoable"""

        self.check(config)

        self.config.update(config)
        # TODO: option to extend; augment lists/dicts

def main(args=sys.argv[:]):

    # parse command line options
    usage = '%prog [options]'
    class PlainDescriptionFormatter(optparse.IndentedHelpFormatter):
        """description formatter for console script entry point"""
        def format_description(self, description):
            if description:
                return description.strip() + '\n'
            else:
                return ''
    parser = optparse.OptionParser(usage=usage, description=__doc__, formatter=PlainDescriptionFormatter())
    options, args = parser.parse_args(args)

if __name__ == '__main__':
  main()