recipes.py 6.98 KB
Newer Older
1 2
#!/usr/bin/env python

3
# Copyright 2017 The LUCI Authors. All rights reserved.
4 5
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
6

7 8
"""Bootstrap script to clone and forward to the recipe engine tool.

9 10 11
*******************
** DO NOT MODIFY **
*******************
12

13 14
This is a copy of https://chromium.googlesource.com/infra/luci/recipes-py/+/master/doc/recipes.py.
To fix bugs, fix in the googlesource repo then run the autoroller.
15 16
"""

17
import argparse
18
import json
19
import logging
20
import os
21 22 23 24
import random
import subprocess
import sys
import time
25
import urlparse
26

27 28
from collections import namedtuple

29
from cStringIO import StringIO
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44
# The dependency entry for the recipe_engine in the client repo's recipes.cfg
#
# url (str) - the url to the engine repo we want to use.
# revision (str) - the git revision for the engine to get.
# path_override (str) - the subdirectory in the engine repo we should use to
#   find it's recipes.py entrypoint. This is here for completeness, but will
#   essentially always be empty. It would be used if the recipes-py repo was
#   merged as a subdirectory of some other repo and you depended on that
#   subdirectory.
# branch (str) - the branch to fetch for the engine as an absolute ref (e.g.
#   refs/heads/master)
# repo_type ("GIT"|"GITILES") - An ignored enum which will be removed soon.
EngineDep = namedtuple('EngineDep',
                       'url revision path_override branch repo_type')
45

46 47 48 49 50 51 52

class MalformedRecipesCfg(Exception):
  def __init__(self, msg, path):
    super(MalformedRecipesCfg, self).__init__('malformed recipes.cfg: %s: %r'
                                              % (msg, path))


53
def parse(repo_root, recipes_cfg_path):
54
  """Parse is a lightweight a recipes.cfg file parser.
55 56 57 58 59 60 61

  Args:
    repo_root (str) - native path to the root of the repo we're trying to run
      recipes for.
    recipes_cfg_path (str) - native path to the recipes.cfg file to process.

  Returns (as tuple):
62 63
    engine_dep (EngineDep|None): The recipe_engine dependency, or None, if the
      current repo IS the recipe_engine.
64 65 66 67 68
    recipes_path (str) - native path to where the recipes live inside of the
      current repo (i.e. the folder containing `recipes/` and/or
      `recipe_modules`)
  """
  with open(recipes_cfg_path, 'rU') as fh:
69 70
    pb = json.load(fh)

71 72 73 74 75
  try:
    if pb['api_version'] != 2:
      raise MalformedRecipesCfg('unknown version %d' % pb['api_version'],
                                recipes_cfg_path)

76 77 78 79 80
    # If we're running ./doc/recipes.py from the recipe_engine repo itself, then
    # return None to signal that there's no EngineDep.
    if pb['project_id'] == 'recipe_engine':
      return None, pb.get('recipes_path', '')

81
    engine = pb['deps']['recipe_engine']
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    if 'url' not in engine:
      raise MalformedRecipesCfg(
        'Required field "url" in dependency "recipe_engine" not found',
        recipes_cfg_path)

    engine.setdefault('revision', '')
    engine.setdefault('path_override', '')
    engine.setdefault('branch', 'refs/heads/master')
    recipes_path = pb.get('recipes_path', '')

    # TODO(iannucci): only support absolute refs
    if not engine['branch'].startswith('refs/'):
      engine['branch'] = 'refs/heads/' + engine['branch']

    engine.setdefault('repo_type', 'GIT')
    if engine['repo_type'] not in ('GIT', 'GITILES'):
      raise MalformedRecipesCfg(
        'Unsupported "repo_type" value in dependency "recipe_engine"',
        recipes_cfg_path)

    recipes_path = os.path.join(
      repo_root, recipes_path.replace('/', os.path.sep))
    return EngineDep(**engine), recipes_path
  except KeyError as ex:
    raise MalformedRecipesCfg(ex.message, recipes_cfg_path)
108 109


110 111 112
_BAT = '.bat' if sys.platform.startswith(('win', 'cygwin')) else ''
GIT = 'git' + _BAT
VPYTHON = 'vpython' + _BAT
113 114


115 116 117 118
def _subprocess_call(argv, **kwargs):
  logging.info('Running %r', argv)
  return subprocess.call(argv, **kwargs)

119

120 121
def _git_check_call(argv, **kwargs):
  argv = [GIT]+argv
122 123 124 125
  logging.info('Running %r', argv)
  subprocess.check_call(argv, **kwargs)


126 127 128 129 130 131
def _git_output(argv, **kwargs):
  argv = [GIT]+argv
  logging.info('Running %r', argv)
  return subprocess.check_output(argv, **kwargs)


132 133 134 135 136 137
def parse_args(argv):
  """This extracts a subset of the arguments that this bootstrap script cares
  about. Currently this consists of:
    * an override for the recipe engine in the form of `-O recipe_engin=/path`
    * the --package option.
  """
138 139
  PREFIX = 'recipe_engine='

140
  p = argparse.ArgumentParser(add_help=False)
141
  p.add_argument('-O', '--project-override', action='append')
142
  p.add_argument('--package', type=os.path.abspath)
143 144 145
  args, _ = p.parse_known_args(argv)
  for override in args.project_override or ():
    if override.startswith(PREFIX):
146 147
      return override[len(PREFIX):], args.package
  return None, args.package
148

149

150
def checkout_engine(engine_path, repo_root, recipes_cfg_path):
151
  dep, recipes_path = parse(repo_root, recipes_cfg_path)
152 153 154
  if dep is None:
    # we're running from the engine repo already!
    return os.path.join(repo_root, recipes_path)
155

156
  url = dep.url
157

158 159
  if not engine_path and url.startswith('file://'):
    engine_path = urlparse.urlparse(url).path
160

161
  if not engine_path:
162 163 164 165
    revision = dep.revision
    subpath = dep.path_override
    branch = dep.branch

166
    # Ensure that we have the recipe engine cloned.
167 168 169 170 171 172 173 174 175 176 177 178 179
    engine = os.path.join(recipes_path, '.recipe_deps', 'recipe_engine')
    engine_path = os.path.join(engine, subpath)

    with open(os.devnull, 'w') as NUL:
      # Note: this logic mirrors the logic in recipe_engine/fetch.py
      _git_check_call(['init', engine], stdout=NUL)

      try:
        _git_check_call(['rev-parse', '--verify', '%s^{commit}' % revision],
                        cwd=engine, stdout=NUL, stderr=NUL)
      except subprocess.CalledProcessError:
        _git_check_call(['fetch', url, branch], cwd=engine, stdout=NUL,
                        stderr=NUL)
180 181

    try:
182
      _git_check_call(['diff', '--quiet', revision], cwd=engine)
183
    except subprocess.CalledProcessError:
184 185 186 187
      _git_check_call(['reset', '-q', '--hard', revision], cwd=engine)

  return engine_path

188

189 190 191 192
def main():
  if '--verbose' in sys.argv:
    logging.getLogger().setLevel(logging.INFO)

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  args = sys.argv[1:]
  engine_override, recipes_cfg_path = parse_args(args)

  if recipes_cfg_path:
    # calculate repo_root from recipes_cfg_path
    repo_root = os.path.dirname(
      os.path.dirname(
        os.path.dirname(recipes_cfg_path)))
  else:
    # find repo_root with git and calculate recipes_cfg_path
    repo_root = (_git_output(
      ['rev-parse', '--show-toplevel'],
      cwd=os.path.abspath(os.path.dirname(__file__))).strip())
    repo_root = os.path.abspath(repo_root)
    recipes_cfg_path = os.path.join(repo_root, 'infra', 'config', 'recipes.cfg')
    args = ['--package', recipes_cfg_path] + args

  engine_path = checkout_engine(engine_override, repo_root, recipes_cfg_path)
211

212
  return _subprocess_call([
213
      VPYTHON, '-u',
214
      os.path.join(engine_path, 'recipes.py')] + args)
215

216

217 218
if __name__ == '__main__':
  sys.exit(main())