Merged my unitary FFT wrappers (FFT_tools) as hooke.util.fft.
[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         # TODO: see_also=[other,command,instances,...]
104         self.name = name
105         if aliases == None:
106             aliases = []
107         self.aliases = aliases
108         self.arguments = [
109             Argument(name='help', type='bool', default=False, count=1,
110                      help='Print a help message.'),
111             ] + arguments
112         self._help = help
113
114     def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
115         """`Normalize inputs and handle <Argument help> before punting
116         to :meth:`_run`.
117         """
118         if inqueue == None:
119             inqueue = NullQueue()
120         if outqueue == None:
121             outqueue = NullQueue()
122         try:
123             params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
124             if params['help'] == True:
125                 outqueue.put(self.help())
126                 raise(Success())
127             self._run(hooke, inqueue, outqueue, params)
128         except CommandExit, e:
129             if isinstance(e, Failure):
130                 outqueue.put(e)
131                 return 1
132             # other CommandExit subclasses fall through to the end
133         except Exception, e:
134             x = UncaughtException(e)
135             outqueue.put(x)
136             return 1
137         else:
138             e = Success()
139         outqueue.put(e)
140         return 0
141
142     def _run(self, inqueue, outqueue, params):
143         """This is where the command-specific magic will happen.
144         """
145         pass
146
147     def handle_arguments(self, hooke, inqueue, outqueue, params):
148         """Normalize and validate input parameters (:class:`Argument` values).
149         """
150         for argument in self.arguments:
151             names = [argument.name] + argument.aliases
152             settings = [(name,v) for name,v in params.items() if name in names]
153             num_provided = len(settings)
154             if num_provided == 0:
155                 if argument.optional == True or argument.count == 0:
156                     settings = [(argument.name, argument.default)]
157                 else:
158                     raise Failure('Required argument %s not set.'
159                                   % argument.name)
160             if num_provided > 1:
161                 raise Failure('Multiple settings for %s:\n  %s'
162                     % (argument.name,
163                        '\n  '.join(['%s: %s' % (name,value)
164                                     for name,value in sorted(settings)])))
165             name,value = settings[0]
166             if num_provided == 0:
167                 params[argument.name] = value
168             else:
169                 if name != argument.name:
170                     params.remove(name)
171                     params[argument.name] = value
172             if argument.callback != None:
173                 value = argument.callback(hooke, self, argument, value)
174                 params[argument.name] = value
175             argument.validate(value)
176         return params
177
178     def help(self, name_fn=lambda name:name):
179         """Return a help message describing the `Command`.
180
181         `name_fn(internal_name) -> external_name` gives calling
182         :class:`hooke.ui.UserInterface`\s a means of changing the
183         display names if it wants (e.g. to remove spaces from command
184         line tokens).
185         """
186         name_part = 'Command: %s' % name_fn(self.name)
187         if len(self.aliases) > 0:
188             name_part += ' (%s)' % ', '.join(
189                 [name_fn(n) for n in self.aliases])
190         parts = [name_part]
191         if len(self.arguments) > 0:
192             argument_part = ['Arguments:', '']
193             for a in self.arguments:
194                 argument_part.append(textwrap.fill(
195                         a.help(name_fn),
196                         initial_indent="",
197                         subsequent_indent="    "))
198             argument_part = '\n'.join(argument_part)
199             parts.append(argument_part)
200         parts.append(self._help) # help part
201         return '\n\n'.join(parts)
202
203 class Argument (object):
204     """Structured user input for :class:`Command`\s.
205     
206     TODO: ranges for `count`?
207     """
208     def __init__(self, name, aliases=None, type='string', metavar=None,
209                  default=None, optional=True, count=1,
210                  completion_callback=None, callback=None, help=''):
211         self.name = name
212         if aliases == None:
213             aliases = []
214         self.aliases = aliases
215         self.type = type
216         if metavar == None:
217             metavar = type.upper()
218         self.metavar = metavar
219         self.default = default
220         self.optional = optional
221         self.count = count
222         self.completion_callback = completion_callback
223         self.callback = callback
224         self._help = help
225
226     def __str__(self):
227         return '<%s %s>' % (self.__class__.__name__, self.name)
228
229     def __repr__(self):
230         return self.__str__()
231
232     def help(self, name_fn=lambda name:name):
233         """Return a help message describing the `Argument`.
234
235         `name_fn(internal_name) -> external_name` gives calling
236         :class:`hooke.ui.UserInterface`\s a means of changing the
237         display names if it wants (e.g. to remove spaces from command
238         line tokens).
239         """        
240         parts = ['%s ' % name_fn(self.name)]
241         if self.metavar != None:
242             parts.append('%s ' % self.metavar)
243         parts.extend(['(%s) ' % self.type, self._help])
244         return ''.join(parts)
245
246     def validate(self, value):
247         """If `value` is not appropriate, raise `ValueError`.
248         """
249         pass # TODO: validation
250
251     # TODO: type conversion
252
253 # TODO: type extensions?
254
255 # Useful callbacks
256
257 class StoreValue (object):
258     def __init__(self, value):
259         self.value = value
260     def __call__(self, hooke, command, argument, fragment=None):
261         return self.value
262
263 class NullQueue (queue.Queue):
264     """The :class:`queue.Queue` equivalent of `/dev/null`.
265
266     This is a bottomless pit.  Items go in, but never come out.
267     """
268     def get(self, block=True, timeout=None):
269         """Raise queue.Empty.
270         
271         There's really no need to override the base Queue.get, but I
272         want to know if someone tries to read from a NullQueue.  With
273         the default implementation they would just block silently
274         forever :(.
275         """
276         raise queue.Empty
277
278     def put(self, item, block=True, timeout=None):
279         """Dump an item into the void.
280
281         Block and timeout are meaningless, because there is always a
282         free slot available in a bottomless pit.
283         """
284         pass
285
286 class PrintQueue (NullQueue):
287     """Debugging :class:`NullQueue` that prints items before dropping
288     them.
289     """
290     def put(self, item, block=True, timeout=None):
291         """Print `item` and then dump it into the void.
292         """
293         print 'ITEM:\n%s' % item