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 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.
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.
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 """Defines :class:`CommandLine` for driving Hooke from the command
28 import readline # including readline makes cmd.Cmd.cmdloop() smarter
29 except ImportError, e:
31 logging.warn('could not import readline, bash-like line editing disabled.')
34 from ..command import CommandExit, Exit, Command, Argument, StoreValue
35 from ..engine import CommandMessage
36 from ..interaction import Request, ReloadUserInterfaceConfig
37 from ..ui import UserInterface
38 from ..util.convert import from_string
39 from ..util.encoding import get_input_encoding, get_output_encoding
42 # Define a few helper classes.
44 class Default (object):
45 """Marker for options not given on the command line.
49 class CommandLineParser (optparse.OptionParser):
50 """Implement a command line syntax for a
51 :class:`hooke.command.Command`.
53 def __init__(self, command, name_fn):
54 optparse.OptionParser.__init__(self, prog=name_fn(command.name))
55 self.command = command
56 self.command_opts = []
57 self.command_args = []
58 for a in command.arguments:
60 continue # 'help' is a default OptionParser option
61 if a.optional == True:
62 name = name_fn(a.name)
67 '--disable-%s' % name, dest=name, default=Default,
69 self.command_opts.append(a)
71 elif a.default == False:
73 '--enable-%s' % name, dest=name, default=Default,
75 self.command_opts.append(a)
79 elif type not in ['string', 'int', 'long', 'choice', 'float',
83 '--%s' % name, dest=name, type=type, default=Default)
84 self.command_opts.append(a)
86 self.command_args.append(a)
87 infinite_counters = [a for a in self.command_args if a.count == -1]
88 assert len(infinite_counters) <= 1, \
89 'Multiple infinite counts for %s: %s\nNeed a better CommandLineParser implementation.' \
90 % (command.name, ', '.join([a.name for a in infinite_counters]))
91 if len(infinite_counters) == 1: # move the big counter to the end.
92 infinite_counter = infinite_counters[0]
93 self.command_args.remove(infinite_counter)
94 self.command_args.append(infinite_counter)
96 def exit(self, status=0, msg=None):
97 """Override :meth:`optparse.OptionParser.exit` which calls
101 raise optparse.OptParseError(msg)
102 raise optparse.OptParseError('OptParse EXIT')
104 class CommandMethod (object):
105 """Base class for method replacer.
107 The .__call__ methods of `CommandMethod` subclasses functions will
108 provide the `do_*`, `help_*`, and `complete_*` methods of
111 def __init__(self, cmd, command, name_fn):
113 self.command = command
114 self.name_fn = name_fn
116 def __call__(self, *args, **kwargs):
117 raise NotImplementedError
119 class DoCommand (CommandMethod):
120 def __init__(self, *args, **kwargs):
121 super(DoCommand, self).__init__(*args, **kwargs)
122 self.parser = CommandLineParser(self.command, self.name_fn)
124 def __call__(self, args):
126 args = self._parse_args(args)
127 except optparse.OptParseError, e:
128 self.cmd.stdout.write(str(e).lstrip()+'\n')
129 self.cmd.stdout.write('Failure\n')
131 cm = CommandMessage(self.command.name, args)
132 self.cmd.ui._submit_command(cm, self.cmd.inqueue)
134 msg = self.cmd.outqueue.get()
135 if isinstance(msg, Exit):
137 elif isinstance(msg, CommandExit):
138 self.cmd.stdout.write(msg.__class__.__name__+'\n')
139 self.cmd.stdout.write(str(msg).rstrip()+'\n')
141 elif isinstance(msg, ReloadUserInterfaceConfig):
142 self.cmd.ui.reload_config(msg.config)
144 elif isinstance(msg, Request):
145 self._handle_request(msg)
147 self.cmd.stdout.write(str(msg).rstrip()+'\n')
149 def _parse_args(self, args):
150 options,args = self.parser.parse_args(args)
151 self._check_argument_length_bounds(args)
153 for argument in self.parser.command_opts:
154 value = getattr(options, self.name_fn(argument.name))
156 params[argument.name] = value
158 for argument in self.parser.command_args:
159 if argument.count == 1:
160 params[argument.name] = from_string(args[arg_index],
162 elif argument.count > 1:
163 params[argument.name] = [
164 from_string(a, argument.type)
165 for a in args[arg_index:arg_index+argument.count]]
166 else: # argument.count == -1:
167 params[argument.name] = [
168 from_string(a, argument.type) for a in args[arg_index:]]
169 arg_index += argument.count
172 def _check_argument_length_bounds(self, arguments):
173 """Check that there are an appropriate number of arguments in
176 If not, raise optparse.OptParseError().
180 for argument in self.parser.command_args:
181 if argument.optional == False and argument.count > 0:
182 min_args += argument.count
183 if max_args >= 0: # otherwise already infinite
184 if argument.count == -1:
187 max_args += argument.count
188 if len(arguments) < min_args \
189 or (max_args >= 0 and len(arguments) > max_args):
190 if min_args == max_args:
191 target_string = str(min_args)
193 target_string = 'more than %d' % min_args
195 target_string = '%d to %d' % (min_args, max_args)
196 raise optparse.OptParseError(
197 '%d arguments given, but %s takes %s'
198 % (len(arguments), self.name_fn(self.command.name),
201 def _handle_request(self, msg):
202 """Repeatedly try to get a response to `msg`.
204 prompt = getattr(self, '_%s_request_prompt' % msg.type, None)
206 raise NotImplementedError('_%s_request_prompt' % msg.type)
207 prompt_string = prompt(msg)
208 parser = getattr(self, '_%s_request_parser' % msg.type, None)
210 raise NotImplementedError('_%s_request_parser' % msg.type)
214 self.cmd.stdout.write(''.join([
215 error.__class__.__name__, ': ', str(error), '\n']))
216 self.cmd.stdout.write(prompt_string)
217 value = parser(msg, self.cmd.stdin.readline())
219 response = msg.response(value)
221 except ValueError, error:
223 self.cmd.inqueue.put(response)
225 def _boolean_request_prompt(self, msg):
226 if msg.default == True:
232 def _boolean_request_parser(self, msg, response):
233 value = response.strip().lower()
234 if value.startswith('y'):
236 elif value.startswith('n'):
238 elif len(value) == 0:
242 def _string_request_prompt(self, msg):
243 if msg.default == None:
246 d = ' [%s] ' % msg.default
249 def _string_request_parser(self, msg, response):
250 response = response.strip()
253 return response.strip()
255 def _float_request_prompt(self, msg):
256 return self._string_request_prompt(msg)
258 def _float_request_parser(self, msg, resposne):
259 if response.strip() == '':
261 return float(response)
263 def _selection_request_prompt(self, msg):
265 for i,option in enumerate(msg.options):
266 options.append(' %d) %s' % (i,option))
267 options = ''.join(options)
268 if msg.default == None:
271 prompt = '? [%d] ' % msg.default
272 return '\n'.join([msg.msg,options,prompt])
274 def _selection_request_parser(self, msg, response):
275 if response.strip() == '':
279 def _point_request_prompt(self, msg):
280 block = msg.curve.data[msg.block]
281 block_info = ('(curve: %s, block: %s, %d points)'
286 if msg.default == None:
289 prompt = '? [%d] ' % msg.default
290 return ' '.join([msg.msg,block_info,prompt])
292 def _point_request_parser(self, msg, response):
293 if response.strip() == '':
298 class HelpCommand (CommandMethod):
299 """Supersedes :class:`hooke.plugin.engine.HelpCommand`.
301 def __init__(self, *args, **kwargs):
302 super(HelpCommand, self).__init__(*args, **kwargs)
303 self.parser = CommandLineParser(self.command, self.name_fn)
306 blocks = [self.command.help(name_fn=self.name_fn),
308 'Usage: ' + self._usage_string(),
310 self.cmd.stdout.write('\n'.join(blocks))
313 return self.command.help(name_fn=self.name_fn)
315 def _usage_string(self):
316 if len(self.parser.command_opts) == 0:
319 options_string = '[options]'
320 arg_string = ' '.join(
321 [self.name_fn(arg.name) for arg in self.parser.command_args])
322 return ' '.join([x for x in [self.parser.prog,
327 class CompleteCommand (CommandMethod):
328 def __call__(self, text, line, begidx, endidx):
333 # Now onto the main attraction.
335 class HookeCmd (cmd.Cmd):
336 def __init__(self, ui, commands, inqueue, outqueue):
337 cmd.Cmd.__init__(self)
339 self.commands = commands
340 self.prompt = 'hooke> '
341 self._add_command_methods()
342 self.inqueue = inqueue
343 self.outqueue = outqueue
345 def _name_fn(self, name):
346 return name.replace(' ', '_')
348 def _add_command_methods(self):
349 for command in self.commands:
350 if command.name == 'exit':
351 command.aliases.extend(['quit', 'EOF'])
352 for name in [command.name] + command.aliases:
353 name = self._name_fn(name)
354 setattr(self.__class__, 'help_%s' % name,
355 HelpCommand(self, command, self._name_fn))
357 setattr(self.__class__, 'do_%s' % name,
358 DoCommand(self, command, self._name_fn))
359 setattr(self.__class__, 'complete_%s' % name,
360 CompleteCommand(self, command, self._name_fn))
362 def parseline(self, line):
363 """Override Cmd.parseline to use shlex.split.
367 This allows us to handle comments cleanly. With the default
368 Cmd implementation, a pure comment line will call the .default
371 Since we use shlex to strip comments, we return a list of
372 split arguments rather than the raw argument string.
375 argv = shlex.split(line, comments=True, posix=True)
377 return None, None, '' # return an empty line
384 return cmd, args, line
386 def do_help(self, arg):
387 """Wrap Cmd.do_help to handle our .parseline argument list.
390 return cmd.Cmd.do_help(self, '')
391 return cmd.Cmd.do_help(self, arg[0])
394 """Override Cmd.emptyline to not do anything.
396 Repeating the last non-empty command seems unwise. Explicit
397 is better than implicit.
402 class CommandLine (UserInterface):
403 """Command line interface. Simple and powerful.
406 super(CommandLine, self).__init__(name='command line')
408 def _cmd(self, commands, ui_to_command_queue, command_to_ui_queue):
409 cmd = HookeCmd(self, commands,
410 inqueue=ui_to_command_queue,
411 outqueue=command_to_ui_queue)
412 #cmd.stdin = codecs.getreader(get_input_encoding())(cmd.stdin)
413 cmd.stdout = codecs.getwriter(get_output_encoding())(cmd.stdout)
416 def run(self, commands, ui_to_command_queue, command_to_ui_queue):
417 cmd = self._cmd(commands, ui_to_command_queue, command_to_ui_queue)
418 cmd.cmdloop(self._splash_text(extra_info={
419 'get-details':'run `license`',
422 def run_lines(self, commands, ui_to_command_queue, command_to_ui_queue,
424 cmd = self._cmd(commands, ui_to_command_queue, command_to_ui_queue)