Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright (c) 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 | |
| 7 Each 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 | |
| 25 Explanation: | |
| 26 - usage decorator alter the usage: 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 main module with a name starting with 'CMD' will be a | |
| 31 subcommand. | |
| 32 - The module's docstring will be used in the default help page. | |
| 33 """ | |
| 34 | |
| 35 import difflib | |
| 36 import sys | |
| 37 | |
| 38 | |
| 39 def usage(more): | |
| 40 """Adds a 'usage_more' property to a CMD function.""" | |
| 41 def hook(fn): | |
| 42 fn.usage_more = more | |
| 43 return fn | |
| 44 return hook | |
| 45 | |
| 46 | |
| 47 def CMDhelp(parser, args): | |
| 48 """Prints list of commands or help for a specific command.""" | |
| 49 # This is the default help implementation. It can be disabled or overriden if | |
| 50 # wanted. | |
| 51 if not any(i in ('-h', '--help') for i in args): | |
| 52 args = args + ['--help'] | |
| 53 _, args = parser.parse_args(args) | |
| 54 # Never gets there. | |
| 55 assert False | |
| 56 | |
| 57 | |
| 58 class CommandDispatcher(object): | |
| 59 def __init__(self, module='__main__'): | |
| 60 """module is the main python module where to search for commands.""" | |
| 61 self.module_name = module | |
|
iannucci
2013/08/15 21:18:52
Why not
def __init__(self, module=None):
self.m
| |
| 62 | |
| 63 @property | |
| 64 def module(self): | |
| 65 return sys.modules.get(self.module_name) or sys.modules.get('__main__') | |
|
M-A Ruel
2013/08/15 21:08:27
This is tricky because:
- 'git_cl' is not present
| |
| 66 | |
| 67 def get_commands(self): | |
| 68 """Returns a dict of command and their handling function. | |
| 69 | |
| 70 The commands must be in the '__main__' modules. To import a command from a | |
| 71 submodule, use: | |
| 72 from mysubcommand import CMDfoo | |
| 73 | |
| 74 Automatically adds 'help' if not already defined. | |
| 75 | |
| 76 A command can be effectively disabled by defining a global variable to None, | |
| 77 e.g.: | |
| 78 CMDhelp = None | |
| 79 """ | |
| 80 cmds = dict( | |
| 81 (fn[3:], getattr(self.module, fn)) | |
| 82 for fn in dir(self.module) if fn.startswith('CMD')) | |
| 83 cmds.setdefault('help', CMDhelp) | |
| 84 return cmds | |
| 85 | |
| 86 def get_command(self, name): | |
| 87 """Retrieves the function to handle a command. | |
| 88 | |
| 89 It automatically tries to guess the intended command by handling typos or | |
| 90 incomplete names. | |
| 91 """ | |
| 92 commands = self.get_commands() | |
| 93 if name in commands: | |
| 94 return commands[name] | |
| 95 | |
| 96 # An exact match was not found. Try to be smart and look if there's | |
| 97 # something similar. | |
| 98 commands_with_prefix = [c for c in commands if c.startswith(name)] | |
| 99 if len(commands_with_prefix) == 1: | |
| 100 return commands[commands_with_prefix[0]] | |
| 101 | |
| 102 # A #closeenough approximation of levenshtein distance. | |
| 103 def close_enough(a, b): | |
| 104 return difflib.SequenceMatcher(a=a, b=b).ratio() | |
| 105 | |
| 106 hamming_commands = sorted( | |
| 107 ((close_enough(c, name), c) for c in commands), | |
| 108 reverse=True) | |
| 109 if (hamming_commands[0][0] - hamming_commands[1][0]) < 0.3: | |
| 110 # Too ambiguous. | |
| 111 return | |
| 112 | |
| 113 if hamming_commands[0][0] < 0.8: | |
| 114 # Not similar enough. Don't be a fool and run a random command. | |
| 115 return | |
| 116 | |
| 117 return commands[hamming_commands[0][1]] | |
| 118 | |
| 119 def _add_command_usage(self, parser, command): | |
| 120 """Modifies an OptionParser object with the function's documentation.""" | |
| 121 name = command.__name__[3:] | |
| 122 more = getattr(command, 'usage_more', '') | |
| 123 if name == 'help': | |
| 124 name = '<command>' | |
| 125 # Use the __main__ module docstring as the help. | |
| 126 parser.description = self.module.__doc__.strip() + '\n' | |
| 127 else: | |
| 128 parser.description = command.__doc__.strip() or '' | |
| 129 if parser.description: | |
| 130 parser.description += '\n' | |
| 131 parser.set_usage('usage: %%prog %s [options] %s' % (name, more)) | |
| 132 | |
| 133 def execute(self, parser, args): | |
| 134 """Dispatches execution to the right command. | |
| 135 | |
| 136 Fallbacks to 'help'. | |
| 137 """ | |
| 138 commands = self.get_commands() | |
| 139 length = max(len(c) for c in commands) | |
| 140 | |
| 141 def gen_summary(x): | |
| 142 """Creates a oneline summary from the docstring.""" | |
| 143 line = x.__doc__.split('\n', 1)[0].rstrip('.') | |
| 144 return (line[0].lower() + line[1:]).strip() | |
| 145 | |
| 146 docs = sorted( | |
| 147 (name, gen_summary(handler)) for name, handler in commands.iteritems()) | |
| 148 | |
| 149 # Lists all the commands in 'help'. | |
| 150 if commands['help']: | |
| 151 commands['help'].usage_more = ( | |
| 152 '\n\nCommands are:\n' + '\n'.join( | |
| 153 ' %-*s %s' % (length, name, doc) for name, doc in docs)) | |
| 154 | |
| 155 if args: | |
| 156 if args[0] in ('-h', '--help') and len(args) > 1: | |
| 157 # Inverse the argument order so 'tool --help cmd' is rewritten to | |
| 158 # 'tool cmd --help'. | |
| 159 args = [args[1], args[0]] + args[2:] | |
| 160 command = self.get_command(args[0]) | |
| 161 if command: | |
| 162 if command.__name__ == 'CMDhelp' and len(args) > 1: | |
| 163 # Inverse the arguments order so 'tool help cmd' is rewritten to | |
| 164 # 'tool cmd --help'. Do it here since we want 'tool hel cmd' to work | |
| 165 # too. | |
| 166 args = [args[1], '--help'] + args[2:] | |
| 167 command = self.get_command(args[0]) | |
| 168 | |
| 169 # "fix" the usage and the description now that we know the subcommand. | |
| 170 self._add_command_usage(parser, command) | |
| 171 return command(parser, args[1:]) | |
| 172 | |
| 173 if commands['help']: | |
| 174 # Not a known command. Default to help. | |
| 175 self._add_command_usage(parser, commands['help']) | |
| 176 return commands['help'](parser, args) | |
| 177 | |
| 178 # Nothing can be done. | |
| 179 return 2 | |
| OLD | NEW |