Mercurial > hg > configuration
changeset 82:490687e70723
add a dict parser thingy
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Tue, 17 Apr 2012 12:50:10 -0700 |
parents | f3b2563b2a91 |
children | 19834bc83d13 |
files | configuration/configuration.py tests/example.py |
diffstat | 2 files changed, 29 insertions(+), 3 deletions(-) [+] |
line wrap: on
line diff
--- a/configuration/configuration.py Tue Apr 17 11:36:01 2012 -0700 +++ b/configuration/configuration.py Tue Apr 17 12:50:10 2012 -0700 @@ -110,13 +110,18 @@ """option that keeps track if it is seen""" # TODO: this should be configurable or something def take_action(self, action, dest, opt, value, values, parser): - """add the parsed option to the set of things parsed""" optparse.Option.take_action(self, action, dest, opt, value, values, parser) + + # add the parsed option to the set of things parsed if not hasattr(parser, 'parsed'): parser.parsed = set() parser.parsed.add(dest) - # TODO (see following comment) - # if self.type in ... + + # switch on types + formatter = getattr(parser, 'cli_formatter') + if formatter: + formatter = formatter(dest) + setattr(values, dest, formatter(getattr(values, dest))) ### plugins for option types ### TODO: this could use a bit of thought @@ -147,6 +152,9 @@ kw['action'] = 'store' return args, kw + def take_action(self, value): + return value + class BoolCLI(BaseCLI): def __call__(self, name, value): @@ -195,13 +203,25 @@ kw['type'] = 'float' return args, kw +class DictCLI(ListCLI): + + delimeter = '=' + + def take_action(self, value): + bad = [i for i in value if self.delimeter not in i] + if bad: + raise AssertionError("Each value must be delimited by '%s': %s" % (self.delimeter, bad)) + return dict([i.split(self.delimeter, 1) for i in value]) + # TODO: 'dict'-type cli interface types = {bool: BoolCLI(), int: IntCLI(), float: FloatCLI(), list: ListCLI(), + dict: DictCLI(), None: BaseCLI()} # default + __all__ += [i.__class__.__name__ for i in types.values()] class Configuration(optparse.OptionParser): @@ -320,6 +340,10 @@ ### methods for optparse ### XXX could go in a subclass + def cli_formatter(self, option): + handler = self.types[self.options[option].get('type')] + return getattr(handler, 'take_action', lambda x: 1) + def optparse_options(self, parser): """add optparse options to a OptionParser instance""" for key, value in self.items():
--- a/tests/example.py Tue Apr 17 11:36:01 2012 -0700 +++ b/tests/example.py Tue Apr 17 12:50:10 2012 -0700 @@ -17,6 +17,8 @@ 'type': bool}, 'test_timeout': {'help': "Time to wait for the browser to output to the log file", 'default': 1200}, + 'preferences': {'type': dict, + 'flags': ['-p', '--pref']} } if __name__ == '__main__':