Adjust hooke.command.UncaughtException to properly handle pickle reconstruction.
[hooke.git] / hooke / command.py
1 """The `command` module provides :class:`Command`\s and
2 :class:`Argument`\s for defining commands.
3 """
4
5 import Queue as queue
6 import sys
7 import textwrap
8 import traceback
9
10
11 class CommandExit (Exception):
12     pass
13
14 class Success (CommandExit):
15     pass
16
17 class Exit (Success):
18     """The command requests an end to the interpreter session.
19     """
20     pass
21
22 class Failure (CommandExit):
23     pass
24
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()
30             sys.exc_clear()
31         self.exception = exception
32         self.traceback = traceback_string
33         self.__setstate__(self.__getstate__())
34
35     def __getstate__(self):
36         """Return a picklable representation of the objects state.
37
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
41         :meth:`__setstate__`.
42
43         See `pickling class instances`_ and `pickling examples`_.
44
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
49         """
50         return {'exception':self.exception, 'traceback':self.traceback}
51
52     def __setstate__(self, state):
53         """Apply the picklable state from :meth:`__getstate__` to
54         reconstruct the instance.
55         """
56         for key,value in state.items():
57             setattr(self, key, value)
58         self.args = (self.traceback + str(self.exception),)
59
60 class Interaction (object):
61     """Mid-command inter-process interaction.
62     """
63     pass
64
65 class Request (Interaction):
66     """Command engine requests for information from the UI.
67     """
68     def __init__(self, msg, default=None):
69         super(Request, self).__init__()
70         self.msg = msg
71         self.default = default
72
73 class Response (Interaction):
74     """UI response to a :class:`Request`.
75     """
76     def __init__(self, value):
77         super(Response, self).__init__()
78         self.value = value
79
80 class BooleanRequest (Request):
81     pass
82
83 class BooleanResponse (Response):
84     pass
85
86 class Command (object):
87     """One-line command description here.
88
89     >>> c = Command(name='test', help='An example Command.')
90     >>> status = c.run(NullQueue(), PrintQueue(), help=True) # doctest: +REPORT_UDIFF
91     ITEM:
92     Command: test
93     <BLANKLINE>
94     Arguments:
95     <BLANKLINE>
96     help BOOL (bool) Print a help message.
97     <BLANKLINE>
98     An example Command.
99     ITEM:
100     Success
101     """
102     def __init__(self, name, aliases=None, arguments=[], help=''):
103         self.name = name
104         if aliases == None:
105             aliases = []
106         self.aliases = aliases
107         self.arguments = [
108             Argument(name='help', type='bool', default=False, count=1,
109                      callback=StoreValue(True), help='Print a help message.'),
110             ] + arguments
111         self._help = help
112
113     def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
114         """`Normalize inputs and handle <Argument help> before punting
115         to :meth:`_run`.
116         """
117         if inqueue == None:
118             inqueue = NullQueue()
119         if outqueue == None:
120             outqueue = NullQueue()
121         try:
122             params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
123             if params['help'] == True:
124                 outqueue.put(self.help())
125                 raise(Success())
126             self._run(hooke, inqueue, outqueue, params)
127         except CommandExit, e:
128             if isinstance(e, Failure):
129                 outqueue.put(e)
130                 return 1
131             # other CommandExit subclasses fall through to the end
132         except Exception, e:
133             x = UncaughtException(e)
134             outqueue.put(x)
135             return 1
136         else:
137             e = Success()
138         outqueue.put(e)
139         return 0
140
141     def _run(self, inqueue, outqueue, params):
142         """This is where the command-specific magic will happen.
143         """
144         pass
145
146     def handle_arguments(self, hooke, inqueue, outqueue, params):
147         """Normalize and validate input parameters (:class:`Argument` values).
148         """
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)]
156                 else:
157                     raise Failure('Required argument %s not set.'
158                                   % argument.name)
159             if num_provided > 1:
160                 raise Failure('Multiple settings for %s:\n  %s'
161                     % (argument.name,
162                        '\n  '.join(['%s: %s' % (name,value)
163                                     for name,value in sorted(settings)])))
164             name,value = settings[0]
165             if name != argument.name:
166                 params.remove(name)
167                 params[argument.name] = value
168             if argument.callback != None:
169                 if num_provided > 0:
170                     value = argument.callback(hooke, self, argument, value)
171                 params[argument.name] = value
172             argument.validate(value)
173         return params
174
175     def help(self, name_fn=lambda name:name):
176         """Return a help message describing the `Command`.
177
178         `name_fn(internal_name) -> external_name` gives calling
179         :class:`hooke.ui.UserInterface`\s a means of changing the
180         display names if it wants (e.g. to remove spaces from command
181         line tokens).
182         """
183         name_part = 'Command: %s' % name_fn(self.name)
184         if len(self.aliases) > 0:
185             name_part += ' (%s)' % ', '.join(
186                 [name_fn(n) for n in self.aliases])
187         parts = [name_part]
188         if len(self.arguments) > 0:
189             argument_part = ['Arguments:', '']
190             for a in self.arguments:
191                 argument_part.append(textwrap.fill(
192                         a.help(name_fn),
193                         initial_indent="",
194                         subsequent_indent="    "))
195             argument_part = '\n'.join(argument_part)
196             parts.append(argument_part)
197         parts.append(self._help) # help part
198         return '\n\n'.join(parts)
199
200 class Argument (object):
201     """Structured user input for :class:`Command`\s.
202     
203     TODO: ranges for `count`?
204     """
205     def __init__(self, name, aliases=None, type='string', metavar=None,
206                  default=None, optional=True, count=1,
207                  completion_callback=None, callback=None, help=''):
208         self.name = name
209         if aliases == None:
210             aliases = []
211         self.aliases = aliases
212         self.type = type
213         if metavar == None:
214             metavar = type.upper()
215         self.metavar = metavar
216         self.default = default
217         self.optional = optional
218         self.count = count
219         self.completion_callback = completion_callback
220         self.callback = callback
221         self._help = help
222
223     def __str__(self):
224         return '<%s %s>' % (self.__class__.__name__, self.name)
225
226     def __repr__(self):
227         return self.__str__()
228
229     def help(self, name_fn=lambda name:name):
230         """Return a help message describing the `Argument`.
231
232         `name_fn(internal_name) -> external_name` gives calling
233         :class:`hooke.ui.UserInterface`\s a means of changing the
234         display names if it wants (e.g. to remove spaces from command
235         line tokens).
236         """        
237         parts = ['%s ' % name_fn(self.name)]
238         if self.metavar != None:
239             parts.append('%s ' % self.metavar)
240         parts.extend(['(%s) ' % self.type, self._help])
241         return ''.join(parts)
242
243     def validate(self, value):
244         """If `value` is not appropriate, raise `ValueError`.
245         """
246         pass # TODO: validation
247
248     # TODO: type conversion
249
250 # TODO: type extensions?
251
252 # Useful callbacks
253
254 class StoreValue (object):
255     def __init__(self, value):
256         self.value = value
257     def __call__(self, hooke, command, argument, fragment=None):
258         return self.value
259
260 class NullQueue (queue.Queue):
261     """The :class:`queue.Queue` equivalent of `/dev/null`.
262
263     This is a bottomless pit.  Items go in, but never come out.
264     """
265     def get(self, block=True, timeout=None):
266         """Raise queue.Empty.
267         
268         There's really no need to override the base Queue.get, but I
269         want to know if someone tries to read from a NullQueue.  With
270         the default implementation they would just block silently
271         forever :(.
272         """
273         raise queue.Empty
274
275     def put(self, item, block=True, timeout=None):
276         """Dump an item into the void.
277
278         Block and timeout are meaningless, because there is always a
279         free slot available in a bottomless pit.
280         """
281         pass
282
283 class PrintQueue (NullQueue):
284     """Debugging :class:`NullQueue` that prints items before dropping
285     them.
286     """
287     def put(self, item, block=True, timeout=None):
288         """Print `item` and then dump it into the void.
289         """
290         print 'ITEM:\n%s' % item