blob: c6b37aea1abb863c4d859b49f3f203011c95a4c8 [file] [log] [blame]
recipe-roller955ddaf2019-05-20 13:03:55 -07001#!/bin/sh
2# Copyright 2019 The LUCI Authors. All rights reserved.
borenet1ed2ae42016-07-26 11:52:17 -07003# Use of this source code is governed under the Apache License, Version 2.0
4# that can be found in the LICENSE file.
Eric Borenf171e162016-11-14 12:18:34 -05005
recipe-roller955ddaf2019-05-20 13:03: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.
13# pylint: disable=pointless-string-statement
14''''exec python -u -- "$0" ${1+"$@"} # '''
15# vi: syntax=python
borenet1ed2ae42016-07-26 11:52:17 -070016"""Bootstrap script to clone and forward to the recipe engine tool.
Eric Borenf171e162016-11-14 12:18:34 -050017
Robert Iannucci3734c7d2017-05-09 11:06:48 -070018*******************
19** DO NOT MODIFY **
20*******************
Eric Borenf171e162016-11-14 12:18:34 -050021
Robert Iannuccie1c23542018-12-07 17:42:12 -080022This is a copy of https://chromium.googlesource.com/infra/luci/recipes-py/+/master/recipes.py.
Eric Boren8e0c2c92017-09-27 13:03:35 -040023To fix bugs, fix in the googlesource repo then run the autoroller.
borenet1ed2ae42016-07-26 11:52:17 -070024"""
borenet1ed2ae42016-07-26 11:52:17 -070025
recipe-roller955ddaf2019-05-20 13:03:55 -070026# pylint: disable=wrong-import-position
Robert Iannuccie8b50852017-03-15 01:24:56 -070027import argparse
Robert Iannucci2ba659e2017-03-15 18:04:05 -070028import json
borenet1ed2ae42016-07-26 11:52:17 -070029import logging
recipe-roller42e16b02017-05-11 04:27:01 -070030import os
borenet1ed2ae42016-07-26 11:52:17 -070031import subprocess
32import sys
Robert Iannucci342977c2017-03-24 17:45:40 -070033import urlparse
Eric Borenf171e162016-11-14 12:18:34 -050034
Robert Iannucci3734c7d2017-05-09 11:06:48 -070035from collections import namedtuple
36
Robert Iannucci3734c7d2017-05-09 11:06:48 -070037# The dependency entry for the recipe_engine in the client repo's recipes.cfg
38#
39# url (str) - the url to the engine repo we want to use.
40# revision (str) - the git revision for the engine to get.
Robert Iannucci3734c7d2017-05-09 11:06:48 -070041# branch (str) - the branch to fetch for the engine as an absolute ref (e.g.
42# refs/heads/master)
recipe-roller0cfdf7f2019-05-22 10:16:16 -070043EngineDep = namedtuple('EngineDep', 'url revision branch')
Robert Iannucci3734c7d2017-05-09 11:06:48 -070044
45
46class MalformedRecipesCfg(Exception):
recipe-roller0cfdf7f2019-05-22 10:16:16 -070047
Robert Iannucci3734c7d2017-05-09 11:06:48 -070048 def __init__(self, msg, path):
recipe-roller0cfdf7f2019-05-22 10:16:16 -070049 full_message = 'malformed recipes.cfg: %s: %r' % (msg, path)
50 super(MalformedRecipesCfg, self).__init__(full_message)
Robert Iannucci3734c7d2017-05-09 11:06:48 -070051
Robert Iannucci2ba659e2017-03-15 18:04:05 -070052
53def parse(repo_root, recipes_cfg_path):
Robert Iannucci3734c7d2017-05-09 11:06:48 -070054 """Parse is a lightweight a recipes.cfg file parser.
Robert Iannucci2ba659e2017-03-15 18:04:05 -070055
56 Args:
57 repo_root (str) - native path to the root of the repo we're trying to run
58 recipes for.
59 recipes_cfg_path (str) - native path to the recipes.cfg file to process.
60
61 Returns (as tuple):
Eric Boren8e0c2c92017-09-27 13:03:35 -040062 engine_dep (EngineDep|None): The recipe_engine dependency, or None, if the
63 current repo IS the recipe_engine.
Robert Iannucci2ba659e2017-03-15 18:04:05 -070064 recipes_path (str) - native path to where the recipes live inside of the
65 current repo (i.e. the folder containing `recipes/` and/or
66 `recipe_modules`)
67 """
68 with open(recipes_cfg_path, 'rU') as fh:
Robert Iannucci654dfee2017-03-27 20:52:15 -070069 pb = json.load(fh)
Robert Iannucci2ba659e2017-03-15 18:04:05 -070070
Robert Iannucci3734c7d2017-05-09 11:06:48 -070071 try:
72 if pb['api_version'] != 2:
73 raise MalformedRecipesCfg('unknown version %d' % pb['api_version'],
74 recipes_cfg_path)
Robert Iannucci2ba659e2017-03-15 18:04:05 -070075
Robert Iannuccie1c23542018-12-07 17:42:12 -080076 # If we're running ./recipes.py from the recipe_engine repo itself, then
Eric Boren8e0c2c92017-09-27 13:03:35 -040077 # return None to signal that there's no EngineDep.
Robert Iannuccif4d4b872019-02-16 14:10:41 -080078 repo_name = pb.get('repo_name')
79 if not repo_name:
80 repo_name = pb['project_id']
81 if repo_name == 'recipe_engine':
Eric Boren8e0c2c92017-09-27 13:03:35 -040082 return None, pb.get('recipes_path', '')
83
Robert Iannucci3734c7d2017-05-09 11:06:48 -070084 engine = pb['deps']['recipe_engine']
85
86 if 'url' not in engine:
87 raise MalformedRecipesCfg(
recipe-roller0cfdf7f2019-05-22 10:16:16 -070088 'Required field "url" in dependency "recipe_engine" not found',
89 recipes_cfg_path)
Robert Iannucci3734c7d2017-05-09 11:06:48 -070090
91 engine.setdefault('revision', '')
Robert Iannucci3734c7d2017-05-09 11:06:48 -070092 engine.setdefault('branch', 'refs/heads/master')
93 recipes_path = pb.get('recipes_path', '')
94
95 # TODO(iannucci): only support absolute refs
96 if not engine['branch'].startswith('refs/'):
97 engine['branch'] = 'refs/heads/' + engine['branch']
98
recipe-roller0cfdf7f2019-05-22 10:16:16 -070099 recipes_path = os.path.join(repo_root,
100 recipes_path.replace('/', os.path.sep))
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700101 return EngineDep(**engine), recipes_path
102 except KeyError as ex:
103 raise MalformedRecipesCfg(ex.message, recipes_cfg_path)
104
105
recipe-roller198498b2018-06-22 07:38:45 -0700106_BAT = '.bat' if sys.platform.startswith(('win', 'cygwin')) else ''
107GIT = 'git' + _BAT
108VPYTHON = 'vpython' + _BAT
recipe-roller11078c652019-04-05 11:34:44 -0700109CIPD = 'cipd' + _BAT
110REQUIRED_BINARIES = {GIT, VPYTHON, CIPD}
111
112
113def _is_executable(path):
114 return os.path.isfile(path) and os.access(path, os.X_OK)
115
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700116
recipe-roller11078c652019-04-05 11:34:44 -0700117# TODO: Use shutil.which once we switch to Python3.
118def _is_on_path(basename):
119 for path in os.environ['PATH'].split(os.pathsep):
120 full_path = os.path.join(path, basename)
121 if _is_executable(full_path):
122 return True
123 return False
Robert Iannucci2ba659e2017-03-15 18:04:05 -0700124
125
borenet1ed2ae42016-07-26 11:52:17 -0700126def _subprocess_call(argv, **kwargs):
127 logging.info('Running %r', argv)
128 return subprocess.call(argv, **kwargs)
Eric Borenf171e162016-11-14 12:18:34 -0500129
Robert Iannuccie8b50852017-03-15 01:24:56 -0700130
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700131def _git_check_call(argv, **kwargs):
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700132 argv = [GIT] + argv
borenet1ed2ae42016-07-26 11:52:17 -0700133 logging.info('Running %r', argv)
134 subprocess.check_call(argv, **kwargs)
Eric Borenf171e162016-11-14 12:18:34 -0500135
136
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700137def _git_output(argv, **kwargs):
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700138 argv = [GIT] + argv
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700139 logging.info('Running %r', argv)
140 return subprocess.check_output(argv, **kwargs)
141
142
143def parse_args(argv):
144 """This extracts a subset of the arguments that this bootstrap script cares
145 about. Currently this consists of:
Robert Iannuccie1c23542018-12-07 17:42:12 -0800146 * an override for the recipe engine in the form of `-O recipe_engine=/path`
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700147 * the --package option.
148 """
Robert Iannuccie8b50852017-03-15 01:24:56 -0700149 PREFIX = 'recipe_engine='
150
Eric Borenc1e96172017-04-19 11:12:20 +0000151 p = argparse.ArgumentParser(add_help=False)
Robert Iannuccie8b50852017-03-15 01:24:56 -0700152 p.add_argument('-O', '--project-override', action='append')
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700153 p.add_argument('--package', type=os.path.abspath)
Robert Iannuccie8b50852017-03-15 01:24:56 -0700154 args, _ = p.parse_known_args(argv)
155 for override in args.project_override or ():
156 if override.startswith(PREFIX):
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700157 return override[len(PREFIX):], args.package
158 return None, args.package
159
160
161def checkout_engine(engine_path, repo_root, recipes_cfg_path):
162 dep, recipes_path = parse(repo_root, recipes_cfg_path)
Eric Boren8e0c2c92017-09-27 13:03:35 -0400163 if dep is None:
164 # we're running from the engine repo already!
165 return os.path.join(repo_root, recipes_path)
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700166
167 url = dep.url
168
169 if not engine_path and url.startswith('file://'):
170 engine_path = urlparse.urlparse(url).path
171
172 if not engine_path:
173 revision = dep.revision
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700174 branch = dep.branch
175
176 # Ensure that we have the recipe engine cloned.
recipe-roller1ce80fb2019-01-16 15:11:31 -0800177 engine_path = os.path.join(recipes_path, '.recipe_deps', 'recipe_engine')
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700178
179 with open(os.devnull, 'w') as NUL:
180 # Note: this logic mirrors the logic in recipe_engine/fetch.py
recipe-roller1ce80fb2019-01-16 15:11:31 -0800181 _git_check_call(['init', engine_path], stdout=NUL)
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700182
183 try:
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700184 _git_check_call(['rev-parse', '--verify',
185 '%s^{commit}' % revision],
186 cwd=engine_path,
187 stdout=NUL,
188 stderr=NUL)
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700189 except subprocess.CalledProcessError:
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700190 _git_check_call(['fetch', url, branch],
191 cwd=engine_path,
192 stdout=NUL,
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700193 stderr=NUL)
194
195 try:
recipe-roller1ce80fb2019-01-16 15:11:31 -0800196 _git_check_call(['diff', '--quiet', revision], cwd=engine_path)
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700197 except subprocess.CalledProcessError:
recipe-roller1ce80fb2019-01-16 15:11:31 -0800198 _git_check_call(['reset', '-q', '--hard', revision], cwd=engine_path)
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700199
recipe-roller98b14ff2019-03-28 13:03:40 -0700200 # If the engine has refactored/moved modules we need to clean all .pyc files
201 # or things will get squirrely.
202 _git_check_call(['clean', '-qxf'], cwd=engine_path)
203
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700204 return engine_path
Robert Iannuccie8b50852017-03-15 01:24:56 -0700205
206
borenet1ed2ae42016-07-26 11:52:17 -0700207def main():
recipe-roller11078c652019-04-05 11:34:44 -0700208 for required_binary in REQUIRED_BINARIES:
209 if not _is_on_path(required_binary):
210 return 'Required binary is not found on PATH: %s' % required_binary
211
borenet1ed2ae42016-07-26 11:52:17 -0700212 if '--verbose' in sys.argv:
213 logging.getLogger().setLevel(logging.INFO)
Eric Borenf171e162016-11-14 12:18:34 -0500214
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700215 args = sys.argv[1:]
216 engine_override, recipes_cfg_path = parse_args(args)
Robert Iannuccie8b50852017-03-15 01:24:56 -0700217
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700218 if recipes_cfg_path:
219 # calculate repo_root from recipes_cfg_path
220 repo_root = os.path.dirname(
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700221 os.path.dirname(os.path.dirname(recipes_cfg_path)))
borenet1ed2ae42016-07-26 11:52:17 -0700222 else:
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700223 # find repo_root with git and calculate recipes_cfg_path
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700224 repo_root = (
225 _git_output(['rev-parse', '--show-toplevel'],
226 cwd=os.path.abspath(os.path.dirname(__file__))).strip())
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700227 repo_root = os.path.abspath(repo_root)
228 recipes_cfg_path = os.path.join(repo_root, 'infra', 'config', 'recipes.cfg')
229 args = ['--package', recipes_cfg_path] + args
Eric Borenf171e162016-11-14 12:18:34 -0500230
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700231 engine_path = checkout_engine(engine_override, repo_root, recipes_cfg_path)
Eric Borenf171e162016-11-14 12:18:34 -0500232
recipe-roller955ddaf2019-05-20 13:03:55 -0700233 try:
recipe-roller0cfdf7f2019-05-22 10:16:16 -0700234 return _subprocess_call(
235 [VPYTHON, '-u',
236 os.path.join(engine_path, 'recipe_engine', 'main.py')] + args)
recipe-roller955ddaf2019-05-20 13:03:55 -0700237 except KeyboardInterrupt:
238 return 1
Eric Borenf171e162016-11-14 12:18:34 -0500239
Robert Iannucci3734c7d2017-05-09 11:06:48 -0700240
borenet1ed2ae42016-07-26 11:52:17 -0700241if __name__ == '__main__':
242 sys.exit(main())