subcommand.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # 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. """Manages subcommands in a script.
  5. Each subcommand should look like this:
  6. @usage('[pet name]')
  7. def CMDpet(parser, args):
  8. '''Prints a pet.
  9. Many people likes pet. This command prints a pet for your pleasure.
  10. '''
  11. parser.add_option('--color', help='color of your pet')
  12. options, args = parser.parse_args(args)
  13. if len(args) != 1:
  14. parser.error('A pet name is required')
  15. pet = args[0]
  16. if options.color:
  17. print('Nice %s %d' % (options.color, pet))
  18. else:
  19. print('Nice %s' % pet)
  20. return 0
  21. Explanation:
  22. - usage decorator alters the 'usage: %prog' line in the command's help.
  23. - docstring is used to both short help line and long help line.
  24. - parser can be augmented with arguments.
  25. - return the exit code.
  26. - Every function in the specified module with a name starting with 'CMD' will
  27. be a subcommand.
  28. - The module's docstring will be used in the default 'help' page.
  29. - If a command has no docstring, it will not be listed in the 'help' page.
  30. Useful to keep compatibility commands around or aliases.
  31. - If a command is an alias to another one, it won't be documented. E.g.:
  32. CMDoldname = CMDnewcmd
  33. will result in oldname not being documented but supported and redirecting to
  34. newcmd. Make it a real function that calls the old function if you want it
  35. to be documented.
  36. - CMDfoo_bar will be command 'foo-bar'.
  37. """
  38. import difflib
  39. import sys
  40. import textwrap
  41. import optparse
  42. from collections.abc import Callable
  43. from typing import NoReturn
  44. CommandFunction = Callable[[optparse.OptionParser, list[str]], int]
  45. def usage(more: str) -> Callable[[CommandFunction], CommandFunction]:
  46. """Adds a 'usage_more' property to a CMD function."""
  47. def hook(fn):
  48. fn.usage_more = more
  49. return fn
  50. return hook
  51. def epilog(text: str) -> Callable[[CommandFunction], CommandFunction]:
  52. """Adds an 'epilog' property to a CMD function.
  53. It will be shown in the epilog. Usually useful for examples.
  54. """
  55. def hook(fn):
  56. fn.epilog = text
  57. return fn
  58. return hook
  59. def CMDhelp(parser: optparse.OptionParser, args: list[str]) -> NoReturn:
  60. """Prints list of commands or help for a specific command."""
  61. # This is the default help implementation. It can be disabled or overridden
  62. # if wanted.
  63. if not any(i in ('-h', '--help') for i in args):
  64. args = args + ['--help']
  65. parser.parse_args(args)
  66. # Never gets there.
  67. assert False
  68. def _get_color_module():
  69. """Returns the colorama module if available.
  70. If so, assumes colors are supported and return the module handle.
  71. """
  72. return sys.modules.get('colorama') or sys.modules.get(
  73. 'third_party.colorama')
  74. def _function_to_name(name: str) -> str:
  75. """Returns the name of a CMD function."""
  76. return name[3:].replace('_', '-')
  77. class CommandDispatcher(object):
  78. def __init__(self, module: str):
  79. """module is the name of the main python module where to look for
  80. commands.
  81. The python builtin variable __name__ MUST be used for |module|. If the
  82. script is executed in the form 'python script.py',
  83. __name__ == '__main__' and sys.modules['script'] doesn't exist. On the
  84. other hand if it is unit tested, __main__ will be the unit test's
  85. module so it has to reference to itself with 'script'. __name__ always
  86. match the right value.
  87. """
  88. self.module = sys.modules[module]
  89. def enumerate_commands(self) -> dict[str, CommandFunction]:
  90. """Returns a dict of command and their handling function.
  91. The commands must be in the '__main__' modules. To import a command
  92. from a submodule, use:
  93. from mysubcommand import CMDfoo
  94. Automatically adds 'help' if not already defined.
  95. Normalizes '_' in the commands to '-'.
  96. A command can be effectively disabled by defining a global variable to
  97. None, e.g.:
  98. CMDhelp = None
  99. """
  100. cmds = dict((_function_to_name(name), getattr(self.module, name))
  101. for name in dir(self.module) if name.startswith('CMD'))
  102. cmds.setdefault('help', CMDhelp)
  103. return cmds
  104. def find_nearest_command(self, name_asked: str) -> CommandFunction | None:
  105. """Retrieves the function to handle a command as supplied by the user.
  106. It automatically tries to guess the _intended command_ by handling typos
  107. and/or incomplete names.
  108. """
  109. commands = self.enumerate_commands()
  110. name_to_dash = name_asked.replace('_', '-')
  111. if name_to_dash in commands:
  112. return commands[name_to_dash]
  113. # An exact match was not found. Try to be smart and look if there's
  114. # something similar.
  115. commands_with_prefix = [c for c in commands if c.startswith(name_asked)]
  116. if len(commands_with_prefix) == 1:
  117. return commands[commands_with_prefix[0]]
  118. # A #closeenough approximation of levenshtein distance.
  119. def close_enough(a, b):
  120. return difflib.SequenceMatcher(a=a, b=b).ratio()
  121. hamming_commands = sorted(
  122. ((close_enough(c, name_asked), c) for c in commands), reverse=True)
  123. if (hamming_commands[0][0] - hamming_commands[1][0]) < 0.3:
  124. # Too ambiguous.
  125. return None
  126. if hamming_commands[0][0] < 0.8:
  127. # Not similar enough. Don't be a fool and run a random command.
  128. return None
  129. return commands[hamming_commands[0][1]]
  130. def _gen_commands_list(self) -> str:
  131. """Generates the short list of supported commands."""
  132. commands = self.enumerate_commands()
  133. docs = sorted(
  134. (cmd_name, self._create_command_summary(cmd_name, handler))
  135. for cmd_name, handler in commands.items())
  136. # Skip commands without a docstring.
  137. docs = [i for i in docs if i[1]]
  138. # Then calculate maximum length for alignment:
  139. length = max(len(c) for c in commands)
  140. # Look if color is supported.
  141. colors = _get_color_module()
  142. green = reset = ''
  143. if colors:
  144. green = colors.Fore.GREEN
  145. reset = colors.Fore.RESET
  146. return ('Commands are:\n' +
  147. ''.join(' %s%-*s%s %s\n' %
  148. (green, length, cmd_name, reset, doc)
  149. for cmd_name, doc in docs))
  150. def _add_command_usage(self, parser: optparse.OptionParser,
  151. command: CommandFunction) -> None:
  152. """Modifies an OptionParser object with the function's documentation."""
  153. cmd_name = _function_to_name(command.__name__)
  154. if cmd_name == 'help':
  155. cmd_name = '<command>'
  156. # Use the module's docstring as the description for the 'help'
  157. # command if available.
  158. parser.description = (self.module.__doc__ or '').rstrip()
  159. if parser.description:
  160. parser.description += '\n\n'
  161. parser.description += self._gen_commands_list()
  162. # Do not touch epilog.
  163. else:
  164. # Use the command's docstring if available. For commands, unlike
  165. # module docstring, realign.
  166. lines = (command.__doc__ or '').rstrip().splitlines()
  167. if lines[:1]:
  168. rest = textwrap.dedent('\n'.join(lines[1:]))
  169. parser.description = '\n'.join((lines[0], rest))
  170. else:
  171. parser.description = lines[0] if lines else ''
  172. if parser.description:
  173. parser.description += '\n'
  174. parser.epilog = getattr(command, 'epilog', None)
  175. if parser.epilog:
  176. parser.epilog = '\n' + parser.epilog.strip() + '\n'
  177. more = getattr(command, 'usage_more', '')
  178. extra = '' if not more else ' ' + more
  179. parser.set_usage('usage: %%prog %s [options]%s' % (cmd_name, extra))
  180. @staticmethod
  181. def _create_command_summary(cmd_name: str, command: CommandFunction) -> str:
  182. """Creates a oneliner summary from the command's docstring."""
  183. if cmd_name != _function_to_name(command.__name__):
  184. # Skip aliases. For example using at module level:
  185. # CMDfoo = CMDbar
  186. return ''
  187. doc = command.__doc__ or ''
  188. line = doc.split('\n', 1)[0].rstrip('.')
  189. if not line:
  190. return line
  191. return (line[0].lower() + line[1:]).strip()
  192. def execute(self, parser: optparse.OptionParser, args: list[str]) -> int:
  193. """Dispatches execution to the right command.
  194. Fallbacks to 'help' if not disabled.
  195. """
  196. # Unconditionally disable format_description() and format_epilog().
  197. # Technically, a formatter should be used but it's not worth (yet) the
  198. # trouble.
  199. parser.format_description = lambda formatter: parser.description or ''
  200. parser.format_epilog = lambda formatter: parser.epilog or ''
  201. if args:
  202. if args[0] in ('-h', '--help') and len(args) > 1:
  203. # Reverse the argument order so 'tool --help cmd' is rewritten
  204. # to 'tool cmd --help'.
  205. args = [args[1], args[0]] + args[2:]
  206. command = self.find_nearest_command(args[0])
  207. if command:
  208. if command.__name__ == 'CMDhelp' and len(args) > 1:
  209. # Reverse the argument order so 'tool help cmd' is rewritten
  210. # to 'tool cmd --help'. Do it here since we want 'tool help
  211. # cmd' to work too.
  212. args = [args[1], '--help'] + args[2:]
  213. command = self.find_nearest_command(args[0]) or command
  214. # "fix" the usage and the description now that we know the
  215. # subcommand.
  216. self._add_command_usage(parser, command)
  217. return command(parser, args[1:])
  218. cmdhelp = self.enumerate_commands().get('help')
  219. if cmdhelp:
  220. # Not a known command. Default to help.
  221. self._add_command_usage(parser, cmdhelp)
  222. # Don't pass list of arguments as those may not be supported by
  223. # cmdhelp. See: https://crbug.com/1352093
  224. return cmdhelp(parser, [])
  225. # Nothing can be done.
  226. return 2