Ran update_copyright.py, updating all the copyright blurbs and adding AUTHORS.
[hooke.git] / hooke / command.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation, either
8 # version 3 of the License, or (at your option) any later version.
9 #
10 # Hooke is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke.  If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """The `command` module provides :class:`Command`\s and
20 :class:`Argument`\s for defining commands.
21
22 It also provides :class:`CommandExit` and subclasses for communicating
23 command completion information between
24 :class:`hooke.engine.CommandEngine`\s and
25 :class:`hooke.ui.UserInterface`\s.
26 """
27
28 import Queue as queue
29 import sys
30 import textwrap
31 import traceback
32
33
34 class CommandExit (Exception):
35     pass
36
37 class Success (CommandExit):
38     pass
39
40 class Exit (Success):
41     """The command requests an end to the interpreter session.
42     """
43     pass
44
45 class Failure (CommandExit):
46     pass
47
48 class UncaughtException (Failure):
49     def __init__(self, exception, traceback_string=None):
50         super(UncaughtException, self).__init__()
51         if traceback_string == None:
52             traceback_string = traceback.format_exc()
53             sys.exc_clear()
54         self.exception = exception
55         self.traceback = traceback_string
56         self.__setstate__(self.__getstate__())
57
58     def __getstate__(self):
59         """Return a picklable representation of the objects state.
60
61         :mod:`pickle`'s doesn't call a :meth:`__init__` when
62         rebuilding a class instance.  To preserve :attr:`args` through
63         a pickle cycle, we use :meth:`__getstate__` and
64         :meth:`__setstate__`.
65
66         See `pickling class instances`_ and `pickling examples`_.
67
68         .. _pickling class instances:
69           http://docs.python.org/library/pickle.html#pickling-and-unpickling-normal-class-instances
70         .. _pickling examples:
71           http://docs.python.org/library/pickle.html#example
72         """
73         return {'exception':self.exception, 'traceback':self.traceback}
74
75     def __setstate__(self, state):
76         """Apply the picklable state from :meth:`__getstate__` to
77         reconstruct the instance.
78         """
79         for key,value in state.items():
80             setattr(self, key, value)
81         self.args = (self.traceback + str(self.exception),)
82
83
84 class Command (object):
85     """One-line command description here.
86
87     >>> c = Command(name='test', help='An example Command.')
88     >>> hooke = None
89     >>> status = c.run(hooke, NullQueue(), PrintQueue(),
90     ...                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     <BLANKLINE>
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                      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 num_provided == 0:
166                 params[argument.name] = value
167             else:
168                 if name != argument.name:
169                     params.remove(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)
175         return params
176
177     def help(self, name_fn=lambda name:name):
178         """Return a help message describing the `Command`.
179
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
183         line tokens).
184         """
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])
189         parts = [name_part]
190         if len(self.arguments) > 0:
191             argument_part = ['Arguments:', '']
192             for a in self.arguments:
193                 argument_part.append(textwrap.fill(
194                         a.help(name_fn),
195                         initial_indent="",
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)
201
202 class Argument (object):
203     """Structured user input for :class:`Command`\s.
204     
205     TODO: ranges for `count`?
206     """
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=''):
210         self.name = name
211         if aliases == None:
212             aliases = []
213         self.aliases = aliases
214         self.type = type
215         if metavar == None:
216             metavar = type.upper()
217         self.metavar = metavar
218         self.default = default
219         self.optional = optional
220         self.count = count
221         self.completion_callback = completion_callback
222         self.callback = callback
223         self._help = help
224
225     def __str__(self):
226         return '<%s %s>' % (self.__class__.__name__, self.name)
227
228     def __repr__(self):
229         return self.__str__()
230
231     def help(self, name_fn=lambda name:name):
232         """Return a help message describing the `Argument`.
233
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
237         line tokens).
238         """        
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)
244
245     def validate(self, value):
246         """If `value` is not appropriate, raise `ValueError`.
247         """
248         pass # TODO: validation
249
250     # TODO: type conversion
251
252 # TODO: type extensions?
253
254 # Useful callbacks
255
256 class StoreValue (object):
257     def __init__(self, value):
258         self.value = value
259     def __call__(self, hooke, command, argument, fragment=None):
260         return self.value
261
262 class NullQueue (queue.Queue):
263     """The :class:`queue.Queue` equivalent of `/dev/null`.
264
265     This is a bottomless pit.  Items go in, but never come out.
266     """
267     def get(self, block=True, timeout=None):
268         """Raise queue.Empty.
269         
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
273         forever :(.
274         """
275         raise queue.Empty
276
277     def put(self, item, block=True, timeout=None):
278         """Dump an item into the void.
279
280         Block and timeout are meaningless, because there is always a
281         free slot available in a bottomless pit.
282         """
283         pass
284
285 class PrintQueue (NullQueue):
286     """Debugging :class:`NullQueue` that prints items before dropping
287     them.
288     """
289     def put(self, item, block=True, timeout=None):
290         """Print `item` and then dump it into the void.
291         """
292         print 'ITEM:\n%s' % item