blob: 4c20d5b66baee917d808415f08d472ba4f979f63 [file] [log] [blame]
Edward Lemur3c814952019-08-12 19:43:00 +00001#!/usr/bin/env vpython
maruel@chromium.org96550942015-05-22 18:46:51 +00002# Copyright 2015 The Chromium Authors. All rights reserved.
szager@chromium.org03fd85b2014-06-09 23:43:33 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
maruel@chromium.org96550942015-05-22 18:46:51 +00006"""Rolls DEPS controlled dependency.
szager@chromium.org03fd85b2014-06-09 23:43:33 +00007
sbc@chromium.org30e5b232015-06-01 18:06:59 +00008Works only with git checkout and git dependencies. Currently this
9script will always roll to the tip of to origin/master.
szager@chromium.org03fd85b2014-06-09 23:43:33 +000010"""
11
Raul Tambre80ee78e2019-05-06 22:41:05 +000012from __future__ import print_function
13
sbc@chromium.org30e5b232015-06-01 18:06:59 +000014import argparse
Edward Lesmesa1df57c2018-04-03 20:00:07 -040015import collections
Edward Lesmesc772cf72018-04-03 14:47:30 -040016import gclient_eval
szager@chromium.org03fd85b2014-06-09 23:43:33 +000017import os
18import re
maruel@chromium.org96550942015-05-22 18:46:51 +000019import subprocess
szager@chromium.org03fd85b2014-06-09 23:43:33 +000020import sys
21
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000022NEED_SHELL = sys.platform.startswith('win')
Edward Lemurfaae42e2018-11-26 18:34:30 +000023GCLIENT_PATH = os.path.join(
24 os.path.dirname(os.path.abspath(__file__)), 'gclient.py')
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000025
26
Marc-Antoine Ruel1e2cb152019-04-17 17:32:52 +000027# Commit subject that will be considered a roll. In the format generated by the
28# git log used, so it's "<year>-<month>-<day> <author> <subject>"
29_ROLL_SUBJECT = re.compile(
30 # Date
31 r'^\d\d\d\d-\d\d-\d\d '
32 # Author
33 r'[^ ]+ '
34 # Subject
35 r'('
36 # Generated by
37 # https://skia.googlesource.com/buildbot/+/master/autoroll/go/repo_manager/deps_repo_manager.go
38 r'Roll [^ ]+ [a-f0-9]+\.\.[a-f0-9]+ \(\d+ commits\)'
39 r'|'
40 # Generated by
41 # https://chromium.googlesource.com/infra/infra/+/master/recipes/recipe_modules/recipe_autoroller/api.py
42 r'Roll recipe dependencies \(trivial\)\.'
43 r')$')
44
45
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000046class Error(Exception):
47 pass
48
49
smut7036c4f2016-06-09 14:28:48 -070050class AlreadyRolledError(Error):
51 pass
52
53
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000054def check_output(*args, **kwargs):
55 """subprocess.check_output() passing shell=True on Windows for git."""
56 kwargs.setdefault('shell', NEED_SHELL)
57 return subprocess.check_output(*args, **kwargs)
58
59
60def check_call(*args, **kwargs):
61 """subprocess.check_call() passing shell=True on Windows for git."""
62 kwargs.setdefault('shell', NEED_SHELL)
63 subprocess.check_call(*args, **kwargs)
64
65
maruel@chromium.org96550942015-05-22 18:46:51 +000066def is_pristine(root, merge_base='origin/master'):
67 """Returns True if a git checkout is pristine."""
68 cmd = ['git', 'diff', '--ignore-submodules', merge_base]
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000069 return not (check_output(cmd, cwd=root).strip() or
70 check_output(cmd + ['--cached'], cwd=root).strip())
szager@chromium.org03fd85b2014-06-09 23:43:33 +000071
72
maruel@chromium.org398ed342015-09-29 12:27:25 +000073def get_log_url(upstream_url, head, master):
74 """Returns an URL to read logs via a Web UI if applicable."""
75 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
76 # gitiles
77 return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
78 if upstream_url.startswith('https://github.com/'):
79 upstream_url = upstream_url.rstrip('/')
80 if upstream_url.endswith('.git'):
81 upstream_url = upstream_url[:-len('.git')]
82 return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
83 return None
84
85
86def should_show_log(upstream_url):
87 """Returns True if a short log should be included in the tree."""
88 # Skip logs for very active projects.
Eric Boren07efc5a2017-08-28 09:13:20 -040089 if upstream_url.endswith('/v8/v8.git'):
maruel@chromium.org398ed342015-09-29 12:27:25 +000090 return False
91 if 'webrtc' in upstream_url:
92 return False
93 return True
94
95
Edward Lemurfaae42e2018-11-26 18:34:30 +000096def gclient(args):
97 """Executes gclient with the given args and returns the stdout."""
98 return check_output([sys.executable, GCLIENT_PATH] + args).strip()
sbc@chromium.org98201122015-04-22 20:21:34 +000099
maruel@chromium.org96550942015-05-22 18:46:51 +0000100
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500101def generate_commit_message(
102 full_dir, dependency, head, roll_to, no_log, log_limit):
103 """Creates the commit message for this specific roll."""
maruel@chromium.org398ed342015-09-29 12:27:25 +0000104 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org398ed342015-09-29 12:27:25 +0000105 upstream_url = check_output(
106 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
107 log_url = get_log_url(upstream_url, head, roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500108 cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000109 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000110 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500111 cwd=full_dir).rstrip()
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000112 logs = re.sub(r'(?m)^(\d\d\d\d-\d\d-\d\d [^@]+)@[^ ]+( .*)$', r'\1\2', logs)
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500113 lines = logs.splitlines()
Marc-Antoine Ruel1e2cb152019-04-17 17:32:52 +0000114 cleaned_lines = [l for l in lines if not _ROLL_SUBJECT.match(l)]
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500115 logs = '\n'.join(cleaned_lines) + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500116
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500117 nb_commits = len(lines)
118 rolls = nb_commits - len(cleaned_lines)
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500119 header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500120 dependency,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000121 commit_range,
122 nb_commits,
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500123 's' if nb_commits > 1 else '',
124 ('; %s trivial rolls' % rolls) if rolls else '')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000125 log_section = ''
126 if log_url:
127 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000128 log_section += '$ %s ' % ' '.join(cmd)
129 log_section += '--format=\'%ad %ae %s\'\n'
Eric Boren3be96a82017-09-29 10:07:46 -0400130 # It is important that --no-log continues to work, as it is used by
131 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000132 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500133 if len(cleaned_lines) > log_limit:
Marc-Antoine Ruel6ce18222019-01-16 21:36:36 +0000134 # Keep the first N/2 log entries and last N/2 entries.
135 lines = logs.splitlines(True)
136 lines = lines[:log_limit/2] + ['(...)\n'] + lines[-log_limit/2:]
137 logs = ''.join(lines)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000138 log_section += logs
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500139 return header + log_section
maruel@chromium.org398ed342015-09-29 12:27:25 +0000140
maruel@chromium.org96550942015-05-22 18:46:51 +0000141
Edward Lemurfaae42e2018-11-26 18:34:30 +0000142def calculate_roll(full_dir, dependency, roll_to):
Edward Lesmesc772cf72018-04-03 14:47:30 -0400143 """Calculates the roll for a dependency by processing gclient_dict, and
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500144 fetching the dependency via git.
145 """
Edward Lemurfaae42e2018-11-26 18:34:30 +0000146 head = gclient(['getdep', '-r', dependency])
Edward Lesmesc772cf72018-04-03 14:47:30 -0400147 if not head:
148 raise Error('%s is unpinned.' % dependency)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500149 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
150 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
151 return head, roll_to
152
153
Robert Iannuccic1e65942018-10-18 17:59:45 +0000154def gen_commit_msg(logs, cmdline, reviewers, bug):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500155 """Returns the final commit message."""
156 commit_msg = ''
157 if len(logs) > 1:
158 commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
159 commit_msg += '\n\n'.join(logs)
Kenneth Russellebe839b2017-12-22 14:55:39 -0800160 commit_msg += '\nCreated with:\n ' + cmdline + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500161 commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
Robert Iannuccic1e65942018-10-18 17:59:45 +0000162 commit_msg += '\nBug: %s\n' % bug if bug else ''
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500163 return commit_msg
164
165
Edward Lemurfaae42e2018-11-26 18:34:30 +0000166def finalize(commit_msg, current_dir, rolls):
167 """Commits changes to the DEPS file, then uploads a CL."""
maruel@chromium.org96550942015-05-22 18:46:51 +0000168 print('Commit message:')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500169 print('\n'.join(' ' + i for i in commit_msg.splitlines()))
170
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400171 check_call(['git', 'add', 'DEPS'], cwd=current_dir)
172 check_call(['git', 'commit', '--quiet', '-m', commit_msg], cwd=current_dir)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000173
174 # Pull the dependency to the right revision. This is surprising to users
175 # otherwise.
Edward Lemurfaae42e2018-11-26 18:34:30 +0000176 for _head, roll_to, full_dir in sorted(rolls.itervalues()):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500177 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000178
179
maruel@chromium.org96550942015-05-22 18:46:51 +0000180def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000181 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000182 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000183 '--ignore-dirty-tree', action='store_true',
184 help='Roll anyways, even if there is a diff.')
185 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000186 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000187 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000188 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000189 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
Eric Boren3be96a82017-09-29 10:07:46 -0400190 # It is important that --no-log continues to work, as it is used by
191 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000192 parser.add_argument(
193 '--no-log', action='store_true',
194 help='Do not include the short log in the commit message')
195 parser.add_argument(
196 '--log-limit', type=int, default=100,
197 help='Trim log after N commits (default: %(default)s)')
198 parser.add_argument(
199 '--roll-to', default='origin/master',
200 help='Specify the new commit to roll to (default: %(default)s)')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500201 parser.add_argument(
202 '--key', action='append', default=[],
203 help='Regex(es) for dependency in DEPS file')
204 parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000205 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000206
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500207 if len(args.dep_path) > 1:
208 if args.roll_to != 'origin/master':
209 parser.error(
210 'Can\'t use multiple paths to roll simultaneously and --roll-to')
211 if args.key:
212 parser.error(
213 'Can\'t use multiple paths to roll simultaneously and --key')
maruel@chromium.org96550942015-05-22 18:46:51 +0000214 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000215 if args.reviewer:
216 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000217 for i, r in enumerate(reviewers):
218 if not '@' in r:
219 reviewers[i] = r + '@chromium.org'
220
Edward Lemurfaae42e2018-11-26 18:34:30 +0000221 gclient_root = gclient(['root'])
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400222 current_dir = os.getcwd()
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500223 dependencies = sorted(d.rstrip('/').rstrip('\\') for d in args.dep_path)
224 cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(
225 ' --key ' + k for k in args.key)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000226 try:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400227 if not args.ignore_dirty_tree and not is_pristine(current_dir):
228 raise Error(
229 'Ensure %s is clean first (no non-merged commits).' % current_dir)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500230 # First gather all the information without modifying anything, except for a
231 # git fetch.
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500232 rolls = {}
233 for dependency in dependencies:
Edward Lemurfaae42e2018-11-26 18:34:30 +0000234 full_dir = os.path.normpath(os.path.join(gclient_root, dependency))
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500235 if not os.path.isdir(full_dir):
Edward Lemurfaae42e2018-11-26 18:34:30 +0000236 print('Dependency %s not found at %s' % (dependency, full_dir))
237 full_dir = os.path.normpath(os.path.join(current_dir, dependency))
238 print('Will look for relative dependency at %s' % full_dir)
239 if not os.path.isdir(full_dir):
240 raise Error('Directory not found: %s (%s)' % (dependency, full_dir))
241
242 head, roll_to = calculate_roll(full_dir, dependency, args.roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500243 if roll_to == head:
244 if len(dependencies) == 1:
245 raise AlreadyRolledError('No revision to roll!')
246 print('%s: Already at latest commit %s' % (dependency, roll_to))
247 else:
248 print(
249 '%s: Rolling from %s to %s' % (dependency, head[:10], roll_to[:10]))
Edward Lemurfaae42e2018-11-26 18:34:30 +0000250 rolls[dependency] = (head, roll_to, full_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000251
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500252 logs = []
Edward Lemurfaae42e2018-11-26 18:34:30 +0000253 setdep_args = []
254 for dependency, (head, roll_to, full_dir) in sorted(rolls.iteritems()):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500255 log = generate_commit_message(
256 full_dir, dependency, head, roll_to, args.no_log, args.log_limit)
257 logs.append(log)
Edward Lemurfaae42e2018-11-26 18:34:30 +0000258 setdep_args.extend(['-r', '{}@{}'.format(dependency, roll_to)])
Edward Lesmesc772cf72018-04-03 14:47:30 -0400259
Edward Lemurfaae42e2018-11-26 18:34:30 +0000260 gclient(['setdep'] + setdep_args)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500261
Robert Iannuccic1e65942018-10-18 17:59:45 +0000262 commit_msg = gen_commit_msg(logs, cmdline, reviewers, args.bug)
Edward Lemurfaae42e2018-11-26 18:34:30 +0000263 finalize(commit_msg, current_dir, rolls)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000264 except Error as e:
265 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700266 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000267
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500268 print('')
269 if not reviewers:
270 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
271 print('to the commit description before emailing.')
272 print('')
273 print('Run:')
274 print(' git cl upload --send-mail')
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000275 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000276
sbc@chromium.org98201122015-04-22 20:21:34 +0000277
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000278if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000279 sys.exit(main())