blob: c847e9df2eb700192777befce68dc526347c6474 [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
Simon Glassf4616ab2011-03-30 13:19:16 -070010import optparse
Doug Andersonf0c73952011-01-18 13:46:07 -080011import os
12import sys
Doug Andersonf0c73952011-01-18 13:46:07 -080013
14
Doug Anderson4b6d3962011-01-21 09:41:50 -080015# Local imports
Doug Andersone91900d2011-01-26 11:37:17 -080016from chromite.lib import text_menu
Doug Andersona9b10902011-02-01 17:54:31 -080017import chromite.lib.cros_build_lib as cros_lib
18from chromite.shell import utils
19from chromite.shell.subcmds import build_cmd
20from chromite.shell.subcmds import clean_cmd
Doug Andersona9b10902011-02-01 17:54:31 -080021from chromite.shell.subcmds import shell_cmd
22from chromite.shell.subcmds import workon_cmd
Simon Glass21599602011-02-11 13:57:29 -080023from chromite.shell import chromite_env
24from chromite.lib import operation
Doug Andersonf0c73952011-01-18 13:46:07 -080025
26
Doug Andersona9b10902011-02-01 17:54:31 -080027# Define command handlers and command strings.
Doug Andersonf0c73952011-01-18 13:46:07 -080028#
29# ORDER MATTERS here when we show the menu.
Doug Andersonf0c73952011-01-18 13:46:07 -080030_COMMAND_HANDLERS = [
Doug Andersona9b10902011-02-01 17:54:31 -080031 build_cmd.BuildCmd,
32 clean_cmd.CleanCmd,
Doug Andersona9b10902011-02-01 17:54:31 -080033 shell_cmd.ShellCmd,
34 workon_cmd.WorkonCmd,
Doug Andersonf0c73952011-01-18 13:46:07 -080035]
Doug Andersona9b10902011-02-01 17:54:31 -080036_COMMAND_STRS = [cls.__name__[:-len('Cmd')].lower()
37 for cls in _COMMAND_HANDLERS]
Doug Andersonf0c73952011-01-18 13:46:07 -080038
39
40def _FindCommand(cmd_name):
41 """Find the command that matches the given command name.
42
43 This tries to be smart. See the cmd_name parameter for details.
44
45 Args:
46 cmd_name: Can be any of the following:
47 1. The full name of a command. This is checked first so that if one
48 command name is a substring of another, you can still specify
49 the shorter spec name and know you won't get a menu (the exact
50 match prevents the menu).
51 2. A _prefix_ that will be used to pare-down a menu of commands
52 Can be the empty string to show a menu of all commands
53
54 Returns:
55 The command name.
56 """
57 # Always make cmd_name lower. Commands are case-insensitive.
58 cmd_name = cmd_name.lower()
59
60 # If we're an exact match, we're done!
61 if cmd_name in _COMMAND_STRS:
62 return cmd_name
63
64 # Find ones that match and put them in a menu...
65 possible_cmds = []
66 possible_choices = []
67 for cmd_num, this_cmd in enumerate(_COMMAND_STRS):
68 if this_cmd.startswith(cmd_name):
Doug Andersona9b10902011-02-01 17:54:31 -080069 handler = _COMMAND_HANDLERS[cmd_num]
Doug Andersonf0c73952011-01-18 13:46:07 -080070 assert hasattr(handler, '__doc__'), \
71 ('All handlers must have docstrings: %s' % cmd_name)
72 desc = handler.__doc__.splitlines()[0]
73
74 possible_cmds.append(this_cmd)
75 possible_choices.append('%s - %s' % (this_cmd, desc))
76
77 if not possible_choices:
Doug Andersona9b10902011-02-01 17:54:31 -080078 cros_lib.Die('No commands matched: "%s". '
Doug Andersonf0c73952011-01-18 13:46:07 -080079 'Try running with no arguments for a menu.' %
80 cmd_name)
81
82 if cmd_name and len(possible_choices) == 1:
83 # Avoid showing the user a menu if the user's search string matched exactly
84 # one item.
85 choice = 0
Doug Andersonf0c73952011-01-18 13:46:07 -080086 else:
87 choice = text_menu.TextMenu(possible_choices, 'Which chromite command',
88 menu_width=0)
89
90 if choice is None:
Doug Andersona9b10902011-02-01 17:54:31 -080091 cros_lib.Die('OK, cancelling...')
Doug Andersonf0c73952011-01-18 13:46:07 -080092 else:
93 return possible_cmds[choice]
94
95
Doug Andersonf0c73952011-01-18 13:46:07 -080096def main():
Doug Andersona9b10902011-02-01 17:54:31 -080097 """Main function for the chromite shell."""
98
99 # Hack it so that argv[0] is 'chromite' so that it doesn't tell user to run
100 # 'main.py' in help commands...
101 # TODO(dianders): Remove this hack, since it is ugly. Shouldn't be needed
102 # once we change the way that the chromite wrapper works.
103 sys.argv[0] = 'chromite'
104
105 # Support EnterChroot().
Simon Glass5329b932011-03-14 16:49:04 -0700106 # This may raise a ChromiteError if the child dies, so we must handle this.
107 try:
108 did_resume = utils.ResumeEnterChrootIfNeeded(sys.argv)
109 if did_resume:
110 return
111 except chromite_env.ChromiteError:
112 # The error has been reported, but we must exit indicating failure
113 sys.exit(1)
Doug Andersona9b10902011-02-01 17:54:31 -0800114
Doug Andersonf0c73952011-01-18 13:46:07 -0800115 # TODO(dianders): Make help a little better. Specifically:
116 # 1. Add a command called 'help'
117 # 2. Make the help string below include command list and descriptions (like
118 # the menu, but without being interactive).
119 # 3. Make "help command" and "--help command" equivalent to "command --help".
120 help_str = (
Simon Glassf4616ab2011-03-30 13:19:16 -0700121 """%(prog)s [chromite_options] [cmd [args]]\n"""
Doug Andersonf0c73952011-01-18 13:46:07 -0800122 """\n"""
123 """The chromite script is a wrapper to make it easy to do various\n"""
Simon Glassf4616ab2011-03-30 13:19:16 -0700124 """build tasks. For a list of commands, run without any arguments."""
Doug Andersonf0c73952011-01-18 13:46:07 -0800125 ) % {'prog': os.path.basename(sys.argv[0])}
Simon Glassf4616ab2011-03-30 13:19:16 -0700126
127 parser = optparse.OptionParser()
128
129 # Verbose defaults to full for now, just to keep people acclimatized to
130 # vast amounts of comforting output.
131 parser.add_option('-v', dest='verbose', default=3,
132 help='Control verbosity: 0=silent, 1=progress, 3=full')
133 parser.add_option('-q', action='store_const', dest='verbose', const=0,
134 help='Be quieter (sets verbosity to 1)')
Doug Andersona9b10902011-02-01 17:54:31 -0800135 if not cros_lib.IsInsideChroot():
Simon Glassf4616ab2011-03-30 13:19:16 -0700136 parser.add_option('--chroot', action='store', type='string',
137 dest='chroot_name', default='chroot',
138 help="Chroot spec to use. Can be an absolute path to a spec file "
139 "or a substring of a chroot spec name (without .spec suffix)")
140 parser.usage = help_str
141 try:
142 (options, args) = parser.parse_args()
143 except:
144 sys.exit(1)
Doug Andersonf0c73952011-01-18 13:46:07 -0800145
Simon Glasseea2a2b2011-03-30 13:36:15 -0700146 # Set up the cros system.
147 cros_env = chromite_env.ChromiteEnv()
148
149 # Configure the operation setup.
150 oper = cros_env.GetOperation()
151 oper.verbose = options.verbose >= 3
152 oper.progress = options.verbose >= 1
153
154 # Look for special "--chroot" argument to allow for alternate chroots
155 if not cros_lib.IsInsideChroot():
156 chroot_spec_path = utils.FindSpec(options.chroot_name,
157 spec_type=utils.CHROOT_SPEC_TYPE)
158
159 oper.Info('Using chroot "%s"' % os.path.relpath(chroot_spec_path))
160
161 chroot_config = utils.ReadConfig(chroot_spec_path)
Doug Andersonf0c73952011-01-18 13:46:07 -0800162 else:
Simon Glasseea2a2b2011-03-30 13:36:15 -0700163 # Already in the chroot; no need to get config...
164 chroot_config = None
Simon Glass5329b932011-03-14 16:49:04 -0700165
Simon Glasseea2a2b2011-03-30 13:36:15 -0700166 # Get command and arguments
167 if args:
168 cmd_str = args[0].lower()
169 args = args[1:]
170 else:
171 cmd_str = ''
Simon Glass5329b932011-03-14 16:49:04 -0700172
Simon Glasseea2a2b2011-03-30 13:36:15 -0700173 # Validate the subcmd, popping a menu if needed.
174 cmd_str = _FindCommand(cmd_str)
175 oper.Info("Running command '%s'." % cmd_str)
Doug Andersonf0c73952011-01-18 13:46:07 -0800176
Simon Glasseea2a2b2011-03-30 13:36:15 -0700177 # Finally, call the function w/ standard argv.
178 cmd_cls = _COMMAND_HANDLERS[_COMMAND_STRS.index(cmd_str)]
179 cmd_obj = cmd_cls()
180 cmd_obj.SetChromiteEnv(cros_env)
181 try:
182 cmd_obj.Run([cmd_str] + args, chroot_config=chroot_config)
Doug Andersonf0c73952011-01-18 13:46:07 -0800183
Simon Glasseea2a2b2011-03-30 13:36:15 -0700184 # Handle an error in one of the scripts: print a message and exit.
185 except chromite_env.ChromiteError, msg:
186 sys.exit(1)
Doug Andersonf0c73952011-01-18 13:46:07 -0800187
188if __name__ == '__main__':
189 main()