Prathmesh Prabhu | fd3d313 | 2020-03-20 12:09:50 -0700 | [diff] [blame] | 1 | #!/bin/sh |
| 2 | # Copyright 2019 The LUCI Authors. All rights reserved. |
| 3 | # Use of this source code is governed under the Apache License, Version 2.0 |
| 4 | # that can be found in the LICENSE file. |
| 5 | |
| 6 | # We want to run python in unbuffered mode; however shebangs on linux grab the |
| 7 | # entire rest of the shebang line as a single argument, leading to errors like: |
| 8 | # |
| 9 | # /usr/bin/env: 'python -u': No such file or directory |
| 10 | # |
| 11 | # This little shell hack is a triple-quoted noop in python, but in sh it |
| 12 | # evaluates to re-exec'ing this script in unbuffered mode. |
| 13 | # pylint: disable=pointless-string-statement |
| 14 | ''''exec python -u -- "$0" ${1+"$@"} # ''' |
| 15 | # vi: syntax=python |
| 16 | """Bootstrap script to clone and forward to the recipe engine tool. |
| 17 | |
| 18 | ******************* |
| 19 | ** DO NOT MODIFY ** |
| 20 | ******************* |
| 21 | |
| 22 | This is a copy of https://chromium.googlesource.com/infra/luci/recipes-py/+/master/recipes.py. |
| 23 | To fix bugs, fix in the googlesource repo then run the autoroller. |
| 24 | """ |
| 25 | |
| 26 | # pylint: disable=wrong-import-position |
| 27 | import argparse |
Prathmesh Prabhu | c81b4a4 | 2020-07-21 13:25:02 -0700 | [diff] [blame] | 28 | import errno |
Prathmesh Prabhu | fd3d313 | 2020-03-20 12:09:50 -0700 | [diff] [blame] | 29 | import json |
| 30 | import logging |
| 31 | import os |
| 32 | import subprocess |
| 33 | import sys |
| 34 | import urlparse |
| 35 | |
| 36 | from collections import namedtuple |
| 37 | |
| 38 | # The dependency entry for the recipe_engine in the client repo's recipes.cfg |
| 39 | # |
| 40 | # url (str) - the url to the engine repo we want to use. |
| 41 | # revision (str) - the git revision for the engine to get. |
| 42 | # branch (str) - the branch to fetch for the engine as an absolute ref (e.g. |
| 43 | # refs/heads/master) |
| 44 | EngineDep = namedtuple('EngineDep', 'url revision branch') |
| 45 | |
| 46 | |
| 47 | class MalformedRecipesCfg(Exception): |
| 48 | |
| 49 | def __init__(self, msg, path): |
| 50 | full_message = 'malformed recipes.cfg: %s: %r' % (msg, path) |
| 51 | super(MalformedRecipesCfg, self).__init__(full_message) |
| 52 | |
| 53 | |
| 54 | def parse(repo_root, recipes_cfg_path): |
| 55 | """Parse is a lightweight a recipes.cfg file parser. |
| 56 | |
| 57 | Args: |
| 58 | repo_root (str) - native path to the root of the repo we're trying to run |
| 59 | recipes for. |
| 60 | recipes_cfg_path (str) - native path to the recipes.cfg file to process. |
| 61 | |
| 62 | Returns (as tuple): |
| 63 | engine_dep (EngineDep|None): The recipe_engine dependency, or None, if the |
| 64 | current repo IS the recipe_engine. |
| 65 | recipes_path (str) - native path to where the recipes live inside of the |
| 66 | current repo (i.e. the folder containing `recipes/` and/or |
| 67 | `recipe_modules`) |
| 68 | """ |
| 69 | with open(recipes_cfg_path, 'rU') as fh: |
| 70 | pb = json.load(fh) |
| 71 | |
| 72 | try: |
| 73 | if pb['api_version'] != 2: |
| 74 | raise MalformedRecipesCfg('unknown version %d' % pb['api_version'], |
| 75 | recipes_cfg_path) |
| 76 | |
| 77 | # If we're running ./recipes.py from the recipe_engine repo itself, then |
| 78 | # return None to signal that there's no EngineDep. |
| 79 | repo_name = pb.get('repo_name') |
| 80 | if not repo_name: |
| 81 | repo_name = pb['project_id'] |
| 82 | if repo_name == 'recipe_engine': |
| 83 | return None, pb.get('recipes_path', '') |
| 84 | |
| 85 | engine = pb['deps']['recipe_engine'] |
| 86 | |
| 87 | if 'url' not in engine: |
| 88 | raise MalformedRecipesCfg( |
| 89 | 'Required field "url" in dependency "recipe_engine" not found', |
| 90 | recipes_cfg_path) |
| 91 | |
| 92 | engine.setdefault('revision', '') |
| 93 | engine.setdefault('branch', 'refs/heads/master') |
| 94 | recipes_path = pb.get('recipes_path', '') |
| 95 | |
| 96 | # TODO(iannucci): only support absolute refs |
| 97 | if not engine['branch'].startswith('refs/'): |
| 98 | engine['branch'] = 'refs/heads/' + engine['branch'] |
| 99 | |
| 100 | recipes_path = os.path.join(repo_root, |
| 101 | recipes_path.replace('/', os.path.sep)) |
| 102 | return EngineDep(**engine), recipes_path |
| 103 | except KeyError as ex: |
| 104 | raise MalformedRecipesCfg(ex.message, recipes_cfg_path) |
| 105 | |
| 106 | |
Prathmesh Prabhu | 98066ba | 2020-09-11 10:52:16 -0700 | [diff] [blame^] | 107 | IS_WIN = sys.platform.startswith(('win', 'cygwin')) |
| 108 | |
| 109 | _BAT = '.bat' if IS_WIN else '' |
Prathmesh Prabhu | fd3d313 | 2020-03-20 12:09:50 -0700 | [diff] [blame] | 110 | GIT = 'git' + _BAT |
| 111 | VPYTHON = 'vpython' + _BAT |
| 112 | CIPD = 'cipd' + _BAT |
| 113 | REQUIRED_BINARIES = {GIT, VPYTHON, CIPD} |
| 114 | |
| 115 | |
| 116 | def _is_executable(path): |
| 117 | return os.path.isfile(path) and os.access(path, os.X_OK) |
| 118 | |
| 119 | |
| 120 | # TODO: Use shutil.which once we switch to Python3. |
| 121 | def _is_on_path(basename): |
| 122 | for path in os.environ['PATH'].split(os.pathsep): |
| 123 | full_path = os.path.join(path, basename) |
| 124 | if _is_executable(full_path): |
| 125 | return True |
| 126 | return False |
| 127 | |
| 128 | |
| 129 | def _subprocess_call(argv, **kwargs): |
| 130 | logging.info('Running %r', argv) |
| 131 | return subprocess.call(argv, **kwargs) |
| 132 | |
| 133 | |
Prathmesh Prabhu | 98066ba | 2020-09-11 10:52:16 -0700 | [diff] [blame^] | 134 | |
Prathmesh Prabhu | fd3d313 | 2020-03-20 12:09:50 -0700 | [diff] [blame] | 135 | def _git_check_call(argv, **kwargs): |
| 136 | argv = [GIT] + argv |
| 137 | logging.info('Running %r', argv) |
| 138 | subprocess.check_call(argv, **kwargs) |
| 139 | |
| 140 | |
| 141 | def _git_output(argv, **kwargs): |
| 142 | argv = [GIT] + argv |
| 143 | logging.info('Running %r', argv) |
| 144 | return subprocess.check_output(argv, **kwargs) |
| 145 | |
| 146 | |
| 147 | def parse_args(argv): |
| 148 | """This extracts a subset of the arguments that this bootstrap script cares |
| 149 | about. Currently this consists of: |
| 150 | * an override for the recipe engine in the form of `-O recipe_engine=/path` |
| 151 | * the --package option. |
| 152 | """ |
| 153 | PREFIX = 'recipe_engine=' |
| 154 | |
| 155 | p = argparse.ArgumentParser(add_help=False) |
| 156 | p.add_argument('-O', '--project-override', action='append') |
| 157 | p.add_argument('--package', type=os.path.abspath) |
| 158 | args, _ = p.parse_known_args(argv) |
| 159 | for override in args.project_override or (): |
| 160 | if override.startswith(PREFIX): |
| 161 | return override[len(PREFIX):], args.package |
| 162 | return None, args.package |
| 163 | |
| 164 | |
| 165 | def checkout_engine(engine_path, repo_root, recipes_cfg_path): |
| 166 | dep, recipes_path = parse(repo_root, recipes_cfg_path) |
| 167 | if dep is None: |
| 168 | # we're running from the engine repo already! |
| 169 | return os.path.join(repo_root, recipes_path) |
| 170 | |
| 171 | url = dep.url |
| 172 | |
| 173 | if not engine_path and url.startswith('file://'): |
| 174 | engine_path = urlparse.urlparse(url).path |
| 175 | |
| 176 | if not engine_path: |
| 177 | revision = dep.revision |
| 178 | branch = dep.branch |
| 179 | |
| 180 | # Ensure that we have the recipe engine cloned. |
| 181 | engine_path = os.path.join(recipes_path, '.recipe_deps', 'recipe_engine') |
| 182 | |
| 183 | with open(os.devnull, 'w') as NUL: |
| 184 | # Note: this logic mirrors the logic in recipe_engine/fetch.py |
| 185 | _git_check_call(['init', engine_path], stdout=NUL) |
| 186 | |
| 187 | try: |
| 188 | _git_check_call(['rev-parse', '--verify', |
| 189 | '%s^{commit}' % revision], |
| 190 | cwd=engine_path, |
| 191 | stdout=NUL, |
| 192 | stderr=NUL) |
| 193 | except subprocess.CalledProcessError: |
| 194 | _git_check_call(['fetch', url, branch], |
| 195 | cwd=engine_path, |
| 196 | stdout=NUL, |
| 197 | stderr=NUL) |
| 198 | |
| 199 | try: |
| 200 | _git_check_call(['diff', '--quiet', revision], cwd=engine_path) |
| 201 | except subprocess.CalledProcessError: |
Prathmesh Prabhu | c81b4a4 | 2020-07-21 13:25:02 -0700 | [diff] [blame] | 202 | index_lock = os.path.join(engine_path, '.git', 'index.lock') |
| 203 | try: |
| 204 | os.remove(index_lock) |
| 205 | except OSError as exc: |
| 206 | if exc.errno != errno.EEXIST: |
| 207 | logging.warn('failed to remove %r, reset will fail: %s', index_lock, exc) |
Prathmesh Prabhu | fd3d313 | 2020-03-20 12:09:50 -0700 | [diff] [blame] | 208 | _git_check_call(['reset', '-q', '--hard', revision], cwd=engine_path) |
| 209 | |
| 210 | # If the engine has refactored/moved modules we need to clean all .pyc files |
| 211 | # or things will get squirrely. |
| 212 | _git_check_call(['clean', '-qxf'], cwd=engine_path) |
| 213 | |
| 214 | return engine_path |
| 215 | |
| 216 | |
| 217 | def main(): |
| 218 | for required_binary in REQUIRED_BINARIES: |
| 219 | if not _is_on_path(required_binary): |
| 220 | return 'Required binary is not found on PATH: %s' % required_binary |
| 221 | |
| 222 | if '--verbose' in sys.argv: |
| 223 | logging.getLogger().setLevel(logging.INFO) |
| 224 | |
| 225 | args = sys.argv[1:] |
| 226 | engine_override, recipes_cfg_path = parse_args(args) |
| 227 | |
| 228 | if recipes_cfg_path: |
| 229 | # calculate repo_root from recipes_cfg_path |
| 230 | repo_root = os.path.dirname( |
| 231 | os.path.dirname(os.path.dirname(recipes_cfg_path))) |
| 232 | else: |
| 233 | # find repo_root with git and calculate recipes_cfg_path |
| 234 | repo_root = ( |
| 235 | _git_output(['rev-parse', '--show-toplevel'], |
| 236 | cwd=os.path.abspath(os.path.dirname(__file__))).strip()) |
| 237 | repo_root = os.path.abspath(repo_root) |
| 238 | recipes_cfg_path = os.path.join(repo_root, 'infra', 'config', 'recipes.cfg') |
| 239 | args = ['--package', recipes_cfg_path] + args |
| 240 | |
| 241 | engine_path = checkout_engine(engine_override, repo_root, recipes_cfg_path) |
| 242 | |
Prathmesh Prabhu | 98066ba | 2020-09-11 10:52:16 -0700 | [diff] [blame^] | 243 | argv = ( |
| 244 | [VPYTHON, '-u', os.path.join(engine_path, 'recipe_engine', 'main.py')] + |
| 245 | args) |
| 246 | |
| 247 | if IS_WIN: |
| 248 | # No real 'exec' on windows; set these signals to ignore so that they |
| 249 | # propagate to our children but we still wait for the child process to quit. |
| 250 | signal.signal(signal.SIGBREAK, signal.SIG_IGN) |
| 251 | signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 252 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
| 253 | return _subprocess_call(argv) |
| 254 | else: |
| 255 | os.execvp(argv[0], argv) |
Prathmesh Prabhu | fd3d313 | 2020-03-20 12:09:50 -0700 | [diff] [blame] | 256 | |
| 257 | |
| 258 | if __name__ == '__main__': |
| 259 | sys.exit(main()) |