Dash separators consistent with hooke.ui.UserInterface._splash_text().
[hooke.git] / hooke / ui / commandline.py
1 """Defines :class:`CommandLine` for driving Hooke from the command
2 line.
3 """
4
5 import cmd
6 import optparse
7 import readline # including readline makes cmd.Cmd.cmdloop() smarter
8 import shlex
9
10 from ..command import CommandExit, Exit, BooleanRequest, BooleanResponse, \
11     Command, Argument, StoreValue
12 from ..ui import UserInterface, CommandMessage
13
14
15 # Define a few helper classes.
16
17 class Default (object):
18     """Marker for options not given on the command line.
19     """
20     pass
21
22 class CommandLineParser (optparse.OptionParser):
23     """Implement a command line syntax for a
24     :class:`hooke.command.Command`.
25     """
26     def __init__(self, command, name_fn):
27         optparse.OptionParser.__init__(self, prog=name_fn(command.name))
28         self.command = command
29         self.command_opts = []
30         self.command_args = []
31         for a in command.arguments:
32             if a.name == 'help':
33                 continue # 'help' is a default OptionParser option
34             if a.optional == True:
35                 name = name_fn(a.name)
36                 self.add_option(
37                     '--%s' % name, dest=name, default=Default)
38                 self.command_opts.append(a)
39             else:
40                 self.command_args.append(a)
41         infinite_counters = [a for a in self.command_args if a.count == -1]
42         assert len(infinite_counters) <= 1, \
43             'Multiple infinite counts for %s: %s\nNeed a better CommandLineParser implementation.' \
44             % (command.name, ', '.join([a.name for a in infinite_counters]))
45         if len(infinite_counters) == 1: # move the big counter to the end.
46             infinite_counter = infinite_counters[0]
47             self.command_args.remove(infinite_counter)
48             self.command_args.append(infinite_counter)
49
50     def exit(self, status=0, msg=None):
51         """Override :meth:`optparse.OptionParser.exit` which calls
52         :func:`sys.exit`.
53         """
54         if msg:
55             raise optparse.OptParseError(msg)
56         raise optparse.OptParseError('OptParse EXIT')
57
58 class CommandMethod (object):
59     """Base class for method replacer.
60
61     The .__call__ methods of `CommandMethod` subclasses functions will
62     provide the `do_*`, `help_*`, and `complete_*` methods of
63     :class:`HookeCmd`.
64     """
65     def __init__(self, cmd, command, name_fn):
66         self.cmd = cmd
67         self.command = command
68         self.name_fn = name_fn
69
70     def __call__(self, *args, **kwargs):
71         raise NotImplementedError
72
73 class DoCommand (CommandMethod):
74     def __init__(self, *args, **kwargs):
75         super(DoCommand, self).__init__(*args, **kwargs)
76         self.parser = CommandLineParser(self.command, self.name_fn)
77
78     def __call__(self, args):
79         try:
80             args = self._parse_args(args)
81         except optparse.OptParseError, e:
82             self.cmd.stdout.write(str(e).lstrip()+'\n')
83             self.cmd.stdout.write('Failure\n')
84             return
85         self.cmd.inqueue.put(CommandMessage(self.command, args))
86         while True:
87             msg = self.cmd.outqueue.get()
88             if isinstance(msg, Exit):
89                 return True
90             elif isinstance(msg, CommandExit):
91                 self.cmd.stdout.write(msg.__class__.__name__+'\n')
92                 self.cmd.stdout.write(str(msg).rstrip()+'\n')
93                 break
94             elif isinstance(msg, BooleanRequest):
95                 self._boolean_request(msg)
96                 continue
97             self.cmd.stdout.write(str(msg).rstrip()+'\n')
98
99     def _parse_args(self, args):
100         argv = shlex.split(args, comments=True, posix=True)
101         options,args = self.parser.parse_args(argv)
102         self._check_argument_length_bounds(args)
103         params = {}
104         for argument in self.parser.command_opts:
105             value = getattr(options, self.name_fn(argument.name))
106             if value != Default:
107                 params[argument.name] = value
108         arg_index = 0
109         for argument in self.parser.command_args:
110             if argument.count == 1:
111                 params[argument.name] = args[arg_index]
112             elif argument.count > 1:
113                 params[argument.name] = \
114                     args[arg_index:arg_index+argument.count]
115             else: # argument.count == -1:
116                 params[argument.name] = args[arg_index:]
117             arg_index += argument.count
118         return params
119
120     def _check_argument_length_bounds(self, arguments):
121         """Check that there are an appropriate number of arguments in
122         `args`.
123
124         If not, raise optparse.OptParseError().
125         """
126         min_args = 0
127         max_args = -1
128         for argument in self.parser.command_args:
129             if argument.optional == False and argument.count > 0:
130                 min_args += argument.count
131             if max_args >= 0: # otherwise already infinite
132                 if argument.count == -1:
133                     max_args = -1
134                 else:
135                     max_args += argument.count
136         if len(arguments) < min_args \
137                 or (max_args >= 0 and len(arguments) > max_args):
138             if min_args == max_args:
139                 target_string = str(min_args)
140             elif max_args == -1:
141                 target_string = 'more than %d' % min_args
142             else:
143                 target_string = '%d to %d' % (min_args, max_args)
144             raise optparse.OptParseError(
145                 '%d arguments given, but %s takes %s'
146                 % (len(arguments), self.name_fn(self.command.name),
147                    target_string))
148
149     def _boolean_request(self, msg):
150         if msg.default == True:
151             yn = ' [Y/n] '
152         else:
153             yn = ' [y/N] '
154         self.cmd.stdout.write(msg.msg+yn)
155         response = self.cmd.stdin.readline().strip().lower()
156         if response.startswith('y'):
157             self.cmd.inqueue.put(BooleanResponse(True))
158         elif response.startswith('n'):
159             self.cmd.inqueue.put(BooleanResponse(False))
160         else:
161             self.cmd.inqueue.put(BooleanResponse(msg.default))
162
163 class HelpCommand (CommandMethod):
164     def __init__(self, *args, **kwargs):
165         super(HelpCommand, self).__init__(*args, **kwargs)
166         self.parser = CommandLineParser(self.command, self.name_fn)
167
168     def __call__(self):
169         blocks = [self.command.help(name_fn=self.name_fn),
170                   '----',
171                   'Usage: ' + self._usage_string(),
172                   '']
173         self.cmd.stdout.write('\n'.join(blocks))
174
175     def _message(self):
176         return self.command.help(name_fn=self.name_fn)
177
178     def _usage_string(self):
179         if len(self.parser.command_opts) == 0:
180             options_string = ''
181         else:
182             options_string = '[options]'
183         arg_string = ' '.join(
184             [self.name_fn(arg.name) for arg in self.parser.command_args])
185         return ' '.join([x for x in [self.parser.prog,
186                                      options_string,
187                                      arg_string]
188                          if x != ''])
189
190 class CompleteCommand (CommandMethod):
191     def __call__(self, text, line, begidx, endidx):
192         pass
193
194
195 # Define some additional commands
196
197 class LocalHelpCommand (Command):
198     """Called with an argument, prints that command's documentation.
199
200     With no argument, lists all available help topics as well as any
201     undocumented commands.
202     """
203     def __init__(self):
204         super(LocalHelpCommand, self).__init__(name='help', help=self.__doc__)
205         # We set .arguments now (vs. using th arguments option to __init__),
206         # to overwrite the default help argument.  We don't override
207         # :meth:`cmd.Cmd.do_help`, so `help --help` is not a valid command.
208         self.arguments = [
209             Argument(name='command', type='string', optional=True,
210                      help='The name of the command you want help with.')
211             ]
212
213     def _run(self, hooke, inqueue, outqueue, params):
214         raise NotImplementedError # cmd.Cmd already implements .do_help()
215
216 class LocalExitCommand (Command):
217     """Exit Hooke cleanly.
218     """
219     def __init__(self):
220         super(LocalExitCommand, self).__init__(
221             name='exit', aliases=['quit', 'EOF'], help=self.__doc__,
222             arguments = [
223                 Argument(name='force', type='bool', default=False,
224                          callback=StoreValue(True), help="""
225 Exit without prompting the user.  Use if you save often or don't make
226 typing mistakes ;).
227 """.strip()),
228                 ])
229
230     def _run(self, hooke, inqueue, outqueue, params):
231         """The guts of the `do_exit/_quit/_EOF` commands.
232
233         A `True` return stops :meth:`.cmdloop` execution.
234         """
235         _exit = True
236         if params['force'] == False:
237             # TODO: get results of hooke.playlists.current().is_saved()
238             is_saved = True
239             msg = 'Exit?'
240             default = True
241             if is_saved == False:
242                 msg = 'You did not save your playlist.  ' + msg
243                 default = False
244             outqueue.put(BooleanRequest(msg, default))
245             result = inqueue.get()
246             assert isinstance(result, BooleanResponse)
247             _exit = result.value
248         if _exit == True:
249             raise Exit()
250
251
252 # Now onto the main attraction.
253
254 class HookeCmd (cmd.Cmd):
255     def __init__(self, commands, inqueue, outqueue):
256         cmd.Cmd.__init__(self)
257         self.commands = commands
258         self.local_commands = [LocalExitCommand(), LocalHelpCommand()]
259         self.prompt = 'hooke> '
260         self._add_command_methods()
261         self.inqueue = inqueue
262         self.outqueue = outqueue
263
264     def _name_fn(self, name):
265         return name.replace(' ', '_')
266
267     def _add_command_methods(self):
268         for command in self.commands + self.local_commands:
269             for name in [command.name] + command.aliases:
270                 name = self._name_fn(name)
271                 setattr(self.__class__, 'help_%s' % name,
272                         HelpCommand(self, command, self._name_fn))
273                 if name != 'help':
274                     setattr(self.__class__, 'do_%s' % name,
275                             DoCommand(self, command, self._name_fn))
276                     setattr(self.__class__, 'complete_%s' % name,
277                             CompleteCommand(self, command, self._name_fn))
278
279
280 class CommandLine (UserInterface):
281     """Command line interface.  Simple and powerful.
282     """
283     def __init__(self):
284         super(CommandLine, self).__init__(name='command line')
285
286     def run(self, commands, ui_to_command_queue, command_to_ui_queue):
287         cmd = HookeCmd(commands,
288                        inqueue=ui_to_command_queue,
289                        outqueue=command_to_ui_queue)
290         cmd.cmdloop(self._splash_text())