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