blob: a9ebae098d49babcd3693ea6a1a570b75cc10e50 [file] [log] [blame]
[email protected]0633fb42013-08-16 20:06:141# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Manages subcommands in a script.
6
7Each subcommand should look like this:
8 @usage('[pet name]')
9 def CMDpet(parser, args):
10 '''Prints a pet.
11
12 Many people likes pet. This command prints a pet for your pleasure.
13 '''
14 parser.add_option('--color', help='color of your pet')
15 options, args = parser.parse_args(args)
16 if len(args) != 1:
17 parser.error('A pet name is required')
18 pet = args[0]
19 if options.color:
20 print('Nice %s %d' % (options.color, pet))
21 else:
22 print('Nice %s' % pet)
23 return 0
24
25Explanation:
26 - usage decorator alters the 'usage: %prog' line in the command's help.
27 - docstring is used to both short help line and long help line.
28 - parser can be augmented with arguments.
29 - return the exit code.
30 - Every function in the specified module with a name starting with 'CMD' will
31 be a subcommand.
32 - The module's docstring will be used in the default 'help' page.
33 - If a command has no docstring, it will not be listed in the 'help' page.
34 Useful to keep compatibility commands around or aliases.
35 - If a command is an alias to another one, it won't be documented. E.g.:
36 CMDoldname = CMDnewcmd
37 will result in oldname not being documented but supported and redirecting to
38 newcmd. Make it a real function that calls the old function if you want it
39 to be documented.
[email protected]9f7fd122015-04-02 19:56:5840 - CMDfoo_bar will be command 'foo-bar'.
[email protected]0633fb42013-08-16 20:06:1441"""
42
43import difflib
44import sys
[email protected]39c0b222013-08-17 16:57:0145import textwrap
[email protected]0633fb42013-08-16 20:06:1446
47
48def usage(more):
49 """Adds a 'usage_more' property to a CMD function."""
50 def hook(fn):
51 fn.usage_more = more
52 return fn
53 return hook
54
55
[email protected]39c0b222013-08-17 16:57:0156def epilog(text):
57 """Adds an 'epilog' property to a CMD function.
58
59 It will be shown in the epilog. Usually useful for examples.
60 """
61 def hook(fn):
62 fn.epilog = text
63 return fn
64 return hook
65
66
[email protected]0633fb42013-08-16 20:06:1467def CMDhelp(parser, args):
68 """Prints list of commands or help for a specific command."""
69 # This is the default help implementation. It can be disabled or overriden if
70 # wanted.
71 if not any(i in ('-h', '--help') for i in args):
72 args = args + ['--help']
73 _, args = parser.parse_args(args)
74 # Never gets there.
75 assert False
76
77
[email protected]39c0b222013-08-17 16:57:0178def _get_color_module():
79 """Returns the colorama module if available.
80
81 If so, assumes colors are supported and return the module handle.
82 """
83 return sys.modules.get('colorama') or sys.modules.get('third_party.colorama')
84
85
[email protected]9f7fd122015-04-02 19:56:5886def _function_to_name(name):
87 """Returns the name of a CMD function."""
88 return name[3:].replace('_', '-')
89
90
[email protected]0633fb42013-08-16 20:06:1491class CommandDispatcher(object):
92 def __init__(self, module):
93 """module is the name of the main python module where to look for commands.
94
95 The python builtin variable __name__ MUST be used for |module|. If the
96 script is executed in the form 'python script.py', __name__ == '__main__'
97 and sys.modules['script'] doesn't exist. On the other hand if it is unit
98 tested, __main__ will be the unit test's module so it has to reference to
99 itself with 'script'. __name__ always match the right value.
100 """
101 self.module = sys.modules[module]
102
103 def enumerate_commands(self):
104 """Returns a dict of command and their handling function.
105
106 The commands must be in the '__main__' modules. To import a command from a
107 submodule, use:
108 from mysubcommand import CMDfoo
109
110 Automatically adds 'help' if not already defined.
111
[email protected]9f7fd122015-04-02 19:56:58112 Normalizes '_' in the commands to '-'.
113
[email protected]0633fb42013-08-16 20:06:14114 A command can be effectively disabled by defining a global variable to None,
115 e.g.:
116 CMDhelp = None
117 """
118 cmds = dict(
[email protected]9f7fd122015-04-02 19:56:58119 (_function_to_name(name), getattr(self.module, name))
120 for name in dir(self.module) if name.startswith('CMD'))
[email protected]0633fb42013-08-16 20:06:14121 cmds.setdefault('help', CMDhelp)
122 return cmds
123
[email protected]9f7fd122015-04-02 19:56:58124 def find_nearest_command(self, name_asked):
125 """Retrieves the function to handle a command as supplied by the user.
[email protected]0633fb42013-08-16 20:06:14126
[email protected]9f7fd122015-04-02 19:56:58127 It automatically tries to guess the _intended command_ by handling typos
128 and/or incomplete names.
[email protected]0633fb42013-08-16 20:06:14129 """
130 commands = self.enumerate_commands()
[email protected]6dc64d32015-04-07 17:19:35131 name_to_dash = name_asked.replace('_', '-')
132 if name_to_dash in commands:
133 return commands[name_to_dash]
[email protected]0633fb42013-08-16 20:06:14134
135 # An exact match was not found. Try to be smart and look if there's
136 # something similar.
[email protected]9f7fd122015-04-02 19:56:58137 commands_with_prefix = [c for c in commands if c.startswith(name_asked)]
[email protected]0633fb42013-08-16 20:06:14138 if len(commands_with_prefix) == 1:
139 return commands[commands_with_prefix[0]]
140
141 # A #closeenough approximation of levenshtein distance.
142 def close_enough(a, b):
143 return difflib.SequenceMatcher(a=a, b=b).ratio()
144
145 hamming_commands = sorted(
[email protected]9f7fd122015-04-02 19:56:58146 ((close_enough(c, name_asked), c) for c in commands),
[email protected]0633fb42013-08-16 20:06:14147 reverse=True)
148 if (hamming_commands[0][0] - hamming_commands[1][0]) < 0.3:
149 # Too ambiguous.
150 return
151
152 if hamming_commands[0][0] < 0.8:
153 # Not similar enough. Don't be a fool and run a random command.
154 return
155
156 return commands[hamming_commands[0][1]]
157
[email protected]39c0b222013-08-17 16:57:01158 def _gen_commands_list(self):
159 """Generates the short list of supported commands."""
160 commands = self.enumerate_commands()
161 docs = sorted(
[email protected]9f7fd122015-04-02 19:56:58162 (cmd_name, self._create_command_summary(cmd_name, handler))
163 for cmd_name, handler in commands.iteritems())
[email protected]39c0b222013-08-17 16:57:01164 # Skip commands without a docstring.
165 docs = [i for i in docs if i[1]]
166 # Then calculate maximum length for alignment:
167 length = max(len(c) for c in commands)
168
169 # Look if color is supported.
170 colors = _get_color_module()
171 green = reset = ''
172 if colors:
173 green = colors.Fore.GREEN
174 reset = colors.Fore.RESET
175 return (
176 'Commands are:\n' +
177 ''.join(
[email protected]9f7fd122015-04-02 19:56:58178 ' %s%-*s%s %s\n' % (green, length, cmd_name, reset, doc)
179 for cmd_name, doc in docs))
[email protected]39c0b222013-08-17 16:57:01180
[email protected]0633fb42013-08-16 20:06:14181 def _add_command_usage(self, parser, command):
182 """Modifies an OptionParser object with the function's documentation."""
[email protected]9f7fd122015-04-02 19:56:58183 cmd_name = _function_to_name(command.__name__)
184 if cmd_name == 'help':
185 cmd_name = '<command>'
[email protected]0633fb42013-08-16 20:06:14186 # Use the module's docstring as the description for the 'help' command if
187 # available.
[email protected]39c0b222013-08-17 16:57:01188 parser.description = (self.module.__doc__ or '').rstrip()
189 if parser.description:
190 parser.description += '\n\n'
191 parser.description += self._gen_commands_list()
192 # Do not touch epilog.
[email protected]0633fb42013-08-16 20:06:14193 else:
[email protected]39c0b222013-08-17 16:57:01194 # Use the command's docstring if available. For commands, unlike module
195 # docstring, realign.
196 lines = (command.__doc__ or '').rstrip().splitlines()
197 if lines[:1]:
198 rest = textwrap.dedent('\n'.join(lines[1:]))
199 parser.description = '\n'.join((lines[0], rest))
200 else:
[email protected]29404b52014-09-08 22:58:00201 parser.description = lines[0] if lines else ''
[email protected]39c0b222013-08-17 16:57:01202 if parser.description:
203 parser.description += '\n'
204 parser.epilog = getattr(command, 'epilog', None)
205 if parser.epilog:
206 parser.epilog = '\n' + parser.epilog.strip() + '\n'
207
208 more = getattr(command, 'usage_more', '')
[email protected]9f7fd122015-04-02 19:56:58209 extra = '' if not more else ' ' + more
210 parser.set_usage('usage: %%prog %s [options]%s' % (cmd_name, extra))
[email protected]0633fb42013-08-16 20:06:14211
212 @staticmethod
[email protected]9f7fd122015-04-02 19:56:58213 def _create_command_summary(cmd_name, command):
214 """Creates a oneliner summary from the command's docstring."""
215 if cmd_name != _function_to_name(command.__name__):
216 # Skip aliases. For example using at module level:
217 # CMDfoo = CMDbar
[email protected]0633fb42013-08-16 20:06:14218 return ''
219 doc = command.__doc__ or ''
220 line = doc.split('\n', 1)[0].rstrip('.')
221 if not line:
222 return line
223 return (line[0].lower() + line[1:]).strip()
224
225 def execute(self, parser, args):
226 """Dispatches execution to the right command.
227
228 Fallbacks to 'help' if not disabled.
229 """
[email protected]39c0b222013-08-17 16:57:01230 # Unconditionally disable format_description() and format_epilog().
231 # Technically, a formatter should be used but it's not worth (yet) the
232 # trouble.
233 parser.format_description = lambda _: parser.description or ''
234 parser.format_epilog = lambda _: parser.epilog or ''
[email protected]0633fb42013-08-16 20:06:14235
236 if args:
237 if args[0] in ('-h', '--help') and len(args) > 1:
238 # Inverse the argument order so 'tool --help cmd' is rewritten to
239 # 'tool cmd --help'.
240 args = [args[1], args[0]] + args[2:]
241 command = self.find_nearest_command(args[0])
242 if command:
243 if command.__name__ == 'CMDhelp' and len(args) > 1:
244 # Inverse the arguments order so 'tool help cmd' is rewritten to
245 # 'tool cmd --help'. Do it here since we want 'tool hel cmd' to work
246 # too.
247 args = [args[1], '--help'] + args[2:]
248 command = self.find_nearest_command(args[0]) or command
249
250 # "fix" the usage and the description now that we know the subcommand.
251 self._add_command_usage(parser, command)
252 return command(parser, args[1:])
253
[email protected]39c0b222013-08-17 16:57:01254 cmdhelp = self.enumerate_commands().get('help')
255 if cmdhelp:
[email protected]0633fb42013-08-16 20:06:14256 # Not a known command. Default to help.
[email protected]39c0b222013-08-17 16:57:01257 self._add_command_usage(parser, cmdhelp)
258 return cmdhelp(parser, args)
[email protected]0633fb42013-08-16 20:06:14259
260 # Nothing can be done.
261 return 2