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