1# Copyright (C) 2024 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15import argparse 16import os 17import pathlib 18import sys 19from typing import Tuple, Optional 20 21_BAZEL_REL_PATH = "prebuilts/kernel-build-tools/bazel/linux-x86_64/bazel" 22 23 24def _partition(lst: list[str], index: Optional[int]) \ 25 -> Tuple[list[str], Optional[str], list[str]]: 26 """Returns the triple split by index. 27 28 That is, return a tuple: 29 (everything before index, the element at index, everything after index) 30 31 If index is None, return (the list, None, empty list) 32 """ 33 if index is None: 34 return lst[:], None, [] 35 return lst[:index], lst[index], lst[index + 1:] 36 37 38class BazelWrapper(object): 39 def __init__(self, workspace_dir: pathlib.Path, bazel_args: list[str]): 40 """Splits arguments to the bazel binary based on the functionality. 41 42 bazel [startup_options] command [command_args] -- [target_patterns] 43 ^- command_idx ^- dash_dash_idx 44 45 See https://bazel.build/reference/command-line-reference 46 47 Args: 48 workspace_dir: root of workspace. 49 bazel_args: The list of arguments the user provides through command line 50 env: existing environment 51 """ 52 53 self.workspace_dir = workspace_dir 54 55 self.bazel_path = self.workspace_dir / _BAZEL_REL_PATH 56 57 command_idx = None 58 for idx, arg in enumerate(bazel_args): 59 if not arg.startswith("-"): 60 command_idx = idx 61 break 62 63 self.startup_options, self.command, remaining_args = _partition(bazel_args, 64 command_idx) 65 66 # Split command_args into `command_args -- target_patterns` 67 dash_dash_idx = None 68 try: 69 dash_dash_idx = remaining_args.index("--") 70 except ValueError: 71 # If -- is not found, put everything in command_args. These arguments 72 # are not provided to the Bazel executable target. 73 pass 74 75 self.command_args, self.dash_dash, self.target_patterns = _partition(remaining_args, 76 dash_dash_idx) 77 78 self._parse_startup_options() 79 self._parse_command_args() 80 self._add_extra_startup_options() 81 82 def add_startup_option_to_parser(self, parser): 83 parser.add_argument( 84 "-h", "--help", action="store_true", 85 help="show this help message and exit" 86 ) 87 88 def _parse_startup_options(self): 89 """Parses the given list of startup_options. 90 91 After calling this function, the following attributes are set: 92 - absolute_user_root: A path holding bazel build output location 93 - transformed_startup_options: The transformed list of startup_options to replace 94 existing startup_options to be fed to the Bazel binary 95 """ 96 97 parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) 98 self.add_startup_option_to_parser(parser) 99 100 self.known_startup_options, self.user_startup_options = \ 101 parser.parse_known_args(self.startup_options) 102 103 self.absolute_out_dir = self.workspace_dir / "out" 104 self.absolute_user_root = \ 105 self.absolute_out_dir / "bazel/output_user_root" 106 107 if self.known_startup_options.help: 108 self.transformed_startup_options = [ 109 "--help" 110 ] 111 112 if not self.known_startup_options.help: 113 javatmp = self.absolute_out_dir / "bazel/javatmp" 114 self.transformed_startup_options = [ 115 f"--host_jvm_args=-Djava.io.tmpdir={javatmp}", 116 ] 117 118 # See _add_extra_startup_options for extra startup options 119 120 def _parse_command_args(self): 121 """Parses the given list of command_args. 122 123 After calling this function, the following attributes are set: 124 - known_args: A namespace holding options known by this Bazel wrapper script 125 - transformed_command_args: The transformed list of command_args to replace 126 existing command_args to be fed to the Bazel binary 127 - env: A dictionary containing the new environment variables for the subprocess. 128 """ 129 130 parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) 131 132 # TODO: Delete these args once build bots no longer specify them 133 parser.add_argument( 134 "--make_jobs", metavar="JOBS", type=int, default=None, 135 help="unused") 136 parser.add_argument( 137 "--make_keep_going", action="store_true", default=False, 138 help="unused") 139 parser.add_argument( 140 "--repo_manifest", metavar="<repo_root>:<manifest.xml>", 141 help="unused") 142 143 # Skip startup options (before command) and target_patterns (after --) 144 _, self.transformed_command_args = parser.parse_known_args( 145 self.command_args) 146 147 def _add_extra_startup_options(self): 148 """Adds extra startup options after command args are parsed.""" 149 150 self.transformed_startup_options += self.user_startup_options 151 152 if not self.known_startup_options.help: 153 self.transformed_startup_options.append( 154 f"--output_user_root={self.absolute_user_root}") 155 156 def _build_final_args(self) -> list[str]: 157 """Builds the final arguments for the subprocess.""" 158 # final_args: 159 # bazel [startup_options] [additional_startup_options] command [transformed_command_args] -- [target_patterns] 160 161 final_args = [self.bazel_path] + self.transformed_startup_options 162 163 if self.command is not None: 164 final_args.append(self.command) 165 final_args += self.transformed_command_args 166 if self.dash_dash is not None: 167 final_args.append(self.dash_dash) 168 final_args += self.target_patterns 169 170 return final_args 171 172 def run(self) -> int: 173 """Runs the wrapper. 174 175 Returns: 176 doesn't return""" 177 final_args = self._build_final_args() 178 179 os.execve(path=self.bazel_path, argv=final_args, env=os.environ) 180 181 182def _bazel_wrapper_main(): 183 # <workspace_dir>/bootable/libbootloader/gbl/bazel.py 184 workspace_dir = ( 185 pathlib.Path(__file__).resolve().parent.parent.parent.parent) 186 return BazelWrapper(workspace_dir=workspace_dir, 187 bazel_args=sys.argv[1:]).run() 188 189 190if __name__ == "__main__": 191 sys.exit(_bazel_wrapper_main()) 192