Mercurial > hg > configuration
view configuration/config.py @ 10:c782d750fd6d
comment
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Mon, 26 Mar 2012 09:14:04 -0700 |
parents | b28ec204df23 |
children | e00afe2c83bf |
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 = [] # TODO: ensure options are of the right type (if specified) 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()