Argument parser now works for command execution as well (vs. just for help).
authorW. Trevor King <wking@drexel.edu>
Mon, 10 May 2010 15:05:34 +0000 (11:05 -0400)
committerW. Trevor King <wking@drexel.edu>
Mon, 10 May 2010 15:05:34 +0000 (11:05 -0400)
hooke/command.py
hooke/plugin/cut.py
hooke/plugin/playlist.py
hooke/ui/commandline.py

index 97d8ea5d6241e0f69462651bba7a16a8f7ba62d5..60e7233f6e70a2db34aa780ea8069cf0e2f67c1f 100644 (file)
@@ -59,7 +59,7 @@ class Command (object):
             self._run(inqueue, outqueue, params)
         except CommandExit, e:
             if isinstance(e, Failure):
-                outqueue.put(e.message)
+                outqueue.put(str(e))
                 outqueue.put(e)
                 return 1
         outqueue.put(e)
@@ -76,13 +76,14 @@ class Command (object):
         for argument in self.arguments:
             names = [argument.name] + argument.aliases
             settings = [(name,v) for name,v in params.items() if name in names]
-            if len(settings) == 0:
+            num_provided = len(settings)
+            if num_provided == 0:
                 if argument.optional == True or argument.count == 0:
                     settings = [(argument.name, argument.default)]
                 else:
                     raise Failure('Required argument %s not set.'
                                   % argument.name)
-            if len(settings) > 1:
+            if num_provided > 1:
                 raise Failure('Multiple settings for %s:\n  %s'
                     % (argument.name,
                        '\n  '.join(['%s: %s' % (name,value)
@@ -92,7 +93,8 @@ class Command (object):
                 params.remove(name)
                 params[argument.name] = value
             if argument.callback != None:
-                value = argument.callback(self, argument, value)
+                if num_provided > 0:
+                    value = argument.callback(self, argument, value)
                 params[argument.name] = value
             argument.validate(value)
         return params
index 15d6bbed2dd352026ff5fd2e286759ef09290990..e93367bd122cbbfa0742f4c9d3aea0f48efb8934 100644 (file)
@@ -41,7 +41,7 @@ File name for the output data.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
        i_min = min([p.index for p in params['points']])
        i_max = max([p.index for p in params['points']])
 
index 44f18bdd7ebab974e415f83b7456adf2fcd54078..04116b7f1ced099964fc64aa0eab41a1afde8c34 100644 (file)
@@ -34,7 +34,7 @@ class NextCommand (Command):
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
        params['playlist'].next()
 
 class PreviousCommand (Command):
@@ -51,7 +51,7 @@ class PreviousCommand (Command):
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
        params['playlist'].previous()
 
 class JumpCommand (Command):
@@ -71,7 +71,7 @@ Index of target curve.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
        params['playlist'].jump(params['index'])
 
 class SaveCommand (Command):
@@ -93,7 +93,7 @@ playlist.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
        params['playlist'].save(params['output'])
 
 class LoadCommand (Command):
@@ -115,7 +115,7 @@ Digests for loading curves.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
         p = FilePlaylist(drivers=params['drivers'], path=params['input'])
         p.load()
        outqueue.put(p)
@@ -142,7 +142,7 @@ Additional information for the input :class:`hooke.curve.Curve`.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
         params['playlist'].append_curve_by_path(params['input'],
                                                 params['info'])
 
@@ -172,7 +172,7 @@ Additional information for the input :class:`hooke.curve.Curve`.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
         for path in sorted(glob.glob(params['input'])):
             params['playlist'].append_curve_by_path(path, params['info'])
 
@@ -193,7 +193,7 @@ Index of target curve.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
         params['playlist'].pop(params['index'])
         params['playlist'].jump(params._index)
 
@@ -219,6 +219,6 @@ Function returning `True` for "good" curves.  `filter(curve) -> True/False`.
                 ],
             help=self.__doc__)
 
-    def _run(inqueue, outqueue, params):
+    def _run(self, inqueue, outqueue, params):
         p = params['playlist'].filter(params['filter'])
         outqueue.put(p)
index cab42969d79f63450697808741291f966390ad13..c9ed605fb07b234d15b50c2a8da054ad470d082e 100644 (file)
@@ -5,6 +5,7 @@ line.
 import cmd
 import optparse
 import readline # including readline makes cmd.Cmd.cmdloop() smarter
+import shlex
 
 from ..command import CommandExit, Command, Argument
 from ..ui import UserInterface, CommandMessage
@@ -24,22 +25,23 @@ class CommandMethod (object):
 
 def command_parser(command):
     p = optparse.OptionParser()
+    opts = []
     args = []
     for a in command.arguments:
         if a.name == 'help':
             continue # 'help' is a default OptionParser option
+        name = a.name.replace('_', '-')
         if a.optional == True:
-            p.add_option(
-                '--%s' % a.name.replace('_', '-'),
-                dest=a.name, default=a.default)
+            p.add_option('--%s' % name, dest=a.name, default=a.default)
+            opts.append((name, a))
         else:
-            args.append((a.name.replace('_', '-'), a))
-    return (p, args)
+            args.append((name, a))
+    return (p, opts, args)
 
 class DoCommand (CommandMethod):
     def __init__(self, *args, **kwargs):
         super(DoCommand, self).__init__(*args, **kwargs)
-        self.parser,self.args = command_parser(self.command)
+        self.parser,self.opts,self.args = command_parser(self.command)
 
     def __call__(self, args):
         args = self._parse_args(self.command, args)
@@ -48,16 +50,24 @@ class DoCommand (CommandMethod):
             msg = self.cmd.outqueue.get()
             if isinstance(msg, CommandExit):
                 break
-            self.cmd.stdout.write(str(msg))
+            self.cmd.stdout.write(str(msg).rstrip()+'\n')
 
     def _parse_args(self, command, args):
-        print 'ARGS:', args, type(args)
-        return {}
+        argv = shlex.split(args, comments=True, posix=True)
+        options,args = self.parser.parse_args(argv)
+        params = {}
+        for namearg in self.opts:
+            name,argument = namearg
+            params[name] = getattr(options, name)
+        for namearg,value in zip(self.args, args):
+            name,argument = namearg
+            params[name] = value
+        return params
 
 class HelpCommand (CommandMethod):
     def __init__(self, *args, **kwargs):
         super(HelpCommand, self).__init__(*args, **kwargs)
-        self.parser,self.args = command_parser(self.command)
+        self.parser,self.opts,self.args = command_parser(self.command)
 
     def __call__(self):
         blocks = [self.command.help(),