1 # Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Hooke. If not, see <http://www.gnu.org/licenses/>.
18 """The `command` module provides :class:`Command`\s and
19 :class:`Argument`\s for defining commands.
21 It also provides :class:`CommandExit` and subclasses for communicating
22 command completion information between
23 :class:`hooke.engine.CommandEngine`\s and
24 :class:`hooke.ui.UserInterface`\s.
33 class CommandExit (Exception):
36 class Success (CommandExit):
40 """The command requests an end to the interpreter session.
44 class Failure (CommandExit):
47 class UncaughtException (Failure):
48 def __init__(self, exception, traceback_string=None):
49 super(UncaughtException, self).__init__()
50 if traceback_string == None:
51 traceback_string = traceback.format_exc()
53 self.exception = exception
54 self.traceback = traceback_string
55 self.__setstate__(self.__getstate__())
57 def __getstate__(self):
58 """Return a picklable representation of the objects state.
60 :mod:`pickle`'s doesn't call a :meth:`__init__` when
61 rebuilding a class instance. To preserve :attr:`args` through
62 a pickle cycle, we use :meth:`__getstate__` and
65 See `pickling class instances`_ and `pickling examples`_.
67 .. _pickling class instances:
68 http://docs.python.org/library/pickle.html#pickling-and-unpickling-normal-class-instances
69 .. _pickling examples:
70 http://docs.python.org/library/pickle.html#example
72 return {'exception':self.exception, 'traceback':self.traceback}
74 def __setstate__(self, state):
75 """Apply the picklable state from :meth:`__getstate__` to
76 reconstruct the instance.
78 for key,value in state.items():
79 setattr(self, key, value)
80 self.args = (self.traceback + str(self.exception),)
83 class Command (object):
84 """One-line command description here.
86 >>> c = Command(name='test', help='An example Command.')
88 >>> status = c.run(hooke, NullQueue(), PrintQueue(),
89 ... help=True) # doctest: +REPORT_UDIFF
95 help BOOL (bool) Print a help message.
96 stack BOOL (bool) Add this command to appropriate command stacks.
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.'),
112 Argument(name='stack', type='bool', default=True, count=1,
113 help='Add this command to appropriate command stacks.'),
118 def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
119 """`Normalize inputs and handle <Argument help> before punting
123 inqueue = NullQueue()
125 outqueue = NullQueue()
127 params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
128 if params['help'] == True:
129 outqueue.put(self.help())
131 self._run(hooke, inqueue, outqueue, params)
132 except CommandExit, e:
133 if isinstance(e, Failure):
136 # other CommandExit subclasses fall through to the end
138 x = UncaughtException(e)
146 def _run(self, hooke, inqueue, outqueue, params):
147 """This is where the command-specific magic will happen.
151 def handle_arguments(self, hooke, inqueue, outqueue, params):
152 """Normalize and validate input parameters (:class:`Argument` values).
154 for argument in self.arguments:
155 names = [argument.name] + argument.aliases
156 settings = [(name,v) for name,v in params.items() if name in names]
157 num_provided = len(settings)
158 if num_provided == 0:
159 if argument.optional == True or argument.count == 0:
160 settings = [(argument.name, argument.default)]
162 raise Failure('Required argument %s not set.'
165 raise Failure('Multiple settings for %s:\n %s'
167 '\n '.join(['%s: %s' % (name,value)
168 for name,value in sorted(settings)])))
169 name,value = settings[0]
170 if num_provided == 0:
171 params[argument.name] = value
173 if name != argument.name:
175 params[argument.name] = value
176 if argument.callback != None:
177 value = argument.callback(hooke, self, argument, value)
178 params[argument.name] = value
179 argument.validate(value)
182 def help(self, name_fn=lambda name:name):
183 """Return a help message describing the `Command`.
185 `name_fn(internal_name) -> external_name` gives calling
186 :class:`hooke.ui.UserInterface`\s a means of changing the
187 display names if it wants (e.g. to remove spaces from command
190 name_part = 'Command: %s' % name_fn(self.name)
191 if len(self.aliases) > 0:
192 name_part += ' (%s)' % ', '.join(
193 [name_fn(n) for n in self.aliases])
195 if len(self.arguments) > 0:
196 argument_part = ['Arguments:', '']
197 for a in self.arguments:
198 argument_part.append(textwrap.fill(
201 subsequent_indent=" "))
202 argument_part = '\n'.join(argument_part)
203 parts.append(argument_part)
204 parts.append(self._help) # help part
205 return '\n\n'.join(parts)
207 class Argument (object):
208 """Structured user input for :class:`Command`\s.
210 TODO: ranges for `count`?
212 def __init__(self, name, aliases=None, type='string', metavar=None,
213 default=None, optional=True, count=1,
214 completion_callback=None, callback=None, help=''):
218 self.aliases = aliases
221 metavar = type.upper()
222 self.metavar = metavar
223 self.default = default
224 self.optional = optional
226 self.completion_callback = completion_callback
227 self.callback = callback
231 return '<%s %s>' % (self.__class__.__name__, self.name)
234 return self.__str__()
236 def help(self, name_fn=lambda name:name):
237 """Return a help message describing the `Argument`.
239 `name_fn(internal_name) -> external_name` gives calling
240 :class:`hooke.ui.UserInterface`\s a means of changing the
241 display names if it wants (e.g. to remove spaces from command
244 parts = ['%s ' % name_fn(self.name)]
245 if self.metavar != None:
246 parts.append('%s ' % self.metavar)
247 parts.extend(['(%s) ' % self.type, self._help])
248 return ''.join(parts)
250 def validate(self, value):
251 """If `value` is not appropriate, raise `ValueError`.
253 pass # TODO: validation
258 class StoreValue (object):
259 def __init__(self, value):
261 def __call__(self, hooke, command, argument, fragment=None):
264 class NullQueue (queue.Queue):
265 """The :class:`queue.Queue` equivalent of `/dev/null`.
267 This is a bottomless pit. Items go in, but never come out.
269 def get(self, block=True, timeout=None):
270 """Raise queue.Empty.
272 There's really no need to override the base Queue.get, but I
273 want to know if someone tries to read from a NullQueue. With
274 the default implementation they would just block silently
279 def put(self, item, block=True, timeout=None):
280 """Dump an item into the void.
282 Block and timeout are meaningless, because there is always a
283 free slot available in a bottomless pit.
287 class PrintQueue (NullQueue):
288 """Debugging :class:`NullQueue` that prints items before dropping
291 def put(self, item, block=True, timeout=None):
292 """Print `item` and then dump it into the void.
294 print('ITEM:\n{}'.format(item))