1dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Block# Copyright (c) 2009 Google Inc. All rights reserved.
2643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# Copyright (c) 2009 Apple Inc. All rights reserved.
3643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#
4643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# Redistribution and use in source and binary forms, with or without
5643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# modification, are permitted provided that the following conditions are
6643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# met:
7643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#
8643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#     * Redistributions of source code must retain the above copyright
9643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# notice, this list of conditions and the following disclaimer.
10643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#     * Redistributions in binary form must reproduce the above
11643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# copyright notice, this list of conditions and the following disclaimer
12643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# in the documentation and/or other materials provided with the
13643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# distribution.
14643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#     * Neither the name of Google Inc. nor the names of its
15643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# contributors may be used to endorse or promote products derived from
16643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# this software without specific prior written permission.
17643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#
18643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29643ca7872b450ea4efacab6188849e5aac2ba161Steve Block#
30643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# MultiCommandTool provides a framework for writing svn-like/git-like tools
31643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# which are called with the following format:
32643ca7872b450ea4efacab6188849e5aac2ba161Steve Block# tool-name [global options] command-name [command options]
33643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
34643ca7872b450ea4efacab6188849e5aac2ba161Steve Blockimport sys
35643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
36643ca7872b450ea4efacab6188849e5aac2ba161Steve Blockfrom optparse import OptionParser, IndentedHelpFormatter, SUPPRESS_USAGE, make_option
37643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
38dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Blockfrom webkitpy.tool.grammar import pluralize
39dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Blockfrom webkitpy.common.system.deprecated_logging import log
40d0825bca7fe65beaee391d30da42e937db621564Steve Block
41643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
42e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarkeclass TryAgain(Exception):
43e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke    pass
44e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke
45e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke
46643ca7872b450ea4efacab6188849e5aac2ba161Steve Blockclass Command(object):
47643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    name = None
48d0825bca7fe65beaee391d30da42e937db621564Steve Block    show_in_main_help = False
49d0825bca7fe65beaee391d30da42e937db621564Steve Block    def __init__(self, help_text, argument_names=None, options=None, long_help=None, requires_local_commits=False):
50643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.help_text = help_text
51d0825bca7fe65beaee391d30da42e937db621564Steve Block        self.long_help = long_help
52643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.argument_names = argument_names
53643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.required_arguments = self._parse_required_arguments(argument_names)
54643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.options = options
55643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.requires_local_commits = requires_local_commits
56bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen        self._tool = None
57d0825bca7fe65beaee391d30da42e937db621564Steve Block        # option_parser can be overriden by the tool using set_option_parser
58d0825bca7fe65beaee391d30da42e937db621564Steve Block        # This default parser will be used for standalone_help printing.
59d0825bca7fe65beaee391d30da42e937db621564Steve Block        self.option_parser = HelpPrintingOptionParser(usage=SUPPRESS_USAGE, add_help_option=False, option_list=self.options)
60d0825bca7fe65beaee391d30da42e937db621564Steve Block
61d0825bca7fe65beaee391d30da42e937db621564Steve Block    # This design is slightly awkward, but we need the
62d0825bca7fe65beaee391d30da42e937db621564Steve Block    # the tool to be able to create and modify the option_parser
63d0825bca7fe65beaee391d30da42e937db621564Steve Block    # before it knows what Command to run.
64d0825bca7fe65beaee391d30da42e937db621564Steve Block    def set_option_parser(self, option_parser):
65d0825bca7fe65beaee391d30da42e937db621564Steve Block        self.option_parser = option_parser
66d0825bca7fe65beaee391d30da42e937db621564Steve Block        self._add_options_to_parser()
67d0825bca7fe65beaee391d30da42e937db621564Steve Block
68d0825bca7fe65beaee391d30da42e937db621564Steve Block    def _add_options_to_parser(self):
69d0825bca7fe65beaee391d30da42e937db621564Steve Block        options = self.options or []
70d0825bca7fe65beaee391d30da42e937db621564Steve Block        for option in options:
71d0825bca7fe65beaee391d30da42e937db621564Steve Block            self.option_parser.add_option(option)
72643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
73643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    # The tool calls bind_to_tool on each Command after adding it to its list.
74643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def bind_to_tool(self, tool):
75643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        # Command instances can only be bound to one tool at a time.
76bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen        if self._tool and tool != self._tool:
77643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            raise Exception("Command already bound to tool!")
78bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen        self._tool = tool
79643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
80643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    @staticmethod
81643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def _parse_required_arguments(argument_names):
82643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        required_args = []
83643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if not argument_names:
84643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            return required_args
85643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        split_args = argument_names.split(" ")
86643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        for argument in split_args:
87643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            if argument[0] == '[':
88643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                # For now our parser is rather dumb.  Do some minimal validation that
89643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                # we haven't confused it.
90643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                if argument[-1] != ']':
91643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                    raise Exception("Failure to parse argument string %s.  Argument %s is missing ending ]" % (argument_names, argument))
92643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            else:
93643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                required_args.append(argument)
94643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return required_args
95643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
96643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def name_with_arguments(self):
97643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        usage_string = self.name
98643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if self.options:
99643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            usage_string += " [options]"
100643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if self.argument_names:
101643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            usage_string += " " + self.argument_names
102643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return usage_string
103643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
104643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def parse_args(self, args):
105643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return self.option_parser.parse_args(args)
106643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
107d0825bca7fe65beaee391d30da42e937db621564Steve Block    def check_arguments_and_execute(self, options, args, tool=None):
108d0825bca7fe65beaee391d30da42e937db621564Steve Block        if len(args) < len(self.required_arguments):
109643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            log("%s required, %s provided.  Provided: %s  Required: %s\nSee '%s help %s' for usage." % (
110643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                pluralize("argument", len(self.required_arguments)),
111d0825bca7fe65beaee391d30da42e937db621564Steve Block                pluralize("argument", len(args)),
112d0825bca7fe65beaee391d30da42e937db621564Steve Block                "'%s'" % " ".join(args),
113643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                " ".join(self.required_arguments),
114643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                tool.name(),
115643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                self.name))
116643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            return 1
117d0825bca7fe65beaee391d30da42e937db621564Steve Block        return self.execute(options, args, tool) or 0
118643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
119643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def standalone_help(self):
120d0825bca7fe65beaee391d30da42e937db621564Steve Block        help_text = self.name_with_arguments().ljust(len(self.name_with_arguments()) + 3) + self.help_text + "\n\n"
121d0825bca7fe65beaee391d30da42e937db621564Steve Block        if self.long_help:
122d0825bca7fe65beaee391d30da42e937db621564Steve Block            help_text += "%s\n\n" % self.long_help
123643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        help_text += self.option_parser.format_option_help(IndentedHelpFormatter())
124643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return help_text
125643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
126643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def execute(self, options, args, tool):
127643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        raise NotImplementedError, "subclasses must implement"
128643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
129d0825bca7fe65beaee391d30da42e937db621564Steve Block    # main() exists so that Commands can be turned into stand-alone scripts.
130d0825bca7fe65beaee391d30da42e937db621564Steve Block    # Other parts of the code will likely require modification to work stand-alone.
131d0825bca7fe65beaee391d30da42e937db621564Steve Block    def main(self, args=sys.argv):
132d0825bca7fe65beaee391d30da42e937db621564Steve Block        (options, args) = self.parse_args(args)
133d0825bca7fe65beaee391d30da42e937db621564Steve Block        # Some commands might require a dummy tool
134d0825bca7fe65beaee391d30da42e937db621564Steve Block        return self.check_arguments_and_execute(options, args)
135d0825bca7fe65beaee391d30da42e937db621564Steve Block
136d0825bca7fe65beaee391d30da42e937db621564Steve Block
137d0825bca7fe65beaee391d30da42e937db621564Steve Block# FIXME: This should just be rolled into Command.  help_text and argument_names do not need to be instance variables.
138d0825bca7fe65beaee391d30da42e937db621564Steve Blockclass AbstractDeclarativeCommand(Command):
139d0825bca7fe65beaee391d30da42e937db621564Steve Block    help_text = None
140d0825bca7fe65beaee391d30da42e937db621564Steve Block    argument_names = None
141d0825bca7fe65beaee391d30da42e937db621564Steve Block    long_help = None
142d0825bca7fe65beaee391d30da42e937db621564Steve Block    def __init__(self, options=None, **kwargs):
143d0825bca7fe65beaee391d30da42e937db621564Steve Block        Command.__init__(self, self.help_text, self.argument_names, options=options, long_help=self.long_help, **kwargs)
144d0825bca7fe65beaee391d30da42e937db621564Steve Block
145643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
146643ca7872b450ea4efacab6188849e5aac2ba161Steve Blockclass HelpPrintingOptionParser(OptionParser):
147643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def __init__(self, epilog_method=None, *args, **kwargs):
148643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.epilog_method = epilog_method
149643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        OptionParser.__init__(self, *args, **kwargs)
150643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
151643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def error(self, msg):
152643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.print_usage(sys.stderr)
153643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        error_message = "%s: error: %s\n" % (self.get_prog_name(), msg)
154d0825bca7fe65beaee391d30da42e937db621564Steve Block        # This method is overriden to add this one line to the output:
155643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        error_message += "\nType \"%s --help\" to see usage.\n" % self.get_prog_name()
156643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.exit(1, error_message)
157643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
158643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    # We override format_epilog to avoid the default formatting which would paragraph-wrap the epilog
159643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    # and also to allow us to compute the epilog lazily instead of in the constructor (allowing it to be context sensitive).
160643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def format_epilog(self, epilog):
161643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if self.epilog_method:
162643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            return "\n%s\n" % self.epilog_method()
163643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return ""
164643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
165643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
166d0825bca7fe65beaee391d30da42e937db621564Steve Blockclass HelpCommand(AbstractDeclarativeCommand):
167643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    name = "help"
168d0825bca7fe65beaee391d30da42e937db621564Steve Block    help_text = "Display information about this program or its subcommands"
169d0825bca7fe65beaee391d30da42e937db621564Steve Block    argument_names = "[COMMAND]"
170643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
171643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def __init__(self):
172643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        options = [
173643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            make_option("-a", "--all-commands", action="store_true", dest="show_all_commands", help="Print all available commands"),
174643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        ]
175d0825bca7fe65beaee391d30da42e937db621564Steve Block        AbstractDeclarativeCommand.__init__(self, options)
176643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.show_all_commands = False # A hack used to pass --all-commands to _help_epilog even though it's called by the OptionParser.
177643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
178643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def _help_epilog(self):
179643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        # Only show commands which are relevant to this checkout's SCM system.  Might this be confusing to some users?
180643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if self.show_all_commands:
181643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            epilog = "All %prog commands:\n"
182bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen            relevant_commands = self._tool.commands[:]
183643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        else:
184643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            epilog = "Common %prog commands:\n"
185bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen            relevant_commands = filter(self._tool.should_show_in_main_help, self._tool.commands)
186643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        longest_name_length = max(map(lambda command: len(command.name), relevant_commands))
187643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        relevant_commands.sort(lambda a, b: cmp(a.name, b.name))
188643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        command_help_texts = map(lambda command: "   %s   %s\n" % (command.name.ljust(longest_name_length), command.help_text), relevant_commands)
189643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        epilog += "%s\n" % "".join(command_help_texts)
190643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        epilog += "See '%prog help --all-commands' to list all commands.\n"
191643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        epilog += "See '%prog help COMMAND' for more information on a specific command.\n"
192bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen        return epilog.replace("%prog", self._tool.name()) # Use of %prog here mimics OptionParser.expand_prog_name().
193d0825bca7fe65beaee391d30da42e937db621564Steve Block
194d0825bca7fe65beaee391d30da42e937db621564Steve Block    # FIXME: This is a hack so that we don't show --all-commands as a global option:
195d0825bca7fe65beaee391d30da42e937db621564Steve Block    def _remove_help_options(self):
196d0825bca7fe65beaee391d30da42e937db621564Steve Block        for option in self.options:
197d0825bca7fe65beaee391d30da42e937db621564Steve Block            self.option_parser.remove_option(option.get_opt_string())
198643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
199643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def execute(self, options, args, tool):
200643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if args:
201bec39347bb3bb5bf1187ccaf471d26247f28b585Kristian Monsen            command = self._tool.command_by_name(args[0])
202643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            if command:
203643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                print command.standalone_help()
204643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                return 0
205643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
206643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.show_all_commands = options.show_all_commands
207d0825bca7fe65beaee391d30da42e937db621564Steve Block        self._remove_help_options()
208d0825bca7fe65beaee391d30da42e937db621564Steve Block        self.option_parser.print_help()
209643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return 0
210643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
211643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
212643ca7872b450ea4efacab6188849e5aac2ba161Steve Blockclass MultiCommandTool(object):
213d0825bca7fe65beaee391d30da42e937db621564Steve Block    global_options = None
214d0825bca7fe65beaee391d30da42e937db621564Steve Block
215643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def __init__(self, name=None, commands=None):
216d0825bca7fe65beaee391d30da42e937db621564Steve Block        self._name = name or OptionParser(prog=name).get_prog_name() # OptionParser has nice logic for fetching the name.
217643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        # Allow the unit tests to disable command auto-discovery.
218643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.commands = commands or [cls() for cls in self._find_all_commands() if cls.name]
219643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        self.help_command = self.command_by_name(HelpCommand.name)
220643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        # Require a help command, even if the manual test list doesn't include one.
221643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if not self.help_command:
222643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            self.help_command = HelpCommand()
223643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            self.commands.append(self.help_command)
224643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        for command in self.commands:
225643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            command.bind_to_tool(self)
226643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
227643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    @classmethod
228643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def _add_all_subclasses(cls, class_to_crawl, seen_classes):
229643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        for subclass in class_to_crawl.__subclasses__():
230643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            if subclass not in seen_classes:
231643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                seen_classes.add(subclass)
232643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                cls._add_all_subclasses(subclass, seen_classes)
233643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
234643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    @classmethod
235643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def _find_all_commands(cls):
236643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        commands = set()
237643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        cls._add_all_subclasses(Command, commands)
238643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return sorted(commands)
239643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
240643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def name(self):
241d0825bca7fe65beaee391d30da42e937db621564Steve Block        return self._name
242643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
243d0825bca7fe65beaee391d30da42e937db621564Steve Block    def _create_option_parser(self):
244d0825bca7fe65beaee391d30da42e937db621564Steve Block        usage = "Usage: %prog [options] COMMAND [ARGS]"
245d0825bca7fe65beaee391d30da42e937db621564Steve Block        return HelpPrintingOptionParser(epilog_method=self.help_command._help_epilog, prog=self.name(), usage=usage)
246643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
247643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    @staticmethod
248d0825bca7fe65beaee391d30da42e937db621564Steve Block    def _split_command_name_from_args(args):
249643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        # Assume the first argument which doesn't start with "-" is the command name.
250643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        command_index = 0
251643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        for arg in args:
252643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            if arg[0] != "-":
253643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                break
254643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            command_index += 1
255643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        else:
256d0825bca7fe65beaee391d30da42e937db621564Steve Block            return (None, args[:])
257643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
258643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        command = args[command_index]
259d0825bca7fe65beaee391d30da42e937db621564Steve Block        return (command, args[:command_index] + args[command_index + 1:])
260643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
261643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def command_by_name(self, command_name):
262643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        for command in self.commands:
263643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            if command_name == command.name:
264643ca7872b450ea4efacab6188849e5aac2ba161Steve Block                return command
265643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return None
266643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
267643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def path(self):
268643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        raise NotImplementedError, "subclasses must implement"
269643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
270dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Block    def command_completed(self):
271dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Block        pass
272dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Block
273643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def should_show_in_main_help(self, command):
274643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        return command.show_in_main_help
275643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
276643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def should_execute_command(self, command):
277d0825bca7fe65beaee391d30da42e937db621564Steve Block        return True
278d0825bca7fe65beaee391d30da42e937db621564Steve Block
279d0825bca7fe65beaee391d30da42e937db621564Steve Block    def _add_global_options(self, option_parser):
280d0825bca7fe65beaee391d30da42e937db621564Steve Block        global_options = self.global_options or []
281d0825bca7fe65beaee391d30da42e937db621564Steve Block        for option in global_options:
282d0825bca7fe65beaee391d30da42e937db621564Steve Block            option_parser.add_option(option)
283d0825bca7fe65beaee391d30da42e937db621564Steve Block
284d0825bca7fe65beaee391d30da42e937db621564Steve Block    def handle_global_options(self, options):
285d0825bca7fe65beaee391d30da42e937db621564Steve Block        pass
286643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
287643ca7872b450ea4efacab6188849e5aac2ba161Steve Block    def main(self, argv=sys.argv):
288d0825bca7fe65beaee391d30da42e937db621564Steve Block        (command_name, args) = self._split_command_name_from_args(argv[1:])
289643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
290d0825bca7fe65beaee391d30da42e937db621564Steve Block        option_parser = self._create_option_parser()
291d0825bca7fe65beaee391d30da42e937db621564Steve Block        self._add_global_options(option_parser)
292643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
293643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        command = self.command_by_name(command_name) or self.help_command
294643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if not command:
295d0825bca7fe65beaee391d30da42e937db621564Steve Block            option_parser.error("%s is not a recognized command" % command_name)
296d0825bca7fe65beaee391d30da42e937db621564Steve Block
297d0825bca7fe65beaee391d30da42e937db621564Steve Block        command.set_option_parser(option_parser)
298d0825bca7fe65beaee391d30da42e937db621564Steve Block        (options, args) = command.parse_args(args)
299d0825bca7fe65beaee391d30da42e937db621564Steve Block        self.handle_global_options(options)
300643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
301643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        (should_execute, failure_reason) = self.should_execute_command(command)
302643ca7872b450ea4efacab6188849e5aac2ba161Steve Block        if not should_execute:
303643ca7872b450ea4efacab6188849e5aac2ba161Steve Block            log(failure_reason)
304d0825bca7fe65beaee391d30da42e937db621564Steve Block            return 0 # FIXME: Should this really be 0?
305643ca7872b450ea4efacab6188849e5aac2ba161Steve Block
306e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke        while True:
307e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke            try:
308e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke                result = command.check_arguments_and_execute(options, args, self)
309e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke                break
310e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke            except TryAgain, e:
311e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke                pass
312e458d70a0d18538346f41b503114c9ebe6b2ce12Leon Clarke
313dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Block        self.command_completed()
314dcc8cf2e65d1aa555cce12431a16547e66b469eeSteve Block        return result
315