1 """The `command` module provides :class:`Command`\s and
2 :class:`Argument`\s for defining commands.
11 class CommandExit (Exception):
14 class Success (CommandExit):
17 class Failure (CommandExit):
20 class UncaughtException (Failure):
21 def __init__(self, exception):
22 self.exception = exception
23 self.exc_string = traceback.format_exc()
25 super(UncaughtException, self).__init__(self.exc_string)
27 class Command (object):
28 """One-line command description here.
30 >>> c = Command(name='test', help='An example Command.')
31 >>> status = c.run(NullQueue(), PrintQueue(), help=True) # doctest: +REPORT_UDIFF
37 help BOOL (bool) Print a help message.
43 def __init__(self, name, aliases=None, arguments=[], help=''):
47 self.aliases = aliases
49 Argument(name='help', type='bool', default=False, count=1,
50 callback=StoreValue(True), help='Print a help message.'),
54 def run(self, hooke, inqueue=None, outqueue=None, **kwargs):
55 """`Normalize inputs and handle <Argument help> before punting
61 outqueue = NullQueue()
63 params = self.handle_arguments(hooke, inqueue, outqueue, kwargs)
64 if params['help'] == True:
65 outqueue.put(self.help())
67 self._run(hooke, inqueue, outqueue, params)
68 except CommandExit, e:
69 if isinstance(e, Failure):
72 # other CommandExit subclasses fall through to the end
74 x = UncaughtException(e)
82 def _run(self, inqueue, outqueue, params):
83 """This is where the command-specific magic will happen.
87 def handle_arguments(self, hooke, inqueue, outqueue, params):
88 """Normalize and validate input parameters (:class:`Argument` values).
90 for argument in self.arguments:
91 names = [argument.name] + argument.aliases
92 settings = [(name,v) for name,v in params.items() if name in names]
93 num_provided = len(settings)
95 if argument.optional == True or argument.count == 0:
96 settings = [(argument.name, argument.default)]
98 raise Failure('Required argument %s not set.'
101 raise Failure('Multiple settings for %s:\n %s'
103 '\n '.join(['%s: %s' % (name,value)
104 for name,value in sorted(settings)])))
105 name,value = settings[0]
106 if name != argument.name:
108 params[argument.name] = value
109 if argument.callback != None:
111 value = argument.callback(hooke, self, argument, value)
112 params[argument.name] = value
113 argument.validate(value)
116 def help(self, name_fn=lambda name:name):
117 """Return a help message describing the `Command`.
119 `name_fn(internal_name) -> external_name` gives calling
120 :class:`hooke.ui.UserInterface`\s a means of changing the
121 display names if it wants (e.g. to remove spaces from command
124 name_part = 'Command: %s' % name_fn(self.name)
125 if len(self.aliases) > 0:
126 name_part += ' (%s)' % ', '.join([name_fn(n) for n in aliases])
128 if len(self.arguments) > 0:
129 argument_part = ['Arguments:', '']
130 for a in self.arguments:
131 argument_part.append(textwrap.fill(
134 subsequent_indent=" "))
135 argument_part = '\n'.join(argument_part)
136 parts.append(argument_part)
137 parts.append(self._help) # help part
138 return '\n\n'.join(parts)
140 class Argument (object):
141 """Structured user input for :class:`Command`\s.
143 TODO: ranges for `count`?
145 def __init__(self, name, aliases=None, type='string', metavar=None,
146 default=None, optional=True, count=1,
147 completion_callback=None, callback=None, help=''):
151 self.aliases = aliases
154 metavar = type.upper()
155 self.metavar = metavar
156 self.default = default
157 self.optional = optional
159 self.completion_callback = completion_callback
160 self.callback = callback
164 return '<%s %s>' % (self.__class__.__name__, self.name)
167 return self.__str__()
169 def help(self, name_fn=lambda name:name):
170 """Return a help message describing the `Argument`.
172 `name_fn(internal_name) -> external_name` gives calling
173 :class:`hooke.ui.UserInterface`\s a means of changing the
174 display names if it wants (e.g. to remove spaces from command
177 parts = ['%s ' % name_fn(self.name)]
178 if self.metavar != None:
179 parts.append('%s ' % self.metavar)
180 parts.extend(['(%s) ' % self.type, self._help])
181 return ''.join(parts)
183 def validate(self, value):
184 """If `value` is not appropriate, raise `ValueError`.
186 pass # TODO: validation
188 # TODO: type conversion
190 # TODO: type extensions?
194 class StoreValue (object):
195 def __init__(self, value):
197 def __call__(self, hooke, command, argument, fragment=None):
200 class NullQueue (queue.Queue):
201 """The :class:`queue.Queue` equivalent of `/dev/null`.
203 This is a bottomless pit. Items go in, but never come out.
205 def get(self, block=True, timeout=None):
206 """Raise queue.Empty.
208 There's really no need to override the base Queue.get, but I
209 want to know if someone tries to read from a NullQueue. With
210 the default implementation they would just block silently
215 def put(self, item, block=True, timeout=None):
216 """Dump an item into the void.
218 Block and timeout are meaningless, because there is always a
219 free slot available in a bottomless pit.
223 class PrintQueue (NullQueue):
224 """Debugging :class:`NullQueue` that prints items before dropping
227 def put(self, item, block=True, timeout=None):
228 """Print `item` and then dump it into the void.
230 print 'ITEM:\n%s' % item