Mike Frysinger | f1ba7ad | 2022-09-12 05:42:57 -0400 | [diff] [blame] | 1 | # Copyright 2012 The ChromiumOS Authors |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 5 | """Module that contains meta-logic related to CLI commands. |
| 6 | |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 7 | This module contains two important definitions used by all commands: |
Alex Klein | 975e86c | 2023-01-23 16:49:10 -0700 | [diff] [blame] | 8 | CliCommand: The parent class of all CLI commands. |
| 9 | command_decorator: Decorator that must be used to ensure that the command |
| 10 | shows up in |_commands| and is discoverable. |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 11 | |
| 12 | Commands can be either imported directly or looked up using this module's |
| 13 | ListCommands() function. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 14 | """ |
| 15 | |
Alex Klein | 665aa07 | 2019-12-12 15:13:53 -0700 | [diff] [blame] | 16 | import importlib |
Chris McDonald | 14ac61d | 2021-07-21 11:49:56 -0600 | [diff] [blame] | 17 | import logging |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 18 | import os |
Alex Klein | 3a88327 | 2021-03-19 16:02:43 -0600 | [diff] [blame] | 19 | import sys |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 20 | |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 21 | from chromite.lib import commandline |
Chris McDonald | 14ac61d | 2021-07-21 11:49:56 -0600 | [diff] [blame] | 22 | from chromite.lib import constants |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 23 | from chromite.lib import cros_build_lib |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 24 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 25 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame] | 26 | # Paths for finding and importing subcommand modules. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 27 | _SUBCOMMAND_MODULE_DIRECTORY = os.path.join(os.path.dirname(__file__), "cros") |
| 28 | _SUBCOMMAND_MODULE_PREFIX = "cros_" |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame] | 29 | |
| 30 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 31 | _commands = dict() |
| 32 | |
| 33 | |
Ralph Nathan | 6993125 | 2015-04-14 16:49:21 -0700 | [diff] [blame] | 34 | def UseProgressBar(): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 35 | """Determine whether the progress bar is to be used or not. |
Ralph Nathan | 6993125 | 2015-04-14 16:49:21 -0700 | [diff] [blame] | 36 | |
Alex Klein | 975e86c | 2023-01-23 16:49:10 -0700 | [diff] [blame] | 37 | We only want the progress bar to display for the brillo commands which |
| 38 | operate at logging level NOTICE. If the user wants to see the noisy output, |
| 39 | then they can execute the command at logging level INFO or DEBUG. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 40 | """ |
| 41 | return logging.getLogger().getEffectiveLevel() == logging.NOTICE |
Ralph Nathan | 6993125 | 2015-04-14 16:49:21 -0700 | [diff] [blame] | 42 | |
| 43 | |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 44 | def ImportCommand(name): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 45 | """Directly import the specified subcommand. |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 46 | |
Alex Klein | 975e86c | 2023-01-23 16:49:10 -0700 | [diff] [blame] | 47 | This method imports the module which must contain the single subcommand. |
| 48 | When the module is loaded, the declared command (those that use |
| 49 | command_decorator) will automatically get added to |_commands|. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 50 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 51 | Args: |
Alex Klein | 53cc3bf | 2022-10-13 08:50:01 -0600 | [diff] [blame] | 52 | name: The subcommand to load. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 53 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 54 | Returns: |
Alex Klein | 53cc3bf | 2022-10-13 08:50:01 -0600 | [diff] [blame] | 55 | A reference to the subcommand class. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 56 | """ |
| 57 | module_path = os.path.join( |
| 58 | _SUBCOMMAND_MODULE_DIRECTORY, "cros_%s" % (name.replace("-", "_"),) |
| 59 | ) |
| 60 | import_path = os.path.relpath( |
| 61 | os.path.realpath(module_path), os.path.dirname(constants.CHROMITE_DIR) |
| 62 | ) |
| 63 | module_parts = import_path.split(os.path.sep) |
| 64 | importlib.import_module(".".join(module_parts)) |
| 65 | return _commands[name] |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 66 | |
| 67 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame] | 68 | def ListCommands(): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 69 | """Return the set of available subcommands. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 70 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 71 | We assume that there is a direct one-to-one relationship between the module |
| 72 | name on disk and the command that module implements. We assume this as a |
| 73 | performance requirement (to avoid importing every subcommand every time even |
| 74 | though we'd only ever run a single one), and to avoid 3rd party module usage |
| 75 | in one subcommand breaking all other subcommands (not a great solution). |
| 76 | """ |
Alex Klein | 975e86c | 2023-01-23 16:49:10 -0700 | [diff] [blame] | 77 | # Filenames use underscores due to python naming limitations, but |
| 78 | # subcommands use dashes as they're easier for humans to type. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 79 | # Strip off the leading "cros_" and the trailing ".py". |
| 80 | return set( |
| 81 | x[5:-3].replace("_", "-") |
| 82 | for x in os.listdir(_SUBCOMMAND_MODULE_DIRECTORY) |
| 83 | if ( |
| 84 | x.startswith(_SUBCOMMAND_MODULE_PREFIX) |
| 85 | and x.endswith(".py") |
| 86 | and not x.endswith("_unittest.py") |
| 87 | ) |
| 88 | ) |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 89 | |
| 90 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 91 | class InvalidCommandError(Exception): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 92 | """Error that occurs when command class fails validity checks.""" |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 93 | |
| 94 | |
Mike Frysinger | 61cf22d | 2021-12-15 00:37:54 -0500 | [diff] [blame] | 95 | def command_decorator(name): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 96 | """Decorator to check validity and add class to list of usable commands.""" |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 97 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 98 | def inner_decorator(original_class): |
| 99 | """Inner Decorator that actually wraps the class.""" |
| 100 | if not hasattr(original_class, "__doc__"): |
| 101 | raise InvalidCommandError( |
| 102 | "All handlers must have docstrings: %s" % original_class |
| 103 | ) |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 104 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 105 | if not issubclass(original_class, CliCommand): |
| 106 | raise InvalidCommandError( |
| 107 | "All Commands must derive from CliCommand: %s" % original_class |
| 108 | ) |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 109 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 110 | _commands[name] = original_class |
| 111 | original_class.name = name |
Ryan Cui | 47f80e4 | 2013-04-01 19:01:54 -0700 | [diff] [blame] | 112 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 113 | return original_class |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 114 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 115 | return inner_decorator |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 116 | |
| 117 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 118 | class CliCommand(object): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 119 | """All CLI commands must derive from this class. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 120 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 121 | This class provides the abstract interface for all CLI commands. When |
| 122 | designing a new command, you must sub-class from this class and use the |
| 123 | command_decorator decorator. You must specify a class docstring as that will |
| 124 | be used as the usage for the sub-command. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 125 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 126 | In addition your command should implement AddParser which is passed in a |
| 127 | parser that you can add your own custom arguments. See argparse for more |
| 128 | information. |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 129 | """ |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 130 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 131 | # Indicates whether command uses cache related commandline options. |
| 132 | use_caching_options = False |
Mike Frysinger | 57a8feb | 2023-02-02 08:48:38 -0500 | [diff] [blame^] | 133 | # Whether command uses dry-run options. |
| 134 | use_dryrun_options = False |
Alex Klein | 3a88327 | 2021-03-19 16:02:43 -0600 | [diff] [blame] | 135 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 136 | def __init__(self, options): |
| 137 | self.options = options |
Alex Klein | 3a88327 | 2021-03-19 16:02:43 -0600 | [diff] [blame] | 138 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 139 | @classmethod |
| 140 | def AddParser(cls, parser): |
| 141 | """Add arguments for this command to the parser.""" |
| 142 | parser.set_defaults(command_class=cls) |
| 143 | |
| 144 | @classmethod |
| 145 | def ProcessOptions( |
| 146 | cls, |
| 147 | parser: commandline.ArgumentParser, |
| 148 | options: commandline.ArgumentNamespace, |
| 149 | ) -> None: |
| 150 | """Validate & post-process options before freezing.""" |
| 151 | |
| 152 | @classmethod |
| 153 | def AddDeviceArgument( |
| 154 | cls, parser, schemes=commandline.DEVICE_SCHEME_SSH, positional=False |
| 155 | ): |
| 156 | """Add a device argument to the parser. |
| 157 | |
| 158 | This standardizes the help message across all subcommands. |
| 159 | |
| 160 | Args: |
Alex Klein | 53cc3bf | 2022-10-13 08:50:01 -0600 | [diff] [blame] | 161 | parser: The parser to add the device argument to. |
| 162 | schemes: List of device schemes or single scheme to allow. |
| 163 | positional: Whether it should be a positional or named argument. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 164 | """ |
| 165 | help_strings = [] |
| 166 | schemes = list(cros_build_lib.iflatten_instance(schemes)) |
| 167 | if commandline.DEVICE_SCHEME_SSH in schemes: |
| 168 | help_strings.append( |
| 169 | "Target a device with [user@]hostname[:port]. " |
| 170 | "IPv4/IPv6 addresses are allowed, but IPv6 must " |
| 171 | "use brackets (e.g. [::1])." |
| 172 | ) |
| 173 | if commandline.DEVICE_SCHEME_USB in schemes: |
| 174 | help_strings.append("Target removable media with usb://[path].") |
| 175 | if commandline.DEVICE_SCHEME_SERVO in schemes: |
| 176 | help_strings.append( |
| 177 | "Target a servo by port or serial number with " |
| 178 | "servo:port[:port] or servo:serial:serial-number. " |
| 179 | "e.g. servo:port:1234 or servo:serial:C1230024192." |
| 180 | ) |
| 181 | if commandline.DEVICE_SCHEME_FILE in schemes: |
| 182 | help_strings.append("Target a local file with file://path.") |
| 183 | if positional: |
| 184 | parser.add_argument( |
| 185 | "device", |
| 186 | type=commandline.DeviceParser(schemes), |
| 187 | help=" ".join(help_strings), |
| 188 | ) |
| 189 | else: |
| 190 | parser.add_argument( |
| 191 | "-d", |
| 192 | "--device", |
| 193 | type=commandline.DeviceParser(schemes), |
| 194 | help=" ".join(help_strings), |
| 195 | ) |
| 196 | |
| 197 | def Run(self): |
| 198 | """The command to run.""" |
| 199 | raise NotImplementedError() |
| 200 | |
| 201 | def TranslateToChrootArgv(self): |
| 202 | """Hook to get the argv for reexecution inside the chroot. |
| 203 | |
| 204 | By default, return the same args used to execute it in the first place. |
Alex Klein | 975e86c | 2023-01-23 16:49:10 -0700 | [diff] [blame] | 205 | Hook allows commands to translate specific arguments, i.e. change paths |
| 206 | to chroot paths. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 207 | """ |
| 208 | return sys.argv[:] |