PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/external/webkit/Tools/Scripts/webkitpy/tool/multicommandtool.py

https://gitlab.com/brian0218/rk3066_r-box_android4.2.2_sdk
Python | 314 lines | 243 code | 23 blank | 48 comment | 17 complexity | 85f1539e9bd12d9104c536bf78d4e488 MD5 | raw file
  1. # Copyright (c) 2009 Google Inc. All rights reserved.
  2. # Copyright (c) 2009 Apple Inc. All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above
  11. # copyright notice, this list of conditions and the following disclaimer
  12. # in the documentation and/or other materials provided with the
  13. # distribution.
  14. # * Neither the name of Google Inc. nor the names of its
  15. # contributors may be used to endorse or promote products derived from
  16. # this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. #
  30. # MultiCommandTool provides a framework for writing svn-like/git-like tools
  31. # which are called with the following format:
  32. # tool-name [global options] command-name [command options]
  33. import sys
  34. from optparse import OptionParser, IndentedHelpFormatter, SUPPRESS_USAGE, make_option
  35. from webkitpy.tool.grammar import pluralize
  36. from webkitpy.common.system.deprecated_logging import log
  37. class TryAgain(Exception):
  38. pass
  39. class Command(object):
  40. name = None
  41. show_in_main_help = False
  42. def __init__(self, help_text, argument_names=None, options=None, long_help=None, requires_local_commits=False):
  43. self.help_text = help_text
  44. self.long_help = long_help
  45. self.argument_names = argument_names
  46. self.required_arguments = self._parse_required_arguments(argument_names)
  47. self.options = options
  48. self.requires_local_commits = requires_local_commits
  49. self._tool = None
  50. # option_parser can be overriden by the tool using set_option_parser
  51. # This default parser will be used for standalone_help printing.
  52. self.option_parser = HelpPrintingOptionParser(usage=SUPPRESS_USAGE, add_help_option=False, option_list=self.options)
  53. # This design is slightly awkward, but we need the
  54. # the tool to be able to create and modify the option_parser
  55. # before it knows what Command to run.
  56. def set_option_parser(self, option_parser):
  57. self.option_parser = option_parser
  58. self._add_options_to_parser()
  59. def _add_options_to_parser(self):
  60. options = self.options or []
  61. for option in options:
  62. self.option_parser.add_option(option)
  63. # The tool calls bind_to_tool on each Command after adding it to its list.
  64. def bind_to_tool(self, tool):
  65. # Command instances can only be bound to one tool at a time.
  66. if self._tool and tool != self._tool:
  67. raise Exception("Command already bound to tool!")
  68. self._tool = tool
  69. @staticmethod
  70. def _parse_required_arguments(argument_names):
  71. required_args = []
  72. if not argument_names:
  73. return required_args
  74. split_args = argument_names.split(" ")
  75. for argument in split_args:
  76. if argument[0] == '[':
  77. # For now our parser is rather dumb. Do some minimal validation that
  78. # we haven't confused it.
  79. if argument[-1] != ']':
  80. raise Exception("Failure to parse argument string %s. Argument %s is missing ending ]" % (argument_names, argument))
  81. else:
  82. required_args.append(argument)
  83. return required_args
  84. def name_with_arguments(self):
  85. usage_string = self.name
  86. if self.options:
  87. usage_string += " [options]"
  88. if self.argument_names:
  89. usage_string += " " + self.argument_names
  90. return usage_string
  91. def parse_args(self, args):
  92. return self.option_parser.parse_args(args)
  93. def check_arguments_and_execute(self, options, args, tool=None):
  94. if len(args) < len(self.required_arguments):
  95. log("%s required, %s provided. Provided: %s Required: %s\nSee '%s help %s' for usage." % (
  96. pluralize("argument", len(self.required_arguments)),
  97. pluralize("argument", len(args)),
  98. "'%s'" % " ".join(args),
  99. " ".join(self.required_arguments),
  100. tool.name(),
  101. self.name))
  102. return 1
  103. return self.execute(options, args, tool) or 0
  104. def standalone_help(self):
  105. help_text = self.name_with_arguments().ljust(len(self.name_with_arguments()) + 3) + self.help_text + "\n\n"
  106. if self.long_help:
  107. help_text += "%s\n\n" % self.long_help
  108. help_text += self.option_parser.format_option_help(IndentedHelpFormatter())
  109. return help_text
  110. def execute(self, options, args, tool):
  111. raise NotImplementedError, "subclasses must implement"
  112. # main() exists so that Commands can be turned into stand-alone scripts.
  113. # Other parts of the code will likely require modification to work stand-alone.
  114. def main(self, args=sys.argv):
  115. (options, args) = self.parse_args(args)
  116. # Some commands might require a dummy tool
  117. return self.check_arguments_and_execute(options, args)
  118. # FIXME: This should just be rolled into Command. help_text and argument_names do not need to be instance variables.
  119. class AbstractDeclarativeCommand(Command):
  120. help_text = None
  121. argument_names = None
  122. long_help = None
  123. def __init__(self, options=None, **kwargs):
  124. Command.__init__(self, self.help_text, self.argument_names, options=options, long_help=self.long_help, **kwargs)
  125. class HelpPrintingOptionParser(OptionParser):
  126. def __init__(self, epilog_method=None, *args, **kwargs):
  127. self.epilog_method = epilog_method
  128. OptionParser.__init__(self, *args, **kwargs)
  129. def error(self, msg):
  130. self.print_usage(sys.stderr)
  131. error_message = "%s: error: %s\n" % (self.get_prog_name(), msg)
  132. # This method is overriden to add this one line to the output:
  133. error_message += "\nType \"%s --help\" to see usage.\n" % self.get_prog_name()
  134. self.exit(1, error_message)
  135. # We override format_epilog to avoid the default formatting which would paragraph-wrap the epilog
  136. # and also to allow us to compute the epilog lazily instead of in the constructor (allowing it to be context sensitive).
  137. def format_epilog(self, epilog):
  138. if self.epilog_method:
  139. return "\n%s\n" % self.epilog_method()
  140. return ""
  141. class HelpCommand(AbstractDeclarativeCommand):
  142. name = "help"
  143. help_text = "Display information about this program or its subcommands"
  144. argument_names = "[COMMAND]"
  145. def __init__(self):
  146. options = [
  147. make_option("-a", "--all-commands", action="store_true", dest="show_all_commands", help="Print all available commands"),
  148. ]
  149. AbstractDeclarativeCommand.__init__(self, options)
  150. self.show_all_commands = False # A hack used to pass --all-commands to _help_epilog even though it's called by the OptionParser.
  151. def _help_epilog(self):
  152. # Only show commands which are relevant to this checkout's SCM system. Might this be confusing to some users?
  153. if self.show_all_commands:
  154. epilog = "All %prog commands:\n"
  155. relevant_commands = self._tool.commands[:]
  156. else:
  157. epilog = "Common %prog commands:\n"
  158. relevant_commands = filter(self._tool.should_show_in_main_help, self._tool.commands)
  159. longest_name_length = max(map(lambda command: len(command.name), relevant_commands))
  160. relevant_commands.sort(lambda a, b: cmp(a.name, b.name))
  161. command_help_texts = map(lambda command: " %s %s\n" % (command.name.ljust(longest_name_length), command.help_text), relevant_commands)
  162. epilog += "%s\n" % "".join(command_help_texts)
  163. epilog += "See '%prog help --all-commands' to list all commands.\n"
  164. epilog += "See '%prog help COMMAND' for more information on a specific command.\n"
  165. return epilog.replace("%prog", self._tool.name()) # Use of %prog here mimics OptionParser.expand_prog_name().
  166. # FIXME: This is a hack so that we don't show --all-commands as a global option:
  167. def _remove_help_options(self):
  168. for option in self.options:
  169. self.option_parser.remove_option(option.get_opt_string())
  170. def execute(self, options, args, tool):
  171. if args:
  172. command = self._tool.command_by_name(args[0])
  173. if command:
  174. print command.standalone_help()
  175. return 0
  176. self.show_all_commands = options.show_all_commands
  177. self._remove_help_options()
  178. self.option_parser.print_help()
  179. return 0
  180. class MultiCommandTool(object):
  181. global_options = None
  182. def __init__(self, name=None, commands=None):
  183. self._name = name or OptionParser(prog=name).get_prog_name() # OptionParser has nice logic for fetching the name.
  184. # Allow the unit tests to disable command auto-discovery.
  185. self.commands = commands or [cls() for cls in self._find_all_commands() if cls.name]
  186. self.help_command = self.command_by_name(HelpCommand.name)
  187. # Require a help command, even if the manual test list doesn't include one.
  188. if not self.help_command:
  189. self.help_command = HelpCommand()
  190. self.commands.append(self.help_command)
  191. for command in self.commands:
  192. command.bind_to_tool(self)
  193. @classmethod
  194. def _add_all_subclasses(cls, class_to_crawl, seen_classes):
  195. for subclass in class_to_crawl.__subclasses__():
  196. if subclass not in seen_classes:
  197. seen_classes.add(subclass)
  198. cls._add_all_subclasses(subclass, seen_classes)
  199. @classmethod
  200. def _find_all_commands(cls):
  201. commands = set()
  202. cls._add_all_subclasses(Command, commands)
  203. return sorted(commands)
  204. def name(self):
  205. return self._name
  206. def _create_option_parser(self):
  207. usage = "Usage: %prog [options] COMMAND [ARGS]"
  208. return HelpPrintingOptionParser(epilog_method=self.help_command._help_epilog, prog=self.name(), usage=usage)
  209. @staticmethod
  210. def _split_command_name_from_args(args):
  211. # Assume the first argument which doesn't start with "-" is the command name.
  212. command_index = 0
  213. for arg in args:
  214. if arg[0] != "-":
  215. break
  216. command_index += 1
  217. else:
  218. return (None, args[:])
  219. command = args[command_index]
  220. return (command, args[:command_index] + args[command_index + 1:])
  221. def command_by_name(self, command_name):
  222. for command in self.commands:
  223. if command_name == command.name:
  224. return command
  225. return None
  226. def path(self):
  227. raise NotImplementedError, "subclasses must implement"
  228. def command_completed(self):
  229. pass
  230. def should_show_in_main_help(self, command):
  231. return command.show_in_main_help
  232. def should_execute_command(self, command):
  233. return True
  234. def _add_global_options(self, option_parser):
  235. global_options = self.global_options or []
  236. for option in global_options:
  237. option_parser.add_option(option)
  238. def handle_global_options(self, options):
  239. pass
  240. def main(self, argv=sys.argv):
  241. (command_name, args) = self._split_command_name_from_args(argv[1:])
  242. option_parser = self._create_option_parser()
  243. self._add_global_options(option_parser)
  244. command = self.command_by_name(command_name) or self.help_command
  245. if not command:
  246. option_parser.error("%s is not a recognized command" % command_name)
  247. command.set_option_parser(option_parser)
  248. (options, args) = command.parse_args(args)
  249. self.handle_global_options(options)
  250. (should_execute, failure_reason) = self.should_execute_command(command)
  251. if not should_execute:
  252. log(failure_reason)
  253. return 0 # FIXME: Should this really be 0?
  254. while True:
  255. try:
  256. result = command.check_arguments_and_execute(options, args, self)
  257. break
  258. except TryAgain, e:
  259. pass
  260. self.command_completed()
  261. return result