115: CLI now parses out kw args; cmd.__call__() now uses print_n_call() to give feedback on the calling

This commit is contained in:
Jason Gerard DeRose 2008-08-12 16:49:23 +00:00
parent bc4b26ffca
commit 99d7638ff5
3 changed files with 30 additions and 18 deletions

View File

@ -76,17 +76,17 @@ class CLI(object):
self.print_commands()
print 'ipa: ERROR: unknown command %r' % cmd
sys.exit(2)
self.run_cmd(cmd)
self.run_cmd(cmd, sys.argv[2:])
def run_cmd(self, cmd):
(options, args) = self.build_parser(cmd)
print options
def run_cmd(self, cmd, args):
kw = dict(self.parse_kw(args))
self[cmd](**kw)
def build_parser(self, cmd):
parser = optparse.OptionParser()
for option in self[cmd].options:
parser.add_option('--%s' % to_cli(option.name),
help=option.get_doc(_),
def parse_kw(self, args):
for arg in args:
m = re.match(r'^--([a-z][-a-z0-9]*)=(.+)$', arg)
if m is not None:
yield (
from_cli(m.group(1)),
m.group(2),
)
(options, args) parser.parse_args()

View File

@ -208,15 +208,15 @@ class cmd(plugable.Plugin):
print '%s.%s(%s)' % (
self.name,
method,
' '.join('%s=%r' % (k, v) for (k, v) in kw.items()),
', '.join('%s=%r' % (k, v) for (k, v) in kw.items()),
)
getattr(self, method)(**kw)
return getattr(self, method)(**kw)
def __call__(self, **kw):
kw = self.normalize(**kw)
kw.update(self.default(**kw))
self.validate(**kw)
return self.execute(**kw)
kw = self.print_n_call('normalize', kw)
kw.update(self.print_n_call('default', kw))
self.print_n_call('validate', kw)
return self.print_n_call('execute', kw)
class obj(plugable.Plugin):

View File

@ -53,3 +53,15 @@ class test_CLI(ClassChecker):
api = 'the plugable.API instance'
o = self.cls(api)
assert read_only(o, 'api') is api
def test_parse_kw(self):
"""
Tests the `parse_kw` method.
"""
o = self.cls(None)
kw = dict(
hello='world',
how_are='you',
)
args = tuple('--%s=%s' % (cli.to_cli(k), v) for (k,v) in kw.items())
assert dict(o.parse_kw(args)) == kw