# HG changeset patch # User Jeff Hammel # Date 1334692210 25200 # Node ID 490687e707239e4d8ec39e07a90330b6627102dd # Parent f3b2563b2a91c4b28b1ab7539130e2d64eb01279 add a dict parser thingy diff -r f3b2563b2a91 -r 490687e70723 configuration/configuration.py --- 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(): diff -r f3b2563b2a91 -r 490687e70723 tests/example.py --- 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__':