1 """The `command` module provides :class:`Command`\s and
2 :class:`Argument`\s for defining commands.
11 class CommandExit (Exception):
14 class Success (CommandExit):
18 """The command requests an end to the interpreter session.
22 class Failure (CommandExit):
25 class UncaughtException (Failure):
26 def __init__(self, exception):
27 self.exception = exception
28 self.exc_string = traceback.format_exc()
30 super(UncaughtException, self).__init__(self.exc_string)
32 class Interaction (object):
33 """Mid-command inter-process interaction.
37 class Request (Interaction):
38 """Command engine requests for information from the UI.
40 def __init__(self, msg, default=None):
41 super(Request, self).__init__()
43 self.default = default
45 class Response (Interaction):
46 """UI response to a :class:`Request`.
48 def __init__(self, value):
49 super(Response, self).__init__()
52 class BooleanRequest (Request):
55 class BooleanResponse (Response):
58 class Command (object):
59 """One-line command description here.
61 >>> c = Command(name='test', help='An example Command.')
62 >>> status = c.run(NullQueue(), PrintQueue(), help=True) # doctest: +REPORT_UDIFF
68 help BOOL (bool) Print a help message.
74 def __init__(self, name, aliases=None, arguments=[], help=''):
78 self.aliases = aliases
80 Argument(name='help', type='bool', default=False, count=1,
81 callback=StoreValue(True), help='Print a help message.'),
85 def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
86 """`Normalize inputs and handle <Argument help> before punting
92 outqueue = NullQueue()
94 params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
95 if params['help'] == True:
96 outqueue.put(self.help())
98 self._run(hooke, inqueue, outqueue, params)
99 except CommandExit, e:
100 if isinstance(e, Failure):
103 # other CommandExit subclasses fall through to the end
105 x = UncaughtException(e)
113 def _run(self, inqueue, outqueue, params):
114 """This is where the command-specific magic will happen.
118 def handle_arguments(self, hooke, inqueue, outqueue, params):
119 """Normalize and validate input parameters (:class:`Argument` values).
121 for argument in self.arguments:
122 names = [argument.name] + argument.aliases
123 settings = [(name,v) for name,v in params.items() if name in names]
124 num_provided = len(settings)
125 if num_provided == 0:
126 if argument.optional == True or argument.count == 0:
127 settings = [(argument.name, argument.default)]
129 raise Failure('Required argument %s not set.'
132 raise Failure('Multiple settings for %s:\n %s'
134 '\n '.join(['%s: %s' % (name,value)
135 for name,value in sorted(settings)])))
136 name,value = settings[0]
137 if name != argument.name:
139 params[argument.name] = value
140 if argument.callback != None:
142 value = argument.callback(hooke, self, argument, value)
143 params[argument.name] = value
144 argument.validate(value)
147 def help(self, name_fn=lambda name:name):
148 """Return a help message describing the `Command`.
150 `name_fn(internal_name) -> external_name` gives calling
151 :class:`hooke.ui.UserInterface`\s a means of changing the
152 display names if it wants (e.g. to remove spaces from command
155 name_part = 'Command: %s' % name_fn(self.name)
156 if len(self.aliases) > 0:
157 name_part += ' (%s)' % ', '.join(
158 [name_fn(n) for n in self.aliases])
160 if len(self.arguments) > 0:
161 argument_part = ['Arguments:', '']
162 for a in self.arguments:
163 argument_part.append(textwrap.fill(
166 subsequent_indent=" "))
167 argument_part = '\n'.join(argument_part)
168 parts.append(argument_part)
169 parts.append(self._help) # help part
170 return '\n\n'.join(parts)
172 class Argument (object):
173 """Structured user input for :class:`Command`\s.
175 TODO: ranges for `count`?
177 def __init__(self, name, aliases=None, type='string', metavar=None,
178 default=None, optional=True, count=1,
179 completion_callback=None, callback=None, help=''):
183 self.aliases = aliases
186 metavar = type.upper()
187 self.metavar = metavar
188 self.default = default
189 self.optional = optional
191 self.completion_callback = completion_callback
192 self.callback = callback
196 return '<%s %s>' % (self.__class__.__name__, self.name)
199 return self.__str__()
201 def help(self, name_fn=lambda name:name):
202 """Return a help message describing the `Argument`.
204 `name_fn(internal_name) -> external_name` gives calling
205 :class:`hooke.ui.UserInterface`\s a means of changing the
206 display names if it wants (e.g. to remove spaces from command
209 parts = ['%s ' % name_fn(self.name)]
210 if self.metavar != None:
211 parts.append('%s ' % self.metavar)
212 parts.extend(['(%s) ' % self.type, self._help])
213 return ''.join(parts)
215 def validate(self, value):
216 """If `value` is not appropriate, raise `ValueError`.
218 pass # TODO: validation
220 # TODO: type conversion
222 # TODO: type extensions?
226 class StoreValue (object):
227 def __init__(self, value):
229 def __call__(self, hooke, command, argument, fragment=None):
232 class NullQueue (queue.Queue):
233 """The :class:`queue.Queue` equivalent of `/dev/null`.
235 This is a bottomless pit. Items go in, but never come out.
237 def get(self, block=True, timeout=None):
238 """Raise queue.Empty.
240 There's really no need to override the base Queue.get, but I
241 want to know if someone tries to read from a NullQueue. With
242 the default implementation they would just block silently
247 def put(self, item, block=True, timeout=None):
248 """Dump an item into the void.
250 Block and timeout are meaningless, because there is always a
251 free slot available in a bottomless pit.
255 class PrintQueue (NullQueue):
256 """Debugging :class:`NullQueue` that prints items before dropping
259 def put(self, item, block=True, timeout=None):
260 """Print `item` and then dump it into the void.
262 print 'ITEM:\n%s' % item