Commits

John Mulligan committed 21fb055

convert option names with dashes to underscores when used a kwargs

Comments (0)

Files changed (2)

test/test_cli_commands.py

     return xxx(3)
 
 
+def fishfunc(in_water, verbose=None, quiet=None):
+    return in_water
+
+
 CMDTABLE_A = [
     ('foo', cmd1, '', [], 'FILENAME'),
     ('bar', cmd2, '', [], 'bar breaks it'),
 
 CMDTABLE_C = {
     'snorkel': {'target': cmd1, 'opts': [], 'help': 'magic stuff'},
-    'fish': {'target': cmd2, 'opts': [], 'help': 'other stuff'},
+    'fish': {'target': fishfunc, 'opts': [
+        ('in-water', 'i', None, 'is it in the water'),
+        ], 'help': 'other stuff'},
     }
 
 CMDTABLE_D = [
     def test_dict_table_style(self):
         arguments = 'fish -v yes yes'.split()
         cmd, opts, args = commander.parse(GOPT_A, CMDTABLE_C, arguments)
-        self.assertEqual(cmd.target, cmd2)
+        self.assertEqual(cmd.target, fishfunc)
         self.assertEqual(args, ['yes', 'yes'])
-        self.assertEqual(opts, dict(verbose=True, quiet=None))
+        self.assertEqual(opts, {'verbose': True, 'quiet': None, 'in-water': None})
 
 
     def test_decorated_table(self):
             caught = True
         self.assertTrue(caught)
 
+    def test_dispatch_option_dashes(self):
+        v = commander.main(GOPT_A, CMDTABLE_C, 'fish --in-water'.split())
+        self.assertEqual(v, True)
+
     def test_main_dispatch_raises(self):
         self.assertRaises(TypeError,
             commander.main, GOPT_A, CMDTABLE_A, 'baz'.split())

vanity/commander.py

             yield line
 
 
+def cleanopts(opts, dropkeys=None):
+    """Convert raw options dictionary to one suitable for use a keyword
+    arguments to a python function.
+
+    * ``opts`` - The options dictionary to clean
+    * ``dropkeys`` - A list of keys to drop if they are in the opts
+    """
+    opts = dict([(k.replace('-', '_'), v) for k, v in opts.iteritems()])
+    if dropkeys:
+        for key in dropkeys:
+            if key in opts:
+                del opts[key]
+    return opts
+
+
 class Command(object):
     """A thin class representing a command.
 
         self.strict = strict
 
     def __call__(self, opts, args):
+        opts = cleanopts(opts, ('help',))
         try:
             return self.target(*args, **opts)
         except TypeError, err: