blob: 174805458903228c79b4f6d62e548e837ecd63af [file] [log] [blame]
szager@chromium.org03fd85b2014-06-09 23:43:33 +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
9script will always roll to the tip of to origin/master.
szager@chromium.org03fd85b2014-06-09 23:43:33 +000010"""
11
sbc@chromium.org30e5b232015-06-01 18:06:59 +000012import argparse
Edward Lesmesa1df57c2018-04-03 20:00:07 -040013import collections
Edward Lesmesc772cf72018-04-03 14:47:30 -040014import gclient_eval
szager@chromium.org03fd85b2014-06-09 23:43:33 +000015import os
16import re
maruel@chromium.org96550942015-05-22 18:46:51 +000017import subprocess
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
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000025class Error(Exception):
26 pass
27
28
smut7036c4f2016-06-09 14:28:48 -070029class AlreadyRolledError(Error):
30 pass
31
32
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000033def check_output(*args, **kwargs):
34 """subprocess.check_output() passing shell=True on Windows for git."""
35 kwargs.setdefault('shell', NEED_SHELL)
36 return subprocess.check_output(*args, **kwargs)
37
38
39def check_call(*args, **kwargs):
40 """subprocess.check_call() passing shell=True on Windows for git."""
41 kwargs.setdefault('shell', NEED_SHELL)
42 subprocess.check_call(*args, **kwargs)
43
44
maruel@chromium.org96550942015-05-22 18:46:51 +000045def is_pristine(root, merge_base='origin/master'):
46 """Returns True if a git checkout is pristine."""
47 cmd = ['git', 'diff', '--ignore-submodules', merge_base]
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000048 return not (check_output(cmd, cwd=root).strip() or
49 check_output(cmd + ['--cached'], cwd=root).strip())
szager@chromium.org03fd85b2014-06-09 23:43:33 +000050
51
maruel@chromium.org398ed342015-09-29 12:27:25 +000052def get_log_url(upstream_url, head, master):
53 """Returns an URL to read logs via a Web UI if applicable."""
54 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
55 # gitiles
56 return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
57 if upstream_url.startswith('https://github.com/'):
58 upstream_url = upstream_url.rstrip('/')
59 if upstream_url.endswith('.git'):
60 upstream_url = upstream_url[:-len('.git')]
61 return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
62 return None
63
64
65def should_show_log(upstream_url):
66 """Returns True if a short log should be included in the tree."""
67 # Skip logs for very active projects.
Eric Boren07efc5a2017-08-28 09:13:20 -040068 if upstream_url.endswith('/v8/v8.git'):
maruel@chromium.org398ed342015-09-29 12:27:25 +000069 return False
70 if 'webrtc' in upstream_url:
71 return False
72 return True
73
74
Edward Lemurfaae42e2018-11-26 18:34:30 +000075def gclient(args):
76 """Executes gclient with the given args and returns the stdout."""
77 return check_output([sys.executable, GCLIENT_PATH] + args).strip()
sbc@chromium.org98201122015-04-22 20:21:34 +000078
maruel@chromium.org96550942015-05-22 18:46:51 +000079
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050080def generate_commit_message(
81 full_dir, dependency, head, roll_to, no_log, log_limit):
82 """Creates the commit message for this specific roll."""
maruel@chromium.org398ed342015-09-29 12:27:25 +000083 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org398ed342015-09-29 12:27:25 +000084 upstream_url = check_output(
85 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
86 log_url = get_log_url(upstream_url, head, roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050087 cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +000088 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +000089 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -050090 cwd=full_dir).rstrip()
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +000091 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 -050092 lines = logs.splitlines()
93 cleaned_lines = [
94 l for l in lines
Andrii Shyshkalove30d0512019-04-02 17:40:52 +000095 if not l.endswith('Roll recipe dependencies (trivial).')
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -050096 ]
97 logs = '\n'.join(cleaned_lines) + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050098
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -050099 nb_commits = len(lines)
100 rolls = nb_commits - len(cleaned_lines)
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500101 header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500102 dependency,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000103 commit_range,
104 nb_commits,
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500105 's' if nb_commits > 1 else '',
106 ('; %s trivial rolls' % rolls) if rolls else '')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000107 log_section = ''
108 if log_url:
109 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000110 log_section += '$ %s ' % ' '.join(cmd)
111 log_section += '--format=\'%ad %ae %s\'\n'
Eric Boren3be96a82017-09-29 10:07:46 -0400112 # It is important that --no-log continues to work, as it is used by
113 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000114 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500115 if len(cleaned_lines) > log_limit:
Marc-Antoine Ruel6ce18222019-01-16 21:36:36 +0000116 # Keep the first N/2 log entries and last N/2 entries.
117 lines = logs.splitlines(True)
118 lines = lines[:log_limit/2] + ['(...)\n'] + lines[-log_limit/2:]
119 logs = ''.join(lines)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000120 log_section += logs
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500121 return header + log_section
maruel@chromium.org398ed342015-09-29 12:27:25 +0000122
maruel@chromium.org96550942015-05-22 18:46:51 +0000123
Edward Lemurfaae42e2018-11-26 18:34:30 +0000124def calculate_roll(full_dir, dependency, roll_to):
Edward Lesmesc772cf72018-04-03 14:47:30 -0400125 """Calculates the roll for a dependency by processing gclient_dict, and
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500126 fetching the dependency via git.
127 """
Edward Lemurfaae42e2018-11-26 18:34:30 +0000128 head = gclient(['getdep', '-r', dependency])
Edward Lesmesc772cf72018-04-03 14:47:30 -0400129 if not head:
130 raise Error('%s is unpinned.' % dependency)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500131 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
132 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
133 return head, roll_to
134
135
Robert Iannuccic1e65942018-10-18 17:59:45 +0000136def gen_commit_msg(logs, cmdline, reviewers, bug):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500137 """Returns the final commit message."""
138 commit_msg = ''
139 if len(logs) > 1:
140 commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
141 commit_msg += '\n\n'.join(logs)
Kenneth Russellebe839b2017-12-22 14:55:39 -0800142 commit_msg += '\nCreated with:\n ' + cmdline + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500143 commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
Robert Iannuccic1e65942018-10-18 17:59:45 +0000144 commit_msg += '\nBug: %s\n' % bug if bug else ''
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500145 return commit_msg
146
147
Edward Lemurfaae42e2018-11-26 18:34:30 +0000148def finalize(commit_msg, current_dir, rolls):
149 """Commits changes to the DEPS file, then uploads a CL."""
maruel@chromium.org96550942015-05-22 18:46:51 +0000150 print('Commit message:')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500151 print('\n'.join(' ' + i for i in commit_msg.splitlines()))
152
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400153 check_call(['git', 'add', 'DEPS'], cwd=current_dir)
154 check_call(['git', 'commit', '--quiet', '-m', commit_msg], cwd=current_dir)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000155
156 # Pull the dependency to the right revision. This is surprising to users
157 # otherwise.
Edward Lemurfaae42e2018-11-26 18:34:30 +0000158 for _head, roll_to, full_dir in sorted(rolls.itervalues()):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500159 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000160
161
maruel@chromium.org96550942015-05-22 18:46:51 +0000162def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000163 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000164 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000165 '--ignore-dirty-tree', action='store_true',
166 help='Roll anyways, even if there is a diff.')
167 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000168 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000169 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000170 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000171 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
Eric Boren3be96a82017-09-29 10:07:46 -0400172 # It is important that --no-log continues to work, as it is used by
173 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000174 parser.add_argument(
175 '--no-log', action='store_true',
176 help='Do not include the short log in the commit message')
177 parser.add_argument(
178 '--log-limit', type=int, default=100,
179 help='Trim log after N commits (default: %(default)s)')
180 parser.add_argument(
181 '--roll-to', default='origin/master',
182 help='Specify the new commit to roll to (default: %(default)s)')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500183 parser.add_argument(
184 '--key', action='append', default=[],
185 help='Regex(es) for dependency in DEPS file')
186 parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000187 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000188
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500189 if len(args.dep_path) > 1:
190 if args.roll_to != 'origin/master':
191 parser.error(
192 'Can\'t use multiple paths to roll simultaneously and --roll-to')
193 if args.key:
194 parser.error(
195 'Can\'t use multiple paths to roll simultaneously and --key')
maruel@chromium.org96550942015-05-22 18:46:51 +0000196 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000197 if args.reviewer:
198 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000199 for i, r in enumerate(reviewers):
200 if not '@' in r:
201 reviewers[i] = r + '@chromium.org'
202
Edward Lemurfaae42e2018-11-26 18:34:30 +0000203 gclient_root = gclient(['root'])
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400204 current_dir = os.getcwd()
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500205 dependencies = sorted(d.rstrip('/').rstrip('\\') for d in args.dep_path)
206 cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(
207 ' --key ' + k for k in args.key)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000208 try:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400209 if not args.ignore_dirty_tree and not is_pristine(current_dir):
210 raise Error(
211 'Ensure %s is clean first (no non-merged commits).' % current_dir)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500212 # First gather all the information without modifying anything, except for a
213 # git fetch.
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500214 rolls = {}
215 for dependency in dependencies:
Edward Lemurfaae42e2018-11-26 18:34:30 +0000216 full_dir = os.path.normpath(os.path.join(gclient_root, dependency))
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500217 if not os.path.isdir(full_dir):
Edward Lemurfaae42e2018-11-26 18:34:30 +0000218 print('Dependency %s not found at %s' % (dependency, full_dir))
219 full_dir = os.path.normpath(os.path.join(current_dir, dependency))
220 print('Will look for relative dependency at %s' % full_dir)
221 if not os.path.isdir(full_dir):
222 raise Error('Directory not found: %s (%s)' % (dependency, full_dir))
223
224 head, roll_to = calculate_roll(full_dir, dependency, args.roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500225 if roll_to == head:
226 if len(dependencies) == 1:
227 raise AlreadyRolledError('No revision to roll!')
228 print('%s: Already at latest commit %s' % (dependency, roll_to))
229 else:
230 print(
231 '%s: Rolling from %s to %s' % (dependency, head[:10], roll_to[:10]))
Edward Lemurfaae42e2018-11-26 18:34:30 +0000232 rolls[dependency] = (head, roll_to, full_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000233
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500234 logs = []
Edward Lemurfaae42e2018-11-26 18:34:30 +0000235 setdep_args = []
236 for dependency, (head, roll_to, full_dir) in sorted(rolls.iteritems()):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500237 log = generate_commit_message(
238 full_dir, dependency, head, roll_to, args.no_log, args.log_limit)
239 logs.append(log)
Edward Lemurfaae42e2018-11-26 18:34:30 +0000240 setdep_args.extend(['-r', '{}@{}'.format(dependency, roll_to)])
Edward Lesmesc772cf72018-04-03 14:47:30 -0400241
Edward Lemurfaae42e2018-11-26 18:34:30 +0000242 gclient(['setdep'] + setdep_args)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500243
Robert Iannuccic1e65942018-10-18 17:59:45 +0000244 commit_msg = gen_commit_msg(logs, cmdline, reviewers, args.bug)
Edward Lemurfaae42e2018-11-26 18:34:30 +0000245 finalize(commit_msg, current_dir, rolls)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000246 except Error as e:
247 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700248 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000249
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500250 print('')
251 if not reviewers:
252 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
253 print('to the commit description before emailing.')
254 print('')
255 print('Run:')
256 print(' git cl upload --send-mail')
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000257 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000258
sbc@chromium.org98201122015-04-22 20:21:34 +0000259
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000260if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000261 sys.exit(main())