blob: ef19a364c3a8142d0929b9b11518da43107c2a7c [file] [log] [blame]
Edward Lesmes7149d232019-08-12 21:04:04 +00001#!/usr/bin/env python
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
Josip Sokcevic9c0dc302020-11-20 18:41:25 +00009script will always roll to the tip of to origin/main or 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
szager@chromium.org03fd85b2014-06-09 23:43:33 +000015import os
16import re
Corentin Wallez5157fbf2020-11-12 22:31:35 +000017import subprocess2
szager@chromium.org03fd85b2014-06-09 23:43:33 +000018import sys
19
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000020NEED_SHELL = sys.platform.startswith('win')
Edward Lemurfaae42e2018-11-26 18:34:30 +000021GCLIENT_PATH = os.path.join(
22 os.path.dirname(os.path.abspath(__file__)), 'gclient.py')
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000023
24
Marc-Antoine Ruel1e2cb152019-04-17 17:32:52 +000025# Commit subject that will be considered a roll. In the format generated by the
26# git log used, so it's "<year>-<month>-<day> <author> <subject>"
27_ROLL_SUBJECT = re.compile(
28 # Date
29 r'^\d\d\d\d-\d\d-\d\d '
30 # Author
31 r'[^ ]+ '
32 # Subject
33 r'('
34 # Generated by
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000035 # https://skia.googlesource.com/buildbot/+/HEAdA/autoroll/go/repo_manager/deps_repo_manager.go
Marc-Antoine Ruel1e2cb152019-04-17 17:32:52 +000036 r'Roll [^ ]+ [a-f0-9]+\.\.[a-f0-9]+ \(\d+ commits\)'
37 r'|'
38 # Generated by
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000039 # https://chromium.googlesource.com/infra/infra/+/HEAD/recipes/recipe_modules/recipe_autoroller/api.py
Marc-Antoine Ruel1e2cb152019-04-17 17:32:52 +000040 r'Roll recipe dependencies \(trivial\)\.'
41 r')$')
42
43
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000044class Error(Exception):
45 pass
46
47
smut7036c4f2016-06-09 14:28:48 -070048class AlreadyRolledError(Error):
49 pass
50
51
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000052def check_output(*args, **kwargs):
Corentin Wallez8732c0e2020-12-09 17:43:46 +000053 """subprocess2.check_output() passing shell=True on Windows for git."""
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000054 kwargs.setdefault('shell', NEED_SHELL)
Corentin Wallez5157fbf2020-11-12 22:31:35 +000055 return subprocess2.check_output(*args, **kwargs).decode('utf-8')
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000056
57
58def check_call(*args, **kwargs):
Corentin Wallez8732c0e2020-12-09 17:43:46 +000059 """subprocess2.check_call() passing shell=True on Windows for git."""
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000060 kwargs.setdefault('shell', NEED_SHELL)
Corentin Wallez5157fbf2020-11-12 22:31:35 +000061 subprocess2.check_call(*args, **kwargs)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000062
63
Corentin Wallez5157fbf2020-11-12 22:31:35 +000064def return_code(*args, **kwargs):
Corentin Wallez8732c0e2020-12-09 17:43:46 +000065 """subprocess2.call() passing shell=True on Windows for git and
Corentin Wallez5157fbf2020-11-12 22:31:35 +000066 subprocess2.VOID for stdout and stderr."""
67 kwargs.setdefault('shell', NEED_SHELL)
68 kwargs.setdefault('stdout', subprocess2.VOID)
69 kwargs.setdefault('stderr', subprocess2.VOID)
70 return subprocess2.call(*args, **kwargs)
71
72
73def is_pristine(root):
maruel@chromium.org96550942015-05-22 18:46:51 +000074 """Returns True if a git checkout is pristine."""
Corentin Wallez5157fbf2020-11-12 22:31:35 +000075 # Check both origin/master and origin/main since many projects are
76 # transitioning to origin/main.
77 for branch in ('origin/main', 'origin/master'):
78 # `git rev-parse --verify` has a non-zero return code if the revision
79 # doesn't exist.
80 rev_cmd = ['git', 'rev-parse', '--verify', '--quiet',
81 'refs/remotes/' + branch]
82 if return_code(rev_cmd, cwd=root) != 0:
83 continue
szager@chromium.org03fd85b2014-06-09 23:43:33 +000084
Corentin Wallez5157fbf2020-11-12 22:31:35 +000085 diff_cmd = ['git', 'diff', '--ignore-submodules', branch]
86 return (not check_output(diff_cmd, cwd=root).strip() and
87 not check_output(diff_cmd + ['--cached'], cwd=root).strip())
88
89
90 raise Error('Couldn\'t find any of origin/main or origin/master')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000091
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000092def get_log_url(upstream_url, head, tot):
maruel@chromium.org398ed342015-09-29 12:27:25 +000093 """Returns an URL to read logs via a Web UI if applicable."""
94 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
95 # gitiles
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000096 return '%s/+log/%s..%s' % (upstream_url, head[:12], tot[:12])
maruel@chromium.org398ed342015-09-29 12:27:25 +000097 if upstream_url.startswith('https://github.com/'):
98 upstream_url = upstream_url.rstrip('/')
99 if upstream_url.endswith('.git'):
100 upstream_url = upstream_url[:-len('.git')]
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000101 return '%s/compare/%s...%s' % (upstream_url, head[:12], tot[:12])
maruel@chromium.org398ed342015-09-29 12:27:25 +0000102 return None
103
104
105def should_show_log(upstream_url):
106 """Returns True if a short log should be included in the tree."""
107 # Skip logs for very active projects.
Eric Boren07efc5a2017-08-28 09:13:20 -0400108 if upstream_url.endswith('/v8/v8.git'):
maruel@chromium.org398ed342015-09-29 12:27:25 +0000109 return False
110 if 'webrtc' in upstream_url:
111 return False
112 return True
113
114
Edward Lemurfaae42e2018-11-26 18:34:30 +0000115def gclient(args):
116 """Executes gclient with the given args and returns the stdout."""
117 return check_output([sys.executable, GCLIENT_PATH] + args).strip()
sbc@chromium.org98201122015-04-22 20:21:34 +0000118
maruel@chromium.org96550942015-05-22 18:46:51 +0000119
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500120def generate_commit_message(
121 full_dir, dependency, head, roll_to, no_log, log_limit):
122 """Creates the commit message for this specific roll."""
Sylvain Defresneae2b9622020-01-31 09:46:06 +0000123 commit_range = '%s..%s' % (head, roll_to)
124 commit_range_for_header = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org398ed342015-09-29 12:27:25 +0000125 upstream_url = check_output(
126 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
127 log_url = get_log_url(upstream_url, head, roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500128 cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000129 logs = check_output(
Sylvain Defresneae2b9622020-01-31 09:46:06 +0000130 # Args with '=' are automatically quoted.
131 cmd + ['--format=%ad %ae %s', '--'],
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500132 cwd=full_dir).rstrip()
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000133 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 -0500134 lines = logs.splitlines()
Marc-Antoine Ruel1e2cb152019-04-17 17:32:52 +0000135 cleaned_lines = [l for l in lines if not _ROLL_SUBJECT.match(l)]
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500136 logs = '\n'.join(cleaned_lines) + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500137
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500138 nb_commits = len(lines)
139 rolls = nb_commits - len(cleaned_lines)
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500140 header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500141 dependency,
Sylvain Defresneae2b9622020-01-31 09:46:06 +0000142 commit_range_for_header,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000143 nb_commits,
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500144 's' if nb_commits > 1 else '',
145 ('; %s trivial rolls' % rolls) if rolls else '')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000146 log_section = ''
147 if log_url:
148 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000149 log_section += '$ %s ' % ' '.join(cmd)
150 log_section += '--format=\'%ad %ae %s\'\n'
Sylvain Defresne4ada8ab2020-01-31 17:22:56 +0000151 log_section = log_section.replace(commit_range, commit_range_for_header)
Eric Boren3be96a82017-09-29 10:07:46 -0400152 # It is important that --no-log continues to work, as it is used by
153 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000154 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500155 if len(cleaned_lines) > log_limit:
Marc-Antoine Ruel6ce18222019-01-16 21:36:36 +0000156 # Keep the first N/2 log entries and last N/2 entries.
157 lines = logs.splitlines(True)
Edward Lesmes994bed52020-04-01 16:21:40 +0000158 lines = lines[:log_limit//2] + ['(...)\n'] + lines[-log_limit//2:]
Marc-Antoine Ruel6ce18222019-01-16 21:36:36 +0000159 logs = ''.join(lines)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000160 log_section += logs
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500161 return header + log_section
maruel@chromium.org398ed342015-09-29 12:27:25 +0000162
maruel@chromium.org96550942015-05-22 18:46:51 +0000163
Edward Lemurfaae42e2018-11-26 18:34:30 +0000164def calculate_roll(full_dir, dependency, roll_to):
Edward Lesmesc772cf72018-04-03 14:47:30 -0400165 """Calculates the roll for a dependency by processing gclient_dict, and
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500166 fetching the dependency via git.
167 """
Edward Lemurfaae42e2018-11-26 18:34:30 +0000168 head = gclient(['getdep', '-r', dependency])
Edward Lesmesc772cf72018-04-03 14:47:30 -0400169 if not head:
170 raise Error('%s is unpinned.' % dependency)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500171 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
172 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
173 return head, roll_to
174
175
Robert Iannuccic1e65942018-10-18 17:59:45 +0000176def gen_commit_msg(logs, cmdline, reviewers, bug):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500177 """Returns the final commit message."""
178 commit_msg = ''
179 if len(logs) > 1:
180 commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
181 commit_msg += '\n\n'.join(logs)
Kenneth Russellebe839b2017-12-22 14:55:39 -0800182 commit_msg += '\nCreated with:\n ' + cmdline + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500183 commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
Robert Iannuccic1e65942018-10-18 17:59:45 +0000184 commit_msg += '\nBug: %s\n' % bug if bug else ''
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500185 return commit_msg
186
187
Edward Lemurfaae42e2018-11-26 18:34:30 +0000188def finalize(commit_msg, current_dir, rolls):
189 """Commits changes to the DEPS file, then uploads a CL."""
maruel@chromium.org96550942015-05-22 18:46:51 +0000190 print('Commit message:')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500191 print('\n'.join(' ' + i for i in commit_msg.splitlines()))
192
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400193 check_call(['git', 'add', 'DEPS'], cwd=current_dir)
194 check_call(['git', 'commit', '--quiet', '-m', commit_msg], cwd=current_dir)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000195
196 # Pull the dependency to the right revision. This is surprising to users
197 # otherwise.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000198 for _head, roll_to, full_dir in sorted(rolls.values()):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500199 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000200
201
maruel@chromium.org96550942015-05-22 18:46:51 +0000202def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000203 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000204 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000205 '--ignore-dirty-tree', action='store_true',
206 help='Roll anyways, even if there is a diff.')
207 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000208 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000209 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000210 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000211 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
Eric Boren3be96a82017-09-29 10:07:46 -0400212 # It is important that --no-log continues to work, as it is used by
213 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000214 parser.add_argument(
215 '--no-log', action='store_true',
216 help='Do not include the short log in the commit message')
217 parser.add_argument(
218 '--log-limit', type=int, default=100,
219 help='Trim log after N commits (default: %(default)s)')
220 parser.add_argument(
221 '--roll-to', default='origin/master',
222 help='Specify the new commit to roll to (default: %(default)s)')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500223 parser.add_argument(
224 '--key', action='append', default=[],
225 help='Regex(es) for dependency in DEPS file')
226 parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000227 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000228
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500229 if len(args.dep_path) > 1:
230 if args.roll_to != 'origin/master':
231 parser.error(
232 'Can\'t use multiple paths to roll simultaneously and --roll-to')
233 if args.key:
234 parser.error(
235 'Can\'t use multiple paths to roll simultaneously and --key')
maruel@chromium.org96550942015-05-22 18:46:51 +0000236 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000237 if args.reviewer:
238 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000239 for i, r in enumerate(reviewers):
240 if not '@' in r:
241 reviewers[i] = r + '@chromium.org'
242
Edward Lemurfaae42e2018-11-26 18:34:30 +0000243 gclient_root = gclient(['root'])
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400244 current_dir = os.getcwd()
Bruce Dawson37b62e52020-06-23 18:06:00 +0000245 dependencies = sorted(d.replace('\\', '/').rstrip('/') for d in args.dep_path)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500246 cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(
247 ' --key ' + k for k in args.key)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000248 try:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400249 if not args.ignore_dirty_tree and not is_pristine(current_dir):
250 raise Error(
251 'Ensure %s is clean first (no non-merged commits).' % current_dir)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500252 # First gather all the information without modifying anything, except for a
253 # git fetch.
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500254 rolls = {}
255 for dependency in dependencies:
Edward Lemurfaae42e2018-11-26 18:34:30 +0000256 full_dir = os.path.normpath(os.path.join(gclient_root, dependency))
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500257 if not os.path.isdir(full_dir):
Edward Lemurfaae42e2018-11-26 18:34:30 +0000258 print('Dependency %s not found at %s' % (dependency, full_dir))
259 full_dir = os.path.normpath(os.path.join(current_dir, dependency))
260 print('Will look for relative dependency at %s' % full_dir)
261 if not os.path.isdir(full_dir):
262 raise Error('Directory not found: %s (%s)' % (dependency, full_dir))
263
264 head, roll_to = calculate_roll(full_dir, dependency, args.roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500265 if roll_to == head:
266 if len(dependencies) == 1:
267 raise AlreadyRolledError('No revision to roll!')
268 print('%s: Already at latest commit %s' % (dependency, roll_to))
269 else:
270 print(
271 '%s: Rolling from %s to %s' % (dependency, head[:10], roll_to[:10]))
Edward Lemurfaae42e2018-11-26 18:34:30 +0000272 rolls[dependency] = (head, roll_to, full_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000273
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500274 logs = []
Edward Lemurfaae42e2018-11-26 18:34:30 +0000275 setdep_args = []
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000276 for dependency, (head, roll_to, full_dir) in sorted(rolls.items()):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500277 log = generate_commit_message(
278 full_dir, dependency, head, roll_to, args.no_log, args.log_limit)
279 logs.append(log)
Edward Lemurfaae42e2018-11-26 18:34:30 +0000280 setdep_args.extend(['-r', '{}@{}'.format(dependency, roll_to)])
Edward Lesmesc772cf72018-04-03 14:47:30 -0400281
Edward Lemurfaae42e2018-11-26 18:34:30 +0000282 gclient(['setdep'] + setdep_args)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500283
Robert Iannuccic1e65942018-10-18 17:59:45 +0000284 commit_msg = gen_commit_msg(logs, cmdline, reviewers, args.bug)
Edward Lemurfaae42e2018-11-26 18:34:30 +0000285 finalize(commit_msg, current_dir, rolls)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000286 except Error as e:
287 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700288 return 2 if isinstance(e, AlreadyRolledError) else 1
Corentin Wallez8732c0e2020-12-09 17:43:46 +0000289 except subprocess2.CalledProcessError:
Edward Lemur3c117942020-03-12 17:21:12 +0000290 return 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000291
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500292 print('')
293 if not reviewers:
294 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
295 print('to the commit description before emailing.')
296 print('')
297 print('Run:')
298 print(' git cl upload --send-mail')
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000299 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000300
sbc@chromium.org98201122015-04-22 20:21:34 +0000301
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000302if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000303 sys.exit(main())