view configuration/config.py @ 9:b28ec204df23

flush out JSON provider
author Jeff Hammel <jhammel@mozilla.com>
date Sun, 25 Mar 2012 10:24:55 -0700
parents 975fbc45cfcd
children c782d750fd6d
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):
            return json.loads(file(filename).read())
    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 parser(self):
        """return OptionParser"""
        raise NotImplementedError("TODO")

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