blob: 71777a8eed546567c378a1d6f819bc85c7943b36 [file] [log] [blame]
Doug Andersonf0c73952011-01-18 13:46:07 -08001#!/usr/bin/python
Doug Andersone91900d2011-01-26 11:37:17 -08002#
3# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
Doug Andersonf0c73952011-01-18 13:46:07 -08004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Doug Andersone91900d2011-01-26 11:37:17 -08007"""Main file for the chromite shell."""
Doug Andersonf0c73952011-01-18 13:46:07 -08008
9# Python imports
Doug Andersonf0c73952011-01-18 13:46:07 -080010import os
11import sys
Doug Andersonf0c73952011-01-18 13:46:07 -080012
13
Doug Anderson4b6d3962011-01-21 09:41:50 -080014# Local imports
Doug Andersone91900d2011-01-26 11:37:17 -080015from chromite.lib import text_menu
Doug Andersona9b10902011-02-01 17:54:31 -080016import chromite.lib.cros_build_lib as cros_lib
17from chromite.shell import utils
18from chromite.shell.subcmds import build_cmd
19from chromite.shell.subcmds import clean_cmd
20from chromite.shell.subcmds import portage_cmds
21from chromite.shell.subcmds import shell_cmd
22from chromite.shell.subcmds import workon_cmd
Doug Andersonf0c73952011-01-18 13:46:07 -080023
24
Doug Andersona9b10902011-02-01 17:54:31 -080025# Define command handlers and command strings.
Doug Andersonf0c73952011-01-18 13:46:07 -080026#
27# ORDER MATTERS here when we show the menu.
Doug Andersonf0c73952011-01-18 13:46:07 -080028_COMMAND_HANDLERS = [
Doug Andersona9b10902011-02-01 17:54:31 -080029 build_cmd.BuildCmd,
30 clean_cmd.CleanCmd,
31 portage_cmds.EbuildCmd,
32 portage_cmds.EmergeCmd,
33 portage_cmds.EqueryCmd,
34 portage_cmds.PortageqCmd,
35 shell_cmd.ShellCmd,
36 workon_cmd.WorkonCmd,
Doug Andersonf0c73952011-01-18 13:46:07 -080037]
Doug Andersona9b10902011-02-01 17:54:31 -080038_COMMAND_STRS = [cls.__name__[:-len('Cmd')].lower()
39 for cls in _COMMAND_HANDLERS]
Doug Andersonf0c73952011-01-18 13:46:07 -080040
41
42def _FindCommand(cmd_name):
43 """Find the command that matches the given command name.
44
45 This tries to be smart. See the cmd_name parameter for details.
46
47 Args:
48 cmd_name: Can be any of the following:
49 1. The full name of a command. This is checked first so that if one
50 command name is a substring of another, you can still specify
51 the shorter spec name and know you won't get a menu (the exact
52 match prevents the menu).
53 2. A _prefix_ that will be used to pare-down a menu of commands
54 Can be the empty string to show a menu of all commands
55
56 Returns:
57 The command name.
58 """
59 # Always make cmd_name lower. Commands are case-insensitive.
60 cmd_name = cmd_name.lower()
61
62 # If we're an exact match, we're done!
63 if cmd_name in _COMMAND_STRS:
64 return cmd_name
65
66 # Find ones that match and put them in a menu...
67 possible_cmds = []
68 possible_choices = []
69 for cmd_num, this_cmd in enumerate(_COMMAND_STRS):
70 if this_cmd.startswith(cmd_name):
Doug Andersona9b10902011-02-01 17:54:31 -080071 handler = _COMMAND_HANDLERS[cmd_num]
Doug Andersonf0c73952011-01-18 13:46:07 -080072 assert hasattr(handler, '__doc__'), \
73 ('All handlers must have docstrings: %s' % cmd_name)
74 desc = handler.__doc__.splitlines()[0]
75
76 possible_cmds.append(this_cmd)
77 possible_choices.append('%s - %s' % (this_cmd, desc))
78
79 if not possible_choices:
Doug Andersona9b10902011-02-01 17:54:31 -080080 cros_lib.Die('No commands matched: "%s". '
Doug Andersonf0c73952011-01-18 13:46:07 -080081 'Try running with no arguments for a menu.' %
82 cmd_name)
83
84 if cmd_name and len(possible_choices) == 1:
85 # Avoid showing the user a menu if the user's search string matched exactly
86 # one item.
87 choice = 0
Doug Andersona9b10902011-02-01 17:54:31 -080088 cros_lib.Info("Running command '%s'." % possible_cmds[choice])
Doug Andersonf0c73952011-01-18 13:46:07 -080089 else:
90 choice = text_menu.TextMenu(possible_choices, 'Which chromite command',
91 menu_width=0)
92
93 if choice is None:
Doug Andersona9b10902011-02-01 17:54:31 -080094 cros_lib.Die('OK, cancelling...')
Doug Andersonf0c73952011-01-18 13:46:07 -080095 else:
96 return possible_cmds[choice]
97
98
Doug Andersonf0c73952011-01-18 13:46:07 -080099def main():
Doug Andersona9b10902011-02-01 17:54:31 -0800100 """Main function for the chromite shell."""
101
102 # Hack it so that argv[0] is 'chromite' so that it doesn't tell user to run
103 # 'main.py' in help commands...
104 # TODO(dianders): Remove this hack, since it is ugly. Shouldn't be needed
105 # once we change the way that the chromite wrapper works.
106 sys.argv[0] = 'chromite'
107
108 # Support EnterChroot().
109 did_resume = utils.ResumeEnterChrootIfNeeded(sys.argv)
110 if did_resume:
111 return
112
Doug Andersonf0c73952011-01-18 13:46:07 -0800113 # TODO(dianders): Make help a little better. Specifically:
114 # 1. Add a command called 'help'
115 # 2. Make the help string below include command list and descriptions (like
116 # the menu, but without being interactive).
117 # 3. Make "help command" and "--help command" equivalent to "command --help".
118 help_str = (
119 """Usage: %(prog)s [chromite_options] [cmd [args]]\n"""
120 """\n"""
121 """The chromite script is a wrapper to make it easy to do various\n"""
122 """build tasks. For a list of commands, run without any arguments.\n"""
123 """\n"""
124 """Options:\n"""
125 """ -h, --help show this help message and exit\n"""
126 ) % {'prog': os.path.basename(sys.argv[0])}
Doug Andersona9b10902011-02-01 17:54:31 -0800127 if not cros_lib.IsInsideChroot():
Doug Andersonf0c73952011-01-18 13:46:07 -0800128 help_str += (
129 """ --chroot=CHROOT_NAME Chroot spec to use. Can be an absolute\n"""
130 """ path to a spec file or a substring of a\n"""
131 """ chroot spec name (without .spec suffix)\n"""
132 )
133
134 # We don't use OptionParser here, since options for different subcommands are
135 # so different. We just look for the chromite options here...
136 if sys.argv[1:2] == ['--help']:
137 print help_str
138 sys.exit(0)
Doug Andersonf0c73952011-01-18 13:46:07 -0800139 else:
140 # Start by skipping argv[0]
141 argv = sys.argv[1:]
142
143 # Look for special "--chroot" argument to allow for alternate chroots
Doug Andersona9b10902011-02-01 17:54:31 -0800144 if not cros_lib.IsInsideChroot():
Doug Andersonf0c73952011-01-18 13:46:07 -0800145 # Default chroot name...
146 chroot_name = 'chroot'
147
148 # Get chroot spec name if specified; trim argv down if needed...
149 if argv:
150 if argv[0].startswith('--chroot='):
151 _, chroot_name = argv[0].split('=', 2)
152 argv = argv[1:]
153 elif argv[0] == '--chroot':
154 if len(argv) < 2:
Doug Andersona9b10902011-02-01 17:54:31 -0800155 cros_lib.Die('Chroot not specified.')
Doug Andersonf0c73952011-01-18 13:46:07 -0800156
157 chroot_name = argv[1]
158 argv = argv[2:]
159
Doug Andersona9b10902011-02-01 17:54:31 -0800160 chroot_spec_path = utils.FindSpec(chroot_name,
161 spec_type=utils.CHROOT_SPEC_TYPE)
Doug Andersonf0c73952011-01-18 13:46:07 -0800162
Doug Andersona9b10902011-02-01 17:54:31 -0800163 cros_lib.Info('Using chroot "%s"' % os.path.relpath(chroot_spec_path))
Doug Andersonf0c73952011-01-18 13:46:07 -0800164
Doug Andersona9b10902011-02-01 17:54:31 -0800165 chroot_config = utils.ReadConfig(chroot_spec_path)
Doug Andersonf0c73952011-01-18 13:46:07 -0800166 else:
167 # Already in the chroot; no need to get config...
168 chroot_config = None
169
170 # Get command and arguments
171 if argv:
Doug Anderson4b6d3962011-01-21 09:41:50 -0800172 cmd_str = argv[0].lower()
Doug Andersonf0c73952011-01-18 13:46:07 -0800173 argv = argv[1:]
174 else:
Doug Anderson4b6d3962011-01-21 09:41:50 -0800175 cmd_str = ''
Doug Andersonf0c73952011-01-18 13:46:07 -0800176
Doug Andersone91900d2011-01-26 11:37:17 -0800177 # Validate the subcmd, popping a menu if needed.
Doug Anderson4b6d3962011-01-21 09:41:50 -0800178 cmd_str = _FindCommand(cmd_str)
Doug Andersonf0c73952011-01-18 13:46:07 -0800179
180 # Finally, call the function w/ standard argv.
Doug Andersona9b10902011-02-01 17:54:31 -0800181 cmd_cls = _COMMAND_HANDLERS[_COMMAND_STRS.index(cmd_str)]
Doug Anderson4b6d3962011-01-21 09:41:50 -0800182 cmd_obj = cmd_cls()
183 cmd_obj.Run([cmd_str] + argv, chroot_config=chroot_config)
Doug Andersonf0c73952011-01-18 13:46:07 -0800184
185
186if __name__ == '__main__':
187 main()