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