blob: 4e37b9cf8e45d78fa05f19811ea8c14720029a16 [file] [log] [blame]
recipe-rollerf8a03292019-05-17 13:55:55 -07001#!/bin/sh
recipe-roller18f0e712019-05-17 15:36:20 -07002# 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
recipe-rollerf8a03292019-05-17 13:55:55 -07006# 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.
recipe-roller18f0e712019-05-17 15:36:20 -070013# pylint: disable=pointless-string-statement
recipe-rollerf8a03292019-05-17 13:55:55 -070014''''exec python -u -- "$0" ${1+"$@"} # '''
15# vi: syntax=python
Lann Martin079e5aa2018-10-29 12:24:54 -060016"""Bootstrap script to clone and forward to the recipe engine tool.
17
18*******************
19** DO NOT MODIFY **
20*******************
21
Yaakov Shaul3114e172019-02-05 21:45:16 -070022This is a copy of https://chromium.googlesource.com/infra/luci/recipes-py/+/master/recipes.py.
Lann Martin079e5aa2018-10-29 12:24:54 -060023To fix bugs, fix in the googlesource repo then run the autoroller.
24"""
25
recipe-rollerf8a03292019-05-17 13:55:55 -070026# pylint: disable=wrong-import-position
Lann Martin079e5aa2018-10-29 12:24:54 -060027import argparse
Prathmesh Prabhu9bc353d2020-07-21 15:35:55 -070028import errno
Lann Martin079e5aa2018-10-29 12:24:54 -060029import json
30import logging
31import os
Lann Martin079e5aa2018-10-29 12:24:54 -060032import subprocess
33import sys
Lann Martin079e5aa2018-10-29 12:24:54 -060034import urlparse
35
36from collections import namedtuple
37
Lann Martin079e5aa2018-10-29 12:24:54 -060038# 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.
Lann Martin079e5aa2018-10-29 12:24:54 -060042# branch (str) - the branch to fetch for the engine as an absolute ref (e.g.
43# refs/heads/master)
recipe-roller7107df22019-05-22 16:47:18 -070044EngineDep = namedtuple('EngineDep', 'url revision branch')
Lann Martin079e5aa2018-10-29 12:24:54 -060045
46
47class MalformedRecipesCfg(Exception):
recipe-roller7107df22019-05-22 16:47:18 -070048
Lann Martin079e5aa2018-10-29 12:24:54 -060049 def __init__(self, msg, path):
recipe-roller7107df22019-05-22 16:47:18 -070050 full_message = 'malformed recipes.cfg: %s: %r' % (msg, path)
51 super(MalformedRecipesCfg, self).__init__(full_message)
Lann Martin079e5aa2018-10-29 12:24:54 -060052
53
54def 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
Yaakov Shaul3114e172019-02-05 21:45:16 -070077 # If we're running ./recipes.py from the recipe_engine repo itself, then
Lann Martin079e5aa2018-10-29 12:24:54 -060078 # return None to signal that there's no EngineDep.
Lann Martinee0b13d2019-03-05 12:52:28 -070079 repo_name = pb.get('repo_name')
80 if not repo_name:
81 repo_name = pb['project_id']
82 if repo_name == 'recipe_engine':
Lann Martin079e5aa2018-10-29 12:24:54 -060083 return None, pb.get('recipes_path', '')
84
85 engine = pb['deps']['recipe_engine']
86
87 if 'url' not in engine:
88 raise MalformedRecipesCfg(
recipe-roller7107df22019-05-22 16:47:18 -070089 'Required field "url" in dependency "recipe_engine" not found',
90 recipes_cfg_path)
Lann Martin079e5aa2018-10-29 12:24:54 -060091
92 engine.setdefault('revision', '')
Lann Martin079e5aa2018-10-29 12:24:54 -060093 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
recipe-roller7107df22019-05-22 16:47:18 -0700100 recipes_path = os.path.join(repo_root,
101 recipes_path.replace('/', os.path.sep))
Lann Martin079e5aa2018-10-29 12:24:54 -0600102 return EngineDep(**engine), recipes_path
103 except KeyError as ex:
104 raise MalformedRecipesCfg(ex.message, recipes_cfg_path)
105
106
recipe-roller4202bc62020-09-17 17:38:22 -0700107IS_WIN = sys.platform.startswith(('win', 'cygwin'))
108
109_BAT = '.bat' if IS_WIN else ''
Lann Martin079e5aa2018-10-29 12:24:54 -0600110GIT = 'git' + _BAT
111VPYTHON = 'vpython' + _BAT
recipe-rollera2fcee52019-04-09 08:22:38 -0700112CIPD = 'cipd' + _BAT
113REQUIRED_BINARIES = {GIT, VPYTHON, CIPD}
114
115
116def _is_executable(path):
117 return os.path.isfile(path) and os.access(path, os.X_OK)
118
recipe-roller7107df22019-05-22 16:47:18 -0700119
recipe-rollera2fcee52019-04-09 08:22:38 -0700120# TODO: Use shutil.which once we switch to Python3.
121def _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
Lann Martin079e5aa2018-10-29 12:24:54 -0600127
128
129def _subprocess_call(argv, **kwargs):
130 logging.info('Running %r', argv)
131 return subprocess.call(argv, **kwargs)
132
133
recipe-roller4202bc62020-09-17 17:38:22 -0700134
Lann Martin079e5aa2018-10-29 12:24:54 -0600135def _git_check_call(argv, **kwargs):
recipe-roller7107df22019-05-22 16:47:18 -0700136 argv = [GIT] + argv
Lann Martin079e5aa2018-10-29 12:24:54 -0600137 logging.info('Running %r', argv)
138 subprocess.check_call(argv, **kwargs)
139
140
141def _git_output(argv, **kwargs):
recipe-roller7107df22019-05-22 16:47:18 -0700142 argv = [GIT] + argv
Lann Martin079e5aa2018-10-29 12:24:54 -0600143 logging.info('Running %r', argv)
144 return subprocess.check_output(argv, **kwargs)
145
146
147def parse_args(argv):
148 """This extracts a subset of the arguments that this bootstrap script cares
149 about. Currently this consists of:
Yaakov Shaul3114e172019-02-05 21:45:16 -0700150 * an override for the recipe engine in the form of `-O recipe_engine=/path`
Lann Martin079e5aa2018-10-29 12:24:54 -0600151 * 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
165def 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
Lann Martin079e5aa2018-10-29 12:24:54 -0600178 branch = dep.branch
179
180 # Ensure that we have the recipe engine cloned.
Yaakov Shaul3114e172019-02-05 21:45:16 -0700181 engine_path = os.path.join(recipes_path, '.recipe_deps', 'recipe_engine')
Lann Martin079e5aa2018-10-29 12:24:54 -0600182
183 with open(os.devnull, 'w') as NUL:
184 # Note: this logic mirrors the logic in recipe_engine/fetch.py
Yaakov Shaul3114e172019-02-05 21:45:16 -0700185 _git_check_call(['init', engine_path], stdout=NUL)
Lann Martin079e5aa2018-10-29 12:24:54 -0600186
187 try:
recipe-roller7107df22019-05-22 16:47:18 -0700188 _git_check_call(['rev-parse', '--verify',
189 '%s^{commit}' % revision],
190 cwd=engine_path,
191 stdout=NUL,
192 stderr=NUL)
Lann Martin079e5aa2018-10-29 12:24:54 -0600193 except subprocess.CalledProcessError:
recipe-roller7107df22019-05-22 16:47:18 -0700194 _git_check_call(['fetch', url, branch],
195 cwd=engine_path,
196 stdout=NUL,
Lann Martin079e5aa2018-10-29 12:24:54 -0600197 stderr=NUL)
198
199 try:
Yaakov Shaul3114e172019-02-05 21:45:16 -0700200 _git_check_call(['diff', '--quiet', revision], cwd=engine_path)
Lann Martin079e5aa2018-10-29 12:24:54 -0600201 except subprocess.CalledProcessError:
Prathmesh Prabhu9bc353d2020-07-21 15:35:55 -0700202 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:
recipe-roller36078882020-09-09 16:08:01 -0700207 logging.warn('failed to remove %r, reset will fail: %s', index_lock, exc)
Yaakov Shaul3114e172019-02-05 21:45:16 -0700208 _git_check_call(['reset', '-q', '--hard', revision], cwd=engine_path)
Lann Martin079e5aa2018-10-29 12:24:54 -0600209
recipe-roller149c1572019-03-28 15:53:36 -0700210 # 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
Lann Martin079e5aa2018-10-29 12:24:54 -0600214 return engine_path
215
216
217def main():
recipe-rollera2fcee52019-04-09 08:22:38 -0700218 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
Lann Martin079e5aa2018-10-29 12:24:54 -0600222 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(
recipe-roller7107df22019-05-22 16:47:18 -0700231 os.path.dirname(os.path.dirname(recipes_cfg_path)))
Lann Martin079e5aa2018-10-29 12:24:54 -0600232 else:
233 # find repo_root with git and calculate recipes_cfg_path
recipe-roller7107df22019-05-22 16:47:18 -0700234 repo_root = (
235 _git_output(['rev-parse', '--show-toplevel'],
236 cwd=os.path.abspath(os.path.dirname(__file__))).strip())
Lann Martin079e5aa2018-10-29 12:24:54 -0600237 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
recipe-roller4202bc62020-09-17 17:38:22 -0700243 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)
Lann Martin079e5aa2018-10-29 12:24:54 -0600256
recipe-roller978cd712020-03-30 12:16:42 -0700257
Lann Martin079e5aa2018-10-29 12:24:54 -0600258if __name__ == '__main__':
259 sys.exit(main())