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 34 import logging 35 import sys 36 37 from optparse import OptionParser, IndentedHelpFormatter, SUPPRESS_USAGE, make_option 38 39 from webkitpy.tool.grammar import pluralize 40 41 _log = logging.getLogger(__name__) 42 43 44 class TryAgain(Exception): 45 pass 46 47 48 class Command(object): 49 name = None 50 show_in_main_help = False 51 def __init__(self, help_text, argument_names=None, options=None, long_help=None, requires_local_commits=False): 52 self.help_text = help_text 53 self.long_help = long_help 54 self.argument_names = argument_names 55 self.required_arguments = self._parse_required_arguments(argument_names) 56 self.options = options 57 self.requires_local_commits = requires_local_commits 58 self._tool = None 59 # option_parser can be overriden by the tool using set_option_parser 60 # This default parser will be used for standalone_help printing. 61 self.option_parser = HelpPrintingOptionParser(usage=SUPPRESS_USAGE, add_help_option=False, option_list=self.options) 62 63 def _exit(self, code): 64 sys.exit(code) 65 66 # This design is slightly awkward, but we need the 67 # the tool to be able to create and modify the option_parser 68 # before it knows what Command to run. 69 def set_option_parser(self, option_parser): 70 self.option_parser = option_parser 71 self._add_options_to_parser() 72 73 def _add_options_to_parser(self): 74 options = self.options or [] 75 for option in options: 76 self.option_parser.add_option(option) 77 78 # The tool calls bind_to_tool on each Command after adding it to its list. 79 def bind_to_tool(self, tool): 80 # Command instances can only be bound to one tool at a time. 81 if self._tool and tool != self._tool: 82 raise Exception("Command already bound to tool!") 83 self._tool = tool 84 85 @staticmethod 86 def _parse_required_arguments(argument_names): 87 required_args = [] 88 if not argument_names: 89 return required_args 90 split_args = argument_names.split(" ") 91 for argument in split_args: 92 if argument[0] == '[': 93 # For now our parser is rather dumb. Do some minimal validation that 94 # we haven't confused it. 95 if argument[-1] != ']': 96 raise Exception("Failure to parse argument string %s. Argument %s is missing ending ]" % (argument_names, argument)) 97 else: 98 required_args.append(argument) 99 return required_args 100 101 def name_with_arguments(self): 102 usage_string = self.name 103 if self.options: 104 usage_string += " [options]" 105 if self.argument_names: 106 usage_string += " " + self.argument_names 107 return usage_string 108 109 def parse_args(self, args): 110 return self.option_parser.parse_args(args) 111 112 def check_arguments_and_execute(self, options, args, tool=None): 113 if len(args) < len(self.required_arguments): 114 _log.error("%s required, %s provided. Provided: %s Required: %s\nSee '%s help %s' for usage." % ( 115 pluralize("argument", len(self.required_arguments)), 116 pluralize("argument", len(args)), 117 "'%s'" % " ".join(args), 118 " ".join(self.required_arguments), 119 tool.name(), 120 self.name)) 121 return 1 122 return self.execute(options, args, tool) or 0 123 124 def standalone_help(self): 125 help_text = self.name_with_arguments().ljust(len(self.name_with_arguments()) + 3) + self.help_text + "\n\n" 126 if self.long_help: 127 help_text += "%s\n\n" % self.long_help 128 help_text += self.option_parser.format_option_help(IndentedHelpFormatter()) 129 return help_text 130 131 def execute(self, options, args, tool): 132 raise NotImplementedError, "subclasses must implement" 133 134 # main() exists so that Commands can be turned into stand-alone scripts. 135 # Other parts of the code will likely require modification to work stand-alone. 136 def main(self, args=sys.argv): 137 (options, args) = self.parse_args(args) 138 # Some commands might require a dummy tool 139 return self.check_arguments_and_execute(options, args) 140 141 142 # FIXME: This should just be rolled into Command. help_text and argument_names do not need to be instance variables. 143 class AbstractDeclarativeCommand(Command): 144 help_text = None 145 argument_names = None 146 long_help = None 147 def __init__(self, options=None, **kwargs): 148 Command.__init__(self, self.help_text, self.argument_names, options=options, long_help=self.long_help, **kwargs) 149 150 151 class HelpPrintingOptionParser(OptionParser): 152 def __init__(self, epilog_method=None, *args, **kwargs): 153 self.epilog_method = epilog_method 154 OptionParser.__init__(self, *args, **kwargs) 155 156 def error(self, msg): 157 self.print_usage(sys.stderr) 158 error_message = "%s: error: %s\n" % (self.get_prog_name(), msg) 159 # This method is overriden to add this one line to the output: 160 error_message += "\nType \"%s --help\" to see usage.\n" % self.get_prog_name() 161 self.exit(1, error_message) 162 163 # We override format_epilog to avoid the default formatting which would paragraph-wrap the epilog 164 # and also to allow us to compute the epilog lazily instead of in the constructor (allowing it to be context sensitive). 165 def format_epilog(self, epilog): 166 if self.epilog_method: 167 return "\n%s\n" % self.epilog_method() 168 return "" 169 170 171 class HelpCommand(AbstractDeclarativeCommand): 172 name = "help" 173 help_text = "Display information about this program or its subcommands" 174 argument_names = "[COMMAND]" 175 176 def __init__(self): 177 options = [ 178 make_option("-a", "--all-commands", action="store_true", dest="show_all_commands", help="Print all available commands"), 179 ] 180 AbstractDeclarativeCommand.__init__(self, options) 181 self.show_all_commands = False # A hack used to pass --all-commands to _help_epilog even though it's called by the OptionParser. 182 183 def _help_epilog(self): 184 # Only show commands which are relevant to this checkout's SCM system. Might this be confusing to some users? 185 if self.show_all_commands: 186 epilog = "All %prog commands:\n" 187 relevant_commands = self._tool.commands[:] 188 else: 189 epilog = "Common %prog commands:\n" 190 relevant_commands = filter(self._tool.should_show_in_main_help, self._tool.commands) 191 longest_name_length = max(map(lambda command: len(command.name), relevant_commands)) 192 relevant_commands.sort(lambda a, b: cmp(a.name, b.name)) 193 command_help_texts = map(lambda command: " %s %s\n" % (command.name.ljust(longest_name_length), command.help_text), relevant_commands) 194 epilog += "%s\n" % "".join(command_help_texts) 195 epilog += "See '%prog help --all-commands' to list all commands.\n" 196 epilog += "See '%prog help COMMAND' for more information on a specific command.\n" 197 return epilog.replace("%prog", self._tool.name()) # Use of %prog here mimics OptionParser.expand_prog_name(). 198 199 # FIXME: This is a hack so that we don't show --all-commands as a global option: 200 def _remove_help_options(self): 201 for option in self.options: 202 self.option_parser.remove_option(option.get_opt_string()) 203 204 def execute(self, options, args, tool): 205 if args: 206 command = self._tool.command_by_name(args[0]) 207 if command: 208 print command.standalone_help() 209 return 0 210 211 self.show_all_commands = options.show_all_commands 212 self._remove_help_options() 213 self.option_parser.print_help() 214 return 0 215 216 217 class MultiCommandTool(object): 218 global_options = None 219 220 def __init__(self, name=None, commands=None): 221 self._name = name or OptionParser(prog=name).get_prog_name() # OptionParser has nice logic for fetching the name. 222 # Allow the unit tests to disable command auto-discovery. 223 self.commands = commands or [cls() for cls in self._find_all_commands() if cls.name] 224 self.help_command = self.command_by_name(HelpCommand.name) 225 # Require a help command, even if the manual test list doesn't include one. 226 if not self.help_command: 227 self.help_command = HelpCommand() 228 self.commands.append(self.help_command) 229 for command in self.commands: 230 command.bind_to_tool(self) 231 232 @classmethod 233 def _add_all_subclasses(cls, class_to_crawl, seen_classes): 234 for subclass in class_to_crawl.__subclasses__(): 235 if subclass not in seen_classes: 236 seen_classes.add(subclass) 237 cls._add_all_subclasses(subclass, seen_classes) 238 239 @classmethod 240 def _find_all_commands(cls): 241 commands = set() 242 cls._add_all_subclasses(Command, commands) 243 return sorted(commands) 244 245 def name(self): 246 return self._name 247 248 def _create_option_parser(self): 249 usage = "Usage: %prog [options] COMMAND [ARGS]" 250 return HelpPrintingOptionParser(epilog_method=self.help_command._help_epilog, prog=self.name(), usage=usage) 251 252 @staticmethod 253 def _split_command_name_from_args(args): 254 # Assume the first argument which doesn't start with "-" is the command name. 255 command_index = 0 256 for arg in args: 257 if arg[0] != "-": 258 break 259 command_index += 1 260 else: 261 return (None, args[:]) 262 263 command = args[command_index] 264 return (command, args[:command_index] + args[command_index + 1:]) 265 266 def command_by_name(self, command_name): 267 for command in self.commands: 268 if command_name == command.name: 269 return command 270 return None 271 272 def path(self): 273 raise NotImplementedError, "subclasses must implement" 274 275 def command_completed(self): 276 pass 277 278 def should_show_in_main_help(self, command): 279 return command.show_in_main_help 280 281 def should_execute_command(self, command): 282 return True 283 284 def _add_global_options(self, option_parser): 285 global_options = self.global_options or [] 286 for option in global_options: 287 option_parser.add_option(option) 288 289 def handle_global_options(self, options): 290 pass 291 292 def main(self, argv=sys.argv): 293 (command_name, args) = self._split_command_name_from_args(argv[1:]) 294 295 option_parser = self._create_option_parser() 296 self._add_global_options(option_parser) 297 298 command = self.command_by_name(command_name) or self.help_command 299 if not command: 300 option_parser.error("%s is not a recognized command" % command_name) 301 302 command.set_option_parser(option_parser) 303 (options, args) = command.parse_args(args) 304 self.handle_global_options(options) 305 306 (should_execute, failure_reason) = self.should_execute_command(command) 307 if not should_execute: 308 _log.error(failure_reason) 309 return 0 # FIXME: Should this really be 0? 310 311 while True: 312 try: 313 result = command.check_arguments_and_execute(options, args, self) 314 break 315 except TryAgain, e: 316 pass 317 318 self.command_completed() 319 return result 320