1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
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.
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.
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/>.
19 """The `command` module provides :class:`Command`\s and
20 :class:`Argument`\s for defining commands.
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.
34 class CommandExit (Exception):
37 class Success (CommandExit):
41 """The command requests an end to the interpreter session.
45 class Failure (CommandExit):
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()
54 self.exception = exception
55 self.traceback = traceback_string
56 self.__setstate__(self.__getstate__())
58 def __getstate__(self):
59 """Return a picklable representation of the objects state.
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
66 See `pickling class instances`_ and `pickling examples`_.
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
73 return {'exception':self.exception, 'traceback':self.traceback}
75 def __setstate__(self, state):
76 """Apply the picklable state from :meth:`__getstate__` to
77 reconstruct the instance.
79 for key,value in state.items():
80 setattr(self, key, value)
81 self.args = (self.traceback + str(self.exception),)
84 class Command (object):
85 """One-line command description here.
87 >>> c = Command(name='test', help='An example Command.')
89 >>> status = c.run(hooke, NullQueue(), PrintQueue(),
90 ... help=True) # doctest: +REPORT_UDIFF
96 help BOOL (bool) Print a help message.
102 def __init__(self, name, aliases=None, arguments=[], help='',
104 # TODO: see_also=[other,command,instances,...]
108 self.aliases = aliases
110 Argument(name='help', type='bool', default=False, count=1,
111 help='Print a help message.'),
116 def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
117 """`Normalize inputs and handle <Argument help> before punting
121 inqueue = NullQueue()
123 outqueue = NullQueue()
125 params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
126 if params['help'] == True:
127 outqueue.put(self.help())
129 self._run(hooke, inqueue, outqueue, params)
130 except CommandExit, e:
131 if isinstance(e, Failure):
134 # other CommandExit subclasses fall through to the end
136 x = UncaughtException(e)
144 def _run(self, hooke, inqueue, outqueue, params):
145 """This is where the command-specific magic will happen.
149 def handle_arguments(self, hooke, inqueue, outqueue, params):
150 """Normalize and validate input parameters (:class:`Argument` values).
152 for argument in self.arguments:
153 names = [argument.name] + argument.aliases
154 settings = [(name,v) for name,v in params.items() if name in names]
155 num_provided = len(settings)
156 if num_provided == 0:
157 if argument.optional == True or argument.count == 0:
158 settings = [(argument.name, argument.default)]
160 raise Failure('Required argument %s not set.'
163 raise Failure('Multiple settings for %s:\n %s'
165 '\n '.join(['%s: %s' % (name,value)
166 for name,value in sorted(settings)])))
167 name,value = settings[0]
168 if num_provided == 0:
169 params[argument.name] = value
171 if name != argument.name:
173 params[argument.name] = value
174 if argument.callback != None:
175 value = argument.callback(hooke, self, argument, value)
176 params[argument.name] = value
177 argument.validate(value)
180 def help(self, name_fn=lambda name:name):
181 """Return a help message describing the `Command`.
183 `name_fn(internal_name) -> external_name` gives calling
184 :class:`hooke.ui.UserInterface`\s a means of changing the
185 display names if it wants (e.g. to remove spaces from command
188 name_part = 'Command: %s' % name_fn(self.name)
189 if len(self.aliases) > 0:
190 name_part += ' (%s)' % ', '.join(
191 [name_fn(n) for n in self.aliases])
193 if len(self.arguments) > 0:
194 argument_part = ['Arguments:', '']
195 for a in self.arguments:
196 argument_part.append(textwrap.fill(
199 subsequent_indent=" "))
200 argument_part = '\n'.join(argument_part)
201 parts.append(argument_part)
202 parts.append(self._help) # help part
203 return '\n\n'.join(parts)
205 class Argument (object):
206 """Structured user input for :class:`Command`\s.
208 TODO: ranges for `count`?
210 def __init__(self, name, aliases=None, type='string', metavar=None,
211 default=None, optional=True, count=1,
212 completion_callback=None, callback=None, help=''):
216 self.aliases = aliases
219 metavar = type.upper()
220 self.metavar = metavar
221 self.default = default
222 self.optional = optional
224 self.completion_callback = completion_callback
225 self.callback = callback
229 return '<%s %s>' % (self.__class__.__name__, self.name)
232 return self.__str__()
234 def help(self, name_fn=lambda name:name):
235 """Return a help message describing the `Argument`.
237 `name_fn(internal_name) -> external_name` gives calling
238 :class:`hooke.ui.UserInterface`\s a means of changing the
239 display names if it wants (e.g. to remove spaces from command
242 parts = ['%s ' % name_fn(self.name)]
243 if self.metavar != None:
244 parts.append('%s ' % self.metavar)
245 parts.extend(['(%s) ' % self.type, self._help])
246 return ''.join(parts)
248 def validate(self, value):
249 """If `value` is not appropriate, raise `ValueError`.
251 pass # TODO: validation
253 # TODO: type conversion
255 # TODO: type extensions?
259 class StoreValue (object):
260 def __init__(self, value):
262 def __call__(self, hooke, command, argument, fragment=None):
265 class NullQueue (queue.Queue):
266 """The :class:`queue.Queue` equivalent of `/dev/null`.
268 This is a bottomless pit. Items go in, but never come out.
270 def get(self, block=True, timeout=None):
271 """Raise queue.Empty.
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
280 def put(self, item, block=True, timeout=None):
281 """Dump an item into the void.
283 Block and timeout are meaningless, because there is always a
284 free slot available in a bottomless pit.
288 class PrintQueue (NullQueue):
289 """Debugging :class:`NullQueue` that prints items before dropping
292 def put(self, item, block=True, timeout=None):
293 """Print `item` and then dump it into the void.
295 print 'ITEM:\n%s' % item