changeset 8:109627b7db9f

add ability to have mandatory class arguments
author Jeff Hammel <jhammel@mozilla.com>
date Fri, 30 Mar 2012 10:37:39 -0700
parents 0abe38b2ea7b
children 0069096e8e22
files commandparser/command.py setup.py
diffstat 2 files changed, 13 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/commandparser/command.py	Fri Mar 30 10:18:34 2012 -0700
+++ b/commandparser/command.py	Fri Mar 30 10:37:39 2012 -0700
@@ -21,7 +21,10 @@
     def __init__(self, _class, description=None):
         self._class = _class
         self.commands = {}
-        usage = '%prog [options] command [command-options]'
+        init = self.command(_class.__init__)
+        self.init_args = init['args']
+        command_str = ' '.join(self.init_args + ['command'])
+        usage = '%prog [options]' + ' %s [command-options]' % (command_str)
         description = description or _class.__doc__
         OptionParser.__init__(self, usage=usage, description=description)
         commands = [ getattr(_class, i) for i in dir(_class)
@@ -33,9 +36,7 @@
             self.commands[c['name']] = c
 
         # get class options
-        init = self.command(_class.__init__)
         self.command2parser(init, self)
-
         self.disable_interspersed_args()
 
     def add_option(self, *args, **kwargs):
@@ -81,6 +82,12 @@
             else:
                 self.print_help()
             sys.exit(0)
+        required = len(self.init_args) + 1 # command
+        if len(args) < required:
+            self.print_usage()
+            sys.exit(1)
+        self.command_args = args[:len(self.init_args)]
+        args = args[len(self.init_args):]
         command = args[0]
         if command not in self.commands:
             self.error("No command '%s'" % command)
@@ -92,7 +99,7 @@
         """
 
         # parse
-        name, args = self.parse(args)
+        name, args  = self.parse(args)
 
         # setup
         options = {}
@@ -116,7 +123,7 @@
                 options[key] = value.default
             else:
                 options[key] = value
-        _object = self._class(**options)
+        _object = self._class(*self.command_args, **options)
 
         # command specific args
         command = self.commands[name]
--- a/setup.py	Fri Mar 30 10:18:34 2012 -0700
+++ b/setup.py	Fri Mar 30 10:37:39 2012 -0700
@@ -4,7 +4,7 @@
 
 import os
 
-version = "0.1"
+version = "0.1.1"
 dependencies = []
 
 # allow use of setuptools/distribute or distutils