1
# Copyright (c) 2009 Google Inc. All rights reserved.
2
# Copyright (c) 2009 Apple Inc. All rights reserved.
4
# Redistribution and use in source and binary forms, with or without
5
# modification, are permitted provided that the following conditions are
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
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.
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.
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]
37
from optparse import OptionParser, IndentedHelpFormatter, SUPPRESS_USAGE, make_option
39
from webkitpy.tool.grammar import pluralize
41
_log = logging.getLogger(__name__)
44
class TryAgain(Exception):
48
class Command(object):
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
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)
63
def _exit(self, code):
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()
73
def _add_options_to_parser(self):
74
options = self.options or []
75
for option in options:
76
self.option_parser.add_option(option)
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!")
86
def _parse_required_arguments(argument_names):
88
if not argument_names:
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))
98
required_args.append(argument)
101
def name_with_arguments(self):
102
usage_string = self.name
104
usage_string += " [options]"
105
if self.argument_names:
106
usage_string += " " + self.argument_names
109
def parse_args(self, args):
110
return self.option_parser.parse_args(args)
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),
122
return self.execute(options, args, tool) or 0
124
def standalone_help(self):
125
help_text = self.name_with_arguments().ljust(len(self.name_with_arguments()) + 3) + self.help_text + "\n\n"
127
help_text += "%s\n\n" % self.long_help
128
help_text += self.option_parser.format_option_help(IndentedHelpFormatter())
131
def execute(self, options, args, tool):
132
raise NotImplementedError, "subclasses must implement"
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)
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):
145
argument_names = 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)
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)
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)
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()
171
class HelpCommand(AbstractDeclarativeCommand):
173
help_text = "Display information about this program or its subcommands"
174
argument_names = "[COMMAND]"
178
make_option("-a", "--all-commands", action="store_true", dest="show_all_commands", help="Print all available commands"),
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.
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[:]
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().
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())
204
def execute(self, options, args, tool):
206
command = self._tool.command_by_name(args[0])
208
print command.standalone_help()
211
self.show_all_commands = options.show_all_commands
212
self._remove_help_options()
213
self.option_parser.print_help()
217
class MultiCommandTool(object):
218
global_options = None
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)
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)
240
def _find_all_commands(cls):
242
cls._add_all_subclasses(Command, commands)
243
return sorted(commands)
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)
253
def _split_command_name_from_args(args):
254
# Assume the first argument which doesn't start with "-" is the command name.
261
return (None, args[:])
263
command = args[command_index]
264
return (command, args[:command_index] + args[command_index + 1:])
266
def command_by_name(self, command_name):
267
for command in self.commands:
268
if command_name == command.name:
273
raise NotImplementedError, "subclasses must implement"
275
def command_completed(self):
278
def should_show_in_main_help(self, command):
279
return command.show_in_main_help
281
def should_execute_command(self, command):
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)
289
def handle_global_options(self, options):
292
def main(self, argv=sys.argv):
293
(command_name, args) = self._split_command_name_from_args(argv[1:])
295
option_parser = self._create_option_parser()
296
self._add_global_options(option_parser)
298
command = self.command_by_name(command_name) or self.help_command
300
option_parser.error("%s is not a recognized command" % command_name)
302
command.set_option_parser(option_parser)
303
(options, args) = command.parse_args(args)
304
self.handle_global_options(options)
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?
313
result = command.check_arguments_and_execute(options, args, self)
318
self.command_completed()