blob: 4950c2de048e35f97e142f7a74bbe723949f414b [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 Lesmesc772cf72018-04-03 14:47:30 -040013import gclient_eval
szager@chromium.org03fd85b2014-06-09 23:43:33 +000014import os
15import re
maruel@chromium.org96550942015-05-22 18:46:51 +000016import subprocess
szager@chromium.org03fd85b2014-06-09 23:43:33 +000017import sys
18
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000019NEED_SHELL = sys.platform.startswith('win')
20
21
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000022class Error(Exception):
23 pass
24
25
smut7036c4f2016-06-09 14:28:48 -070026class AlreadyRolledError(Error):
27 pass
28
29
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000030def check_output(*args, **kwargs):
31 """subprocess.check_output() passing shell=True on Windows for git."""
32 kwargs.setdefault('shell', NEED_SHELL)
33 return subprocess.check_output(*args, **kwargs)
34
35
36def check_call(*args, **kwargs):
37 """subprocess.check_call() passing shell=True on Windows for git."""
38 kwargs.setdefault('shell', NEED_SHELL)
39 subprocess.check_call(*args, **kwargs)
40
41
maruel@chromium.org96550942015-05-22 18:46:51 +000042def is_pristine(root, merge_base='origin/master'):
43 """Returns True if a git checkout is pristine."""
44 cmd = ['git', 'diff', '--ignore-submodules', merge_base]
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000045 return not (check_output(cmd, cwd=root).strip() or
46 check_output(cmd + ['--cached'], cwd=root).strip())
szager@chromium.org03fd85b2014-06-09 23:43:33 +000047
48
maruel@chromium.org398ed342015-09-29 12:27:25 +000049def get_log_url(upstream_url, head, master):
50 """Returns an URL to read logs via a Web UI if applicable."""
51 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
52 # gitiles
53 return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
54 if upstream_url.startswith('https://github.com/'):
55 upstream_url = upstream_url.rstrip('/')
56 if upstream_url.endswith('.git'):
57 upstream_url = upstream_url[:-len('.git')]
58 return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
59 return None
60
61
62def should_show_log(upstream_url):
63 """Returns True if a short log should be included in the tree."""
64 # Skip logs for very active projects.
Eric Boren07efc5a2017-08-28 09:13:20 -040065 if upstream_url.endswith('/v8/v8.git'):
maruel@chromium.org398ed342015-09-29 12:27:25 +000066 return False
67 if 'webrtc' in upstream_url:
68 return False
69 return True
70
71
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050072def get_deps(root):
73 """Returns the path and the content of the DEPS file."""
74 deps_path = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000075 try:
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050076 with open(deps_path, 'rb') as f:
maruel@chromium.org96550942015-05-22 18:46:51 +000077 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000078 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000079 raise Error('Ensure the script is run in the directory '
80 'containing DEPS file.')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050081 return deps_path, deps_content
sbc@chromium.org98201122015-04-22 20:21:34 +000082
maruel@chromium.org96550942015-05-22 18:46:51 +000083
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050084def generate_commit_message(
85 full_dir, dependency, head, roll_to, no_log, log_limit):
86 """Creates the commit message for this specific roll."""
maruel@chromium.org398ed342015-09-29 12:27:25 +000087 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org398ed342015-09-29 12:27:25 +000088 upstream_url = check_output(
89 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
90 log_url = get_log_url(upstream_url, head, roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050091 cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +000092 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +000093 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -050094 cwd=full_dir).rstrip()
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +000095 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 -050096 lines = logs.splitlines()
97 cleaned_lines = [
98 l for l in lines
99 if not l.endswith('recipe-roller Roll recipe dependencies (trivial).')
100 ]
101 logs = '\n'.join(cleaned_lines) + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500102
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500103 nb_commits = len(lines)
104 rolls = nb_commits - len(cleaned_lines)
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500105 header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500106 dependency,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000107 commit_range,
108 nb_commits,
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500109 's' if nb_commits > 1 else '',
110 ('; %s trivial rolls' % rolls) if rolls else '')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000111 log_section = ''
112 if log_url:
113 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000114 log_section += '$ %s ' % ' '.join(cmd)
115 log_section += '--format=\'%ad %ae %s\'\n'
Eric Boren3be96a82017-09-29 10:07:46 -0400116 # It is important that --no-log continues to work, as it is used by
117 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000118 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500119 if len(cleaned_lines) > log_limit:
maruel@chromium.org398ed342015-09-29 12:27:25 +0000120 # Keep the first N log entries.
121 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
122 log_section += logs
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500123 return header + log_section
maruel@chromium.org398ed342015-09-29 12:27:25 +0000124
maruel@chromium.org96550942015-05-22 18:46:51 +0000125
Edward Lesmesc772cf72018-04-03 14:47:30 -0400126def calculate_roll(full_dir, dependency, gclient_dict, roll_to):
127 """Calculates the roll for a dependency by processing gclient_dict, and
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500128 fetching the dependency via git.
129 """
Edward Lesmesc772cf72018-04-03 14:47:30 -0400130 _, _, head = gclient_dict['deps'][dependency].partition('@')
131 if not head:
132 raise Error('%s is unpinned.' % dependency)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500133 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
134 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
135 return head, roll_to
136
137
138def gen_commit_msg(logs, cmdline, rolls, reviewers, bug):
139 """Returns the final commit message."""
140 commit_msg = ''
141 if len(logs) > 1:
142 commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
143 commit_msg += '\n\n'.join(logs)
Kenneth Russellebe839b2017-12-22 14:55:39 -0800144 commit_msg += '\nCreated with:\n ' + cmdline + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500145 commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
146 commit_msg += 'BUG=%s\n' % bug if bug else ''
147 return commit_msg
148
149
150def finalize(commit_msg, deps_path, deps_content, rolls):
151 """Edits the DEPS file, commits it, then uploads a CL."""
maruel@chromium.org96550942015-05-22 18:46:51 +0000152 print('Commit message:')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500153 print('\n'.join(' ' + i for i in commit_msg.splitlines()))
154
155 with open(deps_path, 'wb') as f:
maruel@chromium.org96550942015-05-22 18:46:51 +0000156 f.write(deps_content)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500157 root = os.path.dirname(deps_path)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000158 check_call(['git', 'add', 'DEPS'], cwd=root)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500159 check_call(['git', 'commit', '--quiet', '-m', commit_msg], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000160
161 # Pull the dependency to the right revision. This is surprising to users
162 # otherwise.
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500163 for dependency, (_head, roll_to) in sorted(rolls.iteritems()):
164 full_dir = os.path.normpath(
165 os.path.join(os.path.dirname(root), dependency))
166 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000167
168
maruel@chromium.org96550942015-05-22 18:46:51 +0000169def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000170 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000171 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000172 '--ignore-dirty-tree', action='store_true',
173 help='Roll anyways, even if there is a diff.')
174 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000175 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000176 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000177 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000178 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
Eric Boren3be96a82017-09-29 10:07:46 -0400179 # It is important that --no-log continues to work, as it is used by
180 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000181 parser.add_argument(
182 '--no-log', action='store_true',
183 help='Do not include the short log in the commit message')
184 parser.add_argument(
185 '--log-limit', type=int, default=100,
186 help='Trim log after N commits (default: %(default)s)')
187 parser.add_argument(
188 '--roll-to', default='origin/master',
189 help='Specify the new commit to roll to (default: %(default)s)')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500190 parser.add_argument(
191 '--key', action='append', default=[],
192 help='Regex(es) for dependency in DEPS file')
193 parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000194 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000195
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500196 if len(args.dep_path) > 1:
197 if args.roll_to != 'origin/master':
198 parser.error(
199 'Can\'t use multiple paths to roll simultaneously and --roll-to')
200 if args.key:
201 parser.error(
202 'Can\'t use multiple paths to roll simultaneously and --key')
maruel@chromium.org96550942015-05-22 18:46:51 +0000203 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000204 if args.reviewer:
205 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000206 for i, r in enumerate(reviewers):
207 if not '@' in r:
208 reviewers[i] = r + '@chromium.org'
209
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500210 root = os.getcwd()
211 dependencies = sorted(d.rstrip('/').rstrip('\\') for d in args.dep_path)
212 cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(
213 ' --key ' + k for k in args.key)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000214 try:
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500215 if not args.ignore_dirty_tree and not is_pristine(root):
216 raise Error('Ensure %s is clean first (no non-merged commits).' % root)
217 # First gather all the information without modifying anything, except for a
218 # git fetch.
219 deps_path, deps_content = get_deps(root)
Edward Lesmesc772cf72018-04-03 14:47:30 -0400220 gclient_dict = gclient_eval.Parse(deps_content, True, True, deps_path)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500221 rolls = {}
222 for dependency in dependencies:
223 full_dir = os.path.normpath(
224 os.path.join(os.path.dirname(root), dependency))
225 if not os.path.isdir(full_dir):
226 raise Error('Directory not found: %s (%s)' % (dependency, full_dir))
227 head, roll_to = calculate_roll(
Edward Lesmesc772cf72018-04-03 14:47:30 -0400228 full_dir, dependency, gclient_dict, args.roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500229 if roll_to == head:
230 if len(dependencies) == 1:
231 raise AlreadyRolledError('No revision to roll!')
232 print('%s: Already at latest commit %s' % (dependency, roll_to))
233 else:
234 print(
235 '%s: Rolling from %s to %s' % (dependency, head[:10], roll_to[:10]))
236 rolls[dependency] = (head, roll_to)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000237
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500238 logs = []
239 for dependency, (head, roll_to) in sorted(rolls.iteritems()):
240 full_dir = os.path.normpath(
241 os.path.join(os.path.dirname(root), dependency))
242 log = generate_commit_message(
243 full_dir, dependency, head, roll_to, args.no_log, args.log_limit)
244 logs.append(log)
Edward Lesmesc772cf72018-04-03 14:47:30 -0400245 gclient_eval.SetRevision(gclient_dict, dependency, roll_to)
246
247 deps_content = gclient_eval.RenderDEPSFile(gclient_dict)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500248
249 commit_msg = gen_commit_msg(logs, cmdline, rolls, reviewers, args.bug)
250 finalize(commit_msg, deps_path, deps_content, rolls)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000251 except Error as e:
252 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700253 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000254
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500255 print('')
256 if not reviewers:
257 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
258 print('to the commit description before emailing.')
259 print('')
260 print('Run:')
261 print(' git cl upload --send-mail')
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000262 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000263
sbc@chromium.org98201122015-04-22 20:21:34 +0000264
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000265if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000266 sys.exit(main())