roll_dep.py 7.65 KB
Newer Older
1
#!/usr/bin/env python
2
# Copyright 2015 The Chromium Authors. All rights reserved.
3 4 5
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

6
"""Rolls DEPS controlled dependency.
7

8 9
Works only with git checkout and git dependencies.  Currently this
script will always roll to the tip of to origin/master.
10 11
"""

12
import argparse
13 14
import os
import re
15
import subprocess
16 17
import sys

18 19 20
NEED_SHELL = sys.platform.startswith('win')


21 22 23 24
class Error(Exception):
  pass


25 26 27 28
class AlreadyRolledError(Error):
  pass


29 30 31 32 33 34 35 36 37 38 39 40
def check_output(*args, **kwargs):
  """subprocess.check_output() passing shell=True on Windows for git."""
  kwargs.setdefault('shell', NEED_SHELL)
  return subprocess.check_output(*args, **kwargs)


def check_call(*args, **kwargs):
  """subprocess.check_call() passing shell=True on Windows for git."""
  kwargs.setdefault('shell', NEED_SHELL)
  subprocess.check_call(*args, **kwargs)


41 42 43
def is_pristine(root, merge_base='origin/master'):
  """Returns True if a git checkout is pristine."""
  cmd = ['git', 'diff', '--ignore-submodules', merge_base]
44 45
  return not (check_output(cmd, cwd=root).strip() or
              check_output(cmd + ['--cached'], cwd=root).strip())
46 47


48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
def get_log_url(upstream_url, head, master):
  """Returns an URL to read logs via a Web UI if applicable."""
  if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
    # gitiles
    return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
  if upstream_url.startswith('https://github.com/'):
    upstream_url = upstream_url.rstrip('/')
    if upstream_url.endswith('.git'):
      upstream_url = upstream_url[:-len('.git')]
    return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
  return None


def should_show_log(upstream_url):
  """Returns True if a short log should be included in the tree."""
  # Skip logs for very active projects.
64
  if upstream_url.endswith('/v8/v8.git'):
65 66 67 68 69 70
    return False
  if 'webrtc' in upstream_url:
    return False
  return True


71 72
def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit,
         ignore_dirty_tree=False):
73
  deps = os.path.join(root, 'DEPS')
74
  try:
75 76
    with open(deps, 'rb') as f:
      deps_content = f.read()
77
  except (IOError, OSError):
78 79
    raise Error('Ensure the script is run in the directory '
                'containing DEPS file.')
80

81
  if not ignore_dirty_tree and not is_pristine(root):
82
    raise Error('Ensure %s is clean first (no non-merged commits).' % root)
83

84
  full_dir = os.path.normpath(os.path.join(os.path.dirname(root), deps_dir))
85
  if not os.path.isdir(full_dir):
86
    raise Error('Directory not found: %s (%s)' % (deps_dir, full_dir))
87
  head = check_output(['git', 'rev-parse', 'HEAD'], cwd=full_dir).strip()
88 89 90 91

  if not head in deps_content:
    print('Warning: %s is not checked out at the expected revision in DEPS' %
          deps_dir)
92 93 94 95
    if key is None:
      print("Warning: no key specified.  Using '%s'." % deps_dir)
      key = deps_dir

96 97 98
    # It happens if the user checked out a branch in the dependency by himself.
    # Fall back to reading the DEPS to figure out the original commit.
    for i in deps_content.splitlines():
99
      m = re.match(r'\s+"' + key + '":.*"([a-z0-9]{40})",', i)
100 101 102 103
      if m:
        head = m.group(1)
        break
    else:
104
      raise Error('Expected to find commit %s for %s in DEPS' % (head, key))
105

106
  print('Found old revision %s' % head)
107

108 109 110
  check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
  roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
  print('Found new revision %s' % roll_to)
111

112
  if roll_to == head:
113
    raise AlreadyRolledError('No revision to roll!')
114

115
  commit_range = '%s..%s' % (head[:9], roll_to[:9])
116

117 118 119
  upstream_url = check_output(
      ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
  log_url = get_log_url(upstream_url, head, roll_to)
120 121 122
  cmd = [
    'git', 'log', commit_range, '--date=short', '--no-merges',
  ]
123
  logs = check_output(
124
      cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
125
      cwd=full_dir).rstrip()
126
  logs = re.sub(r'(?m)^(\d\d\d\d-\d\d-\d\d [^@]+)@[^ ]+( .*)$', r'\1\2', logs)
127 128 129 130 131 132 133 134
  lines = logs.splitlines()
  cleaned_lines = [
      l for l in lines
      if not l.endswith('recipe-roller Roll recipe dependencies (trivial).')
  ]
  logs = '\n'.join(cleaned_lines) + '\n'
  nb_commits = len(lines)
  rolls = nb_commits - len(cleaned_lines)
135

136
  header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
137 138 139
      deps_dir,
      commit_range,
      nb_commits,
140 141
      's' if nb_commits > 1 else '',
      ('; %s trivial rolls' % rolls) if rolls else '')
142 143 144 145

  log_section = ''
  if log_url:
    log_section = log_url + '\n\n'
146 147
  log_section += '$ %s ' % ' '.join(cmd)
  log_section += '--format=\'%ad %ae %s\'\n'
148 149
  # It is important that --no-log continues to work, as it is used by
  # internal -> external rollers. Please do not remove or break it.
150
  if not no_log and should_show_log(upstream_url):
151
    if len(cleaned_lines) > log_limit:
152 153 154
      # Keep the first N log entries.
      logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
    log_section += logs
155
  log_section += '\n\nCreated with:\n  roll-dep %s\n' % deps_dir
156

157 158
  reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
  bug = 'BUG=%s\n' % bug if bug else ''
159
  msg = header + log_section + reviewer + bug
160 161 162

  print('Commit message:')
  print('\n'.join('    ' + i for i in msg.splitlines()))
163
  deps_content = deps_content.replace(head, roll_to)
164 165
  with open(deps, 'wb') as f:
    f.write(deps_content)
166
  check_call(['git', 'add', 'DEPS'], cwd=root)
167 168 169 170 171 172
  check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)

  # Pull the dependency to the right revision. This is surprising to users
  # otherwise.
  check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)

173 174 175 176 177 178 179
  print('')
  if not reviewers:
    print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
    print('to the commit description before emailing.')
    print('')
  print('Run:')
  print('  git cl upload --send-mail')
180 181


182
def main():
183
  parser = argparse.ArgumentParser(description=__doc__)
184 185 186
  parser.add_argument(
      '--ignore-dirty-tree', action='store_true',
      help='Roll anyways, even if there is a diff.')
187 188
  parser.add_argument(
      '-r', '--reviewer',
189
      help='To specify multiple reviewers, use comma separated list, e.g. '
190
           '-r joe,jane,john. Defaults to @chromium.org')
191
  parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
192 193
  # It is important that --no-log continues to work, as it is used by
  # internal -> external rollers. Please do not remove or break it.
194 195 196 197 198 199 200 201 202 203
  parser.add_argument(
      '--no-log', action='store_true',
      help='Do not include the short log in the commit message')
  parser.add_argument(
      '--log-limit', type=int, default=100,
      help='Trim log after N commits (default: %(default)s)')
  parser.add_argument(
      '--roll-to', default='origin/master',
      help='Specify the new commit to roll to (default: %(default)s)')
  parser.add_argument('dep_path', help='Path to dependency')
204
  parser.add_argument('key', nargs='?',
205
      help='Regexp for dependency in DEPS file')
206
  args = parser.parse_args()
207 208

  reviewers = None
209 210
  if args.reviewer:
    reviewers = args.reviewer.split(',')
211 212 213 214
    for i, r in enumerate(reviewers):
      if not '@' in r:
        reviewers[i] = r + '@chromium.org'

215 216 217
  try:
    roll(
        os.getcwd(),
218
        args.dep_path.rstrip('/').rstrip('\\'),
219
        args.roll_to,
220
        args.key,
221 222 223
        reviewers,
        args.bug,
        args.no_log,
224 225
        args.log_limit,
        args.ignore_dirty_tree)
226 227 228

  except Error as e:
    sys.stderr.write('error: %s\n' % e)
229
    return 2 if isinstance(e, AlreadyRolledError) else 1
230 231

  return 0
232

233

234
if __name__ == '__main__':
235
  sys.exit(main())