Mercurial > hg > CommandParser
annotate commandparser/command.py @ 9:0069096e8e22
python 2.4 compatability
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Fri, 30 Mar 2012 16:45:50 -0700 |
parents | 109627b7db9f |
children | a3599e4db9a4 |
rev | line source |
---|---|
1 | 1 """ |
2 a command-line interface to the command line, a la pythonpaste | |
3 """ | |
4 | |
5 import inspect | |
6 import os | |
7 import sys | |
8 from optparse import OptionParser | |
9 from pprint import pprint | |
10 | |
9 | 11 try: |
12 import json | |
13 except ImportError: | |
14 import simplejson as json | |
15 | |
2
d36032625794
add __all__ and whitespace cleanup
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
16 __all__ = ['Undefined', 'CommandParser'] |
d36032625794
add __all__ and whitespace cleanup
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
17 |
1 | 18 class Undefined(object): |
9 | 19 def __init__(self, default): |
20 self.default=default | |
1 | 21 |
22 class CommandParser(OptionParser): | |
23 # TODO: add `help` command | |
24 | |
25 def __init__(self, _class, description=None): | |
26 self._class = _class | |
27 self.commands = {} | |
8
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
28 init = self.command(_class.__init__) |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
29 self.init_args = init['args'] |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
30 command_str = ' '.join(self.init_args + ['command']) |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
31 usage = '%prog [options]' + ' %s [command-options]' % (command_str) |
1 | 32 description = description or _class.__doc__ |
33 OptionParser.__init__(self, usage=usage, description=description) | |
34 commands = [ getattr(_class, i) for i in dir(_class) | |
35 if not i.startswith('_') ] | |
36 commands = [ method for method in commands | |
37 if hasattr(method, '__call__') ] | |
38 for _command in commands: | |
39 c = self.command(_command) | |
40 self.commands[c['name']] = c | |
41 | |
42 # get class options | |
43 self.command2parser(init, self) | |
44 self.disable_interspersed_args() | |
45 | |
46 def add_option(self, *args, **kwargs): | |
47 kwargs['default'] = Undefined(kwargs.get('default')) | |
48 OptionParser.add_option(self, *args, **kwargs) | |
49 | |
50 def print_help(self): | |
3 | 51 |
1 | 52 OptionParser.print_help(self) |
3 | 53 |
1 | 54 # short descriptions for commands |
55 command_descriptions = [dict(name=i, | |
56 description=self.commands[i]['doc'].strip().split('\n',1)[0]) | |
57 for i in self.commands.keys()] | |
58 command_descriptions.append(dict(name='help', description='print help for a given command')) | |
59 command_descriptions.sort(key=lambda x: x['name']) | |
60 max_len = max([len(i['name']) for i in command_descriptions]) | |
61 description = "Commands: \n%s" % ('\n'.join([' %s%s %s' % (description['name'], ' ' * (max_len - len(description['name'])), description['description']) | |
62 for description in command_descriptions])) | |
63 | |
64 print | |
65 print description | |
66 | |
67 def parse(self, args=sys.argv[1:]): | |
68 """global parse step""" | |
3 | 69 |
1 | 70 self.options, args = self.parse_args(args) |
71 | |
72 # help/sanity check -- should probably be separated | |
73 if not len(args): | |
74 self.print_help() | |
75 sys.exit(0) | |
76 if args[0] == 'help': | |
77 if len(args) == 2: | |
78 if args[1] == 'help': | |
79 self.print_help() | |
80 elif args[1] in self.commands: | |
81 name = args[1] | |
82 commandparser = self.command2parser(name) | |
83 commandparser.print_help() | |
84 else: | |
85 self.error("No command '%s'" % args[1]) | |
86 else: | |
87 self.print_help() | |
88 sys.exit(0) | |
8
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
89 required = len(self.init_args) + 1 # command |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
90 if len(args) < required: |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
91 self.print_usage() |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
92 sys.exit(1) |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
93 self.command_args = args[:len(self.init_args)] |
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
94 args = args[len(self.init_args):] |
1 | 95 command = args[0] |
96 if command not in self.commands: | |
97 self.error("No command '%s'" % command) | |
98 return command, args[1:] | |
99 | |
100 def invoke(self, args=sys.argv[1:]): | |
101 """ | |
102 invoke | |
103 """ | |
104 | |
105 # parse | |
8
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
106 name, args = self.parse(args) |
1 | 107 |
108 # setup | |
109 options = {} | |
110 dotfile = os.path.join(os.environ['HOME'], '.' + self.get_prog_name()) | |
111 if os.path.exists(dotfile): | |
112 f = file(dotfile) | |
113 for line in f.readlines(): | |
114 line = line.strip() | |
115 if not line: | |
116 continue | |
117 if ':' in line: | |
118 key, value = [i.strip() | |
119 for i in line.split(':', 1)] | |
120 options[key] = value | |
121 else: | |
122 print >> sys.stderr, "Bad option line: " + line | |
123 for key, value in self.options.__dict__.items(): | |
124 if isinstance(value, Undefined): | |
125 if key in options: | |
126 continue | |
127 options[key] = value.default | |
128 else: | |
129 options[key] = value | |
8
109627b7db9f
add ability to have mandatory class arguments
Jeff Hammel <jhammel@mozilla.com>
parents:
5
diff
changeset
|
130 _object = self._class(*self.command_args, **options) |
1 | 131 |
132 # command specific args | |
133 command = self.commands[name] | |
134 commandparser = self.command2parser(name) | |
135 command_options, command_args = commandparser.parse_args(args) | |
136 if len(command_args) < len(command['args']): | |
137 commandparser.error("Not enough arguments given") | |
138 if len(command_args) != len(command['args']) and not command['varargs']: | |
139 commandparser.error("Too many arguments given") | |
140 | |
141 # invoke the command | |
142 retval = getattr(_object, name)(*command_args, **command_options.__dict__) | |
143 if isinstance(retval, basestring): | |
144 print retval | |
145 elif retval is None: | |
146 pass | |
147 elif isinstance(retval, list): | |
148 for i in retval: | |
149 print i | |
150 elif isinstance(retval, dict): | |
151 try: | |
152 print json.dumps(retval, indent=2, sort_keys=True) | |
153 except: | |
154 pprint(retval) | |
155 else: | |
156 pprint(retval) | |
157 return retval | |
158 | |
159 def command(self, function): | |
160 name = function.func_name | |
161 if function.__doc__: | |
162 doc = inspect.cleandoc(function.__doc__) | |
163 else: | |
164 doc = '' | |
165 argspec = inspect.getargspec(function) | |
166 defaults = argspec.defaults | |
167 if defaults: | |
168 args = argspec.args[1:-len(defaults)] | |
169 optional = dict(zip(argspec.args[-len(defaults):], defaults)) | |
170 else: | |
171 args = argspec.args[1:] | |
172 optional = None | |
5 | 173 command = {'doc': doc, |
174 'name': name, | |
175 'args': args, | |
176 'optional': optional, | |
177 'varargs': argspec.varargs | |
178 } | |
1 | 179 return command |
180 | |
181 def commandargs2str(self, command): | |
182 if isinstance(command, basestring): | |
183 command = self.commands[command] | |
184 retval = [] | |
185 retval.extend(['<%s>' % arg for arg in command['args']]) | |
186 varargs = command['varargs'] | |
187 if varargs: | |
188 retval.append('<%s> [%s] [...]' % (varargs, varargs)) | |
189 if command['optional']: | |
190 retval.append('[options]') | |
191 return ' '.join(retval) | |
192 | |
193 def doc2arghelp(self, docstring, decoration='-', delimeter=':'): | |
194 """ | |
195 Parse a docstring and get at the section describing arguments | |
196 - decoration: decoration character | |
197 - delimeter: delimter character | |
3 | 198 |
1 | 199 Yields a tuple of the stripped docstring and the arguments help |
200 dictionary | |
201 """ | |
202 lines = [ i.strip() for i in docstring.split('\n') ] | |
203 argdict = {} | |
204 doc = [] | |
205 option = None | |
206 for line in lines: | |
207 if not line and option: # blank lines terminate [?] | |
208 break | |
209 if line.startswith(decoration) and delimeter in line: | |
210 name, description = line.split(delimeter, 1) | |
211 name = name.lstrip(decoration).strip() | |
212 description = description.strip() | |
213 argdict[name] = [ description ] | |
214 option = name | |
215 else: | |
216 if option: | |
217 argdict[name].append(line) | |
218 else: | |
219 doc.append(line) | |
220 argdict = dict([(key, ' '.join(value)) | |
221 for key, value in argdict.items()]) | |
222 return ('\n'.join(doc), argdict) | |
223 | |
224 def command2parser(self, command, parser=None): | |
225 if isinstance(command, basestring): | |
226 command = self.commands[command] | |
227 doc, argdict = self.doc2arghelp(command['doc']) | |
228 if parser is None: | |
229 parser = OptionParser('%%prog %s %s' % (command['name'], self.commandargs2str(command)), | |
230 description=doc, add_help_option=False) | |
231 if command['optional']: | |
232 for key, value in command['optional'].items(): | |
233 help = argdict.get(key, '') | |
234 if value is True: | |
235 parser.add_option('--no-%s' % key, dest=key, | |
236 action='store_false', default=True, | |
237 help=help) | |
238 elif value is False: | |
239 parser.add_option('--%s' % key, action='store_true', | |
240 default=False, help=help) | |
4 | 241 elif isinstance(value, int): |
242 help += ' [DEFAULT: %s]' % value | |
243 parser.add_option('--%s' % key, help=help, | |
244 type='int', default=value) | |
1 | 245 elif type(value) in set([type(()), type([])]): |
246 if value: | |
247 help += ' [DEFAULT: %s]' % value | |
248 parser.add_option('--%s' % key, action='append', | |
249 default=list(value), | |
250 help=help) | |
251 else: | |
252 if value is not None: | |
253 help += ' [DEFAULT: %s]' % value | |
254 parser.add_option('--%s' % key, help=help, default=value) | |
3 | 255 |
1 | 256 return parser |