1 """The `command` module provides :class:`Command`\s and
2 :class:`Argument`\s for defining commands.
11 class CommandExit (Exception):
14 class Success (CommandExit):
18 """The command requests an end to the interpreter session.
22 class Failure (CommandExit):
25 class UncaughtException (Failure):
26 def __init__(self, exception, traceback_string=None):
27 super(UncaughtException, self).__init__()
28 if traceback_string == None:
29 traceback_string = traceback.format_exc()
31 self.exception = exception
32 self.traceback = traceback_string
33 self.__setstate__(self.__getstate__())
35 def __getstate__(self):
36 """Return a picklable representation of the objects state.
38 :mod:`pickle`'s doesn't call a :meth:`__init__` when
39 rebuilding a class instance. To preserve :attr:`args` through
40 a pickle cycle, we use :meth:`__getstate__` and
43 See `pickling class instances`_ and `pickling examples`_.
45 .. _pickling class instances:
46 http://docs.python.org/library/pickle.html#pickling-and-unpickling-normal-class-instances
47 .. _pickling examples:
48 http://docs.python.org/library/pickle.html#example
50 return {'exception':self.exception, 'traceback':self.traceback}
52 def __setstate__(self, state):
53 """Apply the picklable state from :meth:`__getstate__` to
54 reconstruct the instance.
56 for key,value in state.items():
57 setattr(self, key, value)
58 self.args = (self.traceback + str(self.exception),)
60 class Interaction (object):
61 """Mid-command inter-process interaction.
65 class Request (Interaction):
66 """Command engine requests for information from the UI.
68 def __init__(self, msg, default=None):
69 super(Request, self).__init__()
71 self.default = default
73 class Response (Interaction):
74 """UI response to a :class:`Request`.
76 def __init__(self, value):
77 super(Response, self).__init__()
80 class BooleanRequest (Request):
83 class BooleanResponse (Response):
86 class Command (object):
87 """One-line command description here.
89 >>> c = Command(name='test', help='An example Command.')
90 >>> status = c.run(NullQueue(), PrintQueue(), help=True) # doctest: +REPORT_UDIFF
96 help BOOL (bool) Print a help message.
102 def __init__(self, name, aliases=None, arguments=[], help=''):
106 self.aliases = aliases
108 Argument(name='help', type='bool', default=False, count=1,
109 callback=StoreValue(True), help='Print a help message.'),
113 def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
114 """`Normalize inputs and handle <Argument help> before punting
118 inqueue = NullQueue()
120 outqueue = NullQueue()
122 params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
123 if params['help'] == True:
124 outqueue.put(self.help())
126 self._run(hooke, inqueue, outqueue, params)
127 except CommandExit, e:
128 if isinstance(e, Failure):
131 # other CommandExit subclasses fall through to the end
133 x = UncaughtException(e)
141 def _run(self, inqueue, outqueue, params):
142 """This is where the command-specific magic will happen.
146 def handle_arguments(self, hooke, inqueue, outqueue, params):
147 """Normalize and validate input parameters (:class:`Argument` values).
149 for argument in self.arguments:
150 names = [argument.name] + argument.aliases
151 settings = [(name,v) for name,v in params.items() if name in names]
152 num_provided = len(settings)
153 if num_provided == 0:
154 if argument.optional == True or argument.count == 0:
155 settings = [(argument.name, argument.default)]
157 raise Failure('Required argument %s not set.'
160 raise Failure('Multiple settings for %s:\n %s'
162 '\n '.join(['%s: %s' % (name,value)
163 for name,value in sorted(settings)])))
164 name,value = settings[0]
165 if num_provided == 0:
166 params[argument.name] = value
168 if name != argument.name:
170 params[argument.name] = value
171 if argument.callback != None:
172 value = argument.callback(hooke, self, argument, value)
173 params[argument.name] = value
174 argument.validate(value)
177 def help(self, name_fn=lambda name:name):
178 """Return a help message describing the `Command`.
180 `name_fn(internal_name) -> external_name` gives calling
181 :class:`hooke.ui.UserInterface`\s a means of changing the
182 display names if it wants (e.g. to remove spaces from command
185 name_part = 'Command: %s' % name_fn(self.name)
186 if len(self.aliases) > 0:
187 name_part += ' (%s)' % ', '.join(
188 [name_fn(n) for n in self.aliases])
190 if len(self.arguments) > 0:
191 argument_part = ['Arguments:', '']
192 for a in self.arguments:
193 argument_part.append(textwrap.fill(
196 subsequent_indent=" "))
197 argument_part = '\n'.join(argument_part)
198 parts.append(argument_part)
199 parts.append(self._help) # help part
200 return '\n\n'.join(parts)
202 class Argument (object):
203 """Structured user input for :class:`Command`\s.
205 TODO: ranges for `count`?
207 def __init__(self, name, aliases=None, type='string', metavar=None,
208 default=None, optional=True, count=1,
209 completion_callback=None, callback=None, help=''):
213 self.aliases = aliases
216 metavar = type.upper()
217 self.metavar = metavar
218 self.default = default
219 self.optional = optional
221 self.completion_callback = completion_callback
222 self.callback = callback
226 return '<%s %s>' % (self.__class__.__name__, self.name)
229 return self.__str__()
231 def help(self, name_fn=lambda name:name):
232 """Return a help message describing the `Argument`.
234 `name_fn(internal_name) -> external_name` gives calling
235 :class:`hooke.ui.UserInterface`\s a means of changing the
236 display names if it wants (e.g. to remove spaces from command
239 parts = ['%s ' % name_fn(self.name)]
240 if self.metavar != None:
241 parts.append('%s ' % self.metavar)
242 parts.extend(['(%s) ' % self.type, self._help])
243 return ''.join(parts)
245 def validate(self, value):
246 """If `value` is not appropriate, raise `ValueError`.
248 pass # TODO: validation
250 # TODO: type conversion
252 # TODO: type extensions?
256 class StoreValue (object):
257 def __init__(self, value):
259 def __call__(self, hooke, command, argument, fragment=None):
262 class NullQueue (queue.Queue):
263 """The :class:`queue.Queue` equivalent of `/dev/null`.
265 This is a bottomless pit. Items go in, but never come out.
267 def get(self, block=True, timeout=None):
268 """Raise queue.Empty.
270 There's really no need to override the base Queue.get, but I
271 want to know if someone tries to read from a NullQueue. With
272 the default implementation they would just block silently
277 def put(self, item, block=True, timeout=None):
278 """Dump an item into the void.
280 Block and timeout are meaningless, because there is always a
281 free slot available in a bottomless pit.
285 class PrintQueue (NullQueue):
286 """Debugging :class:`NullQueue` that prints items before dropping
289 def put(self, item, block=True, timeout=None):
290 """Print `item` and then dump it into the void.
292 print 'ITEM:\n%s' % item