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