blob: 0201c90aa35d61a17252fd4eeb1e227bd76375d3 [file] [log] [blame]
maruel@chromium.org0633fb42013-08-16 20:06:14 +00001# 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.
maruel@chromium.org9f7fd122015-04-02 19:56:58 +000040 - CMDfoo_bar will be command 'foo-bar'.
maruel@chromium.org0633fb42013-08-16 20:06:14 +000041"""
42
43import difflib
44import sys
maruel@chromium.org39c0b222013-08-17 16:57:01 +000045import textwrap
maruel@chromium.org0633fb42013-08-16 20:06:14 +000046
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
maruel@chromium.org39c0b222013-08-17 16:57:01 +000056def 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
maruel@chromium.org0633fb42013-08-16 20:06:14 +000067def 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
maruel@chromium.org39c0b222013-08-17 16:57:01 +000078def _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
maruel@chromium.org9f7fd122015-04-02 19:56:58 +000086def _function_to_name(name):
87 """Returns the name of a CMD function."""
88 return name[3:].replace('_', '-')
89
90
maruel@chromium.org0633fb42013-08-16 20:06:14 +000091class 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
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000112 Normalizes '_' in the commands to '-'.
113
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000114 A command can be effectively disabled by defining a global variable to None,
115 e.g.:
116 CMDhelp = None
117 """
118 cmds = dict(
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000119 (_function_to_name(name), getattr(self.module, name))
120 for name in dir(self.module) if name.startswith('CMD'))
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000121 cmds.setdefault('help', CMDhelp)
122 return cmds
123
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000124 def find_nearest_command(self, name_asked):
125 """Retrieves the function to handle a command as supplied by the user.
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000126
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000127 It automatically tries to guess the _intended command_ by handling typos
128 and/or incomplete names.
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000129 """
130 commands = self.enumerate_commands()
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000131 if name_asked in commands:
132 return commands[name_asked]
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000133
134 # An exact match was not found. Try to be smart and look if there's
135 # something similar.
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000136 commands_with_prefix = [c for c in commands if c.startswith(name_asked)]
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000137 if len(commands_with_prefix) == 1:
138 return commands[commands_with_prefix[0]]
139
140 # A #closeenough approximation of levenshtein distance.
141 def close_enough(a, b):
142 return difflib.SequenceMatcher(a=a, b=b).ratio()
143
144 hamming_commands = sorted(
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000145 ((close_enough(c, name_asked), c) for c in commands),
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000146 reverse=True)
147 if (hamming_commands[0][0] - hamming_commands[1][0]) < 0.3:
148 # Too ambiguous.
149 return
150
151 if hamming_commands[0][0] < 0.8:
152 # Not similar enough. Don't be a fool and run a random command.
153 return
154
155 return commands[hamming_commands[0][1]]
156
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000157 def _gen_commands_list(self):
158 """Generates the short list of supported commands."""
159 commands = self.enumerate_commands()
160 docs = sorted(
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000161 (cmd_name, self._create_command_summary(cmd_name, handler))
162 for cmd_name, handler in commands.iteritems())
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000163 # Skip commands without a docstring.
164 docs = [i for i in docs if i[1]]
165 # Then calculate maximum length for alignment:
166 length = max(len(c) for c in commands)
167
168 # Look if color is supported.
169 colors = _get_color_module()
170 green = reset = ''
171 if colors:
172 green = colors.Fore.GREEN
173 reset = colors.Fore.RESET
174 return (
175 'Commands are:\n' +
176 ''.join(
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000177 ' %s%-*s%s %s\n' % (green, length, cmd_name, reset, doc)
178 for cmd_name, doc in docs))
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000179
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000180 def _add_command_usage(self, parser, command):
181 """Modifies an OptionParser object with the function's documentation."""
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000182 cmd_name = _function_to_name(command.__name__)
183 if cmd_name == 'help':
184 cmd_name = '<command>'
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000185 # Use the module's docstring as the description for the 'help' command if
186 # available.
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000187 parser.description = (self.module.__doc__ or '').rstrip()
188 if parser.description:
189 parser.description += '\n\n'
190 parser.description += self._gen_commands_list()
191 # Do not touch epilog.
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000192 else:
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000193 # Use the command's docstring if available. For commands, unlike module
194 # docstring, realign.
195 lines = (command.__doc__ or '').rstrip().splitlines()
196 if lines[:1]:
197 rest = textwrap.dedent('\n'.join(lines[1:]))
198 parser.description = '\n'.join((lines[0], rest))
199 else:
maruel@chromium.org29404b52014-09-08 22:58:00 +0000200 parser.description = lines[0] if lines else ''
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000201 if parser.description:
202 parser.description += '\n'
203 parser.epilog = getattr(command, 'epilog', None)
204 if parser.epilog:
205 parser.epilog = '\n' + parser.epilog.strip() + '\n'
206
207 more = getattr(command, 'usage_more', '')
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000208 extra = '' if not more else ' ' + more
209 parser.set_usage('usage: %%prog %s [options]%s' % (cmd_name, extra))
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000210
211 @staticmethod
maruel@chromium.org9f7fd122015-04-02 19:56:58 +0000212 def _create_command_summary(cmd_name, command):
213 """Creates a oneliner summary from the command's docstring."""
214 if cmd_name != _function_to_name(command.__name__):
215 # Skip aliases. For example using at module level:
216 # CMDfoo = CMDbar
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000217 return ''
218 doc = command.__doc__ or ''
219 line = doc.split('\n', 1)[0].rstrip('.')
220 if not line:
221 return line
222 return (line[0].lower() + line[1:]).strip()
223
224 def execute(self, parser, args):
225 """Dispatches execution to the right command.
226
227 Fallbacks to 'help' if not disabled.
228 """
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000229 # Unconditionally disable format_description() and format_epilog().
230 # Technically, a formatter should be used but it's not worth (yet) the
231 # trouble.
232 parser.format_description = lambda _: parser.description or ''
233 parser.format_epilog = lambda _: parser.epilog or ''
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000234
235 if args:
236 if args[0] in ('-h', '--help') and len(args) > 1:
237 # Inverse the argument order so 'tool --help cmd' is rewritten to
238 # 'tool cmd --help'.
239 args = [args[1], args[0]] + args[2:]
240 command = self.find_nearest_command(args[0])
241 if command:
242 if command.__name__ == 'CMDhelp' and len(args) > 1:
243 # Inverse the arguments order so 'tool help cmd' is rewritten to
244 # 'tool cmd --help'. Do it here since we want 'tool hel cmd' to work
245 # too.
246 args = [args[1], '--help'] + args[2:]
247 command = self.find_nearest_command(args[0]) or command
248
249 # "fix" the usage and the description now that we know the subcommand.
250 self._add_command_usage(parser, command)
251 return command(parser, args[1:])
252
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000253 cmdhelp = self.enumerate_commands().get('help')
254 if cmdhelp:
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000255 # Not a known command. Default to help.
maruel@chromium.org39c0b222013-08-17 16:57:01 +0000256 self._add_command_usage(parser, cmdhelp)
257 return cmdhelp(parser, args)
maruel@chromium.org0633fb42013-08-16 20:06:14 +0000258
259 # Nothing can be done.
260 return 2