blob: ddd13cbca57ac0b897a3637c55546c90ec9a7a9a [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')
21
22
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000023class Error(Exception):
24 pass
25
26
smut7036c4f2016-06-09 14:28:48 -070027class AlreadyRolledError(Error):
28 pass
29
30
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000031def check_output(*args, **kwargs):
32 """subprocess.check_output() passing shell=True on Windows for git."""
33 kwargs.setdefault('shell', NEED_SHELL)
34 return subprocess.check_output(*args, **kwargs)
35
36
37def check_call(*args, **kwargs):
38 """subprocess.check_call() passing shell=True on Windows for git."""
39 kwargs.setdefault('shell', NEED_SHELL)
40 subprocess.check_call(*args, **kwargs)
41
42
maruel@chromium.org96550942015-05-22 18:46:51 +000043def is_pristine(root, merge_base='origin/master'):
44 """Returns True if a git checkout is pristine."""
45 cmd = ['git', 'diff', '--ignore-submodules', merge_base]
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000046 return not (check_output(cmd, cwd=root).strip() or
47 check_output(cmd + ['--cached'], cwd=root).strip())
szager@chromium.org03fd85b2014-06-09 23:43:33 +000048
49
maruel@chromium.org398ed342015-09-29 12:27:25 +000050def get_log_url(upstream_url, head, master):
51 """Returns an URL to read logs via a Web UI if applicable."""
52 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
53 # gitiles
54 return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
55 if upstream_url.startswith('https://github.com/'):
56 upstream_url = upstream_url.rstrip('/')
57 if upstream_url.endswith('.git'):
58 upstream_url = upstream_url[:-len('.git')]
59 return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
60 return None
61
62
63def should_show_log(upstream_url):
64 """Returns True if a short log should be included in the tree."""
65 # Skip logs for very active projects.
Eric Boren07efc5a2017-08-28 09:13:20 -040066 if upstream_url.endswith('/v8/v8.git'):
maruel@chromium.org398ed342015-09-29 12:27:25 +000067 return False
68 if 'webrtc' in upstream_url:
69 return False
70 return True
71
72
Edward Lesmes3f277fc2018-04-06 15:32:51 -040073def get_gclient_root():
Eric Boren5888d6f2018-04-09 13:20:39 -040074 gclient = os.path.join(
75 os.path.dirname(os.path.abspath(__file__)), 'gclient.py')
76 return check_output([sys.executable, gclient, 'root']).strip()
Edward Lesmes3f277fc2018-04-06 15:32:51 -040077
78
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050079def get_deps(root):
80 """Returns the path and the content of the DEPS file."""
81 deps_path = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000082 try:
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050083 with open(deps_path, 'rb') as f:
maruel@chromium.org96550942015-05-22 18:46:51 +000084 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000085 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000086 raise Error('Ensure the script is run in the directory '
87 'containing DEPS file.')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050088 return deps_path, deps_content
sbc@chromium.org98201122015-04-22 20:21:34 +000089
maruel@chromium.org96550942015-05-22 18:46:51 +000090
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050091def generate_commit_message(
92 full_dir, dependency, head, roll_to, no_log, log_limit):
93 """Creates the commit message for this specific roll."""
maruel@chromium.org398ed342015-09-29 12:27:25 +000094 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org398ed342015-09-29 12:27:25 +000095 upstream_url = check_output(
96 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
97 log_url = get_log_url(upstream_url, head, roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -050098 cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +000099 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000100 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500101 cwd=full_dir).rstrip()
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000102 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 -0500103 lines = logs.splitlines()
104 cleaned_lines = [
105 l for l in lines
106 if not l.endswith('recipe-roller Roll recipe dependencies (trivial).')
107 ]
108 logs = '\n'.join(cleaned_lines) + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500109
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500110 nb_commits = len(lines)
111 rolls = nb_commits - len(cleaned_lines)
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500112 header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500113 dependency,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000114 commit_range,
115 nb_commits,
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500116 's' if nb_commits > 1 else '',
117 ('; %s trivial rolls' % rolls) if rolls else '')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000118 log_section = ''
119 if log_url:
120 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000121 log_section += '$ %s ' % ' '.join(cmd)
122 log_section += '--format=\'%ad %ae %s\'\n'
Eric Boren3be96a82017-09-29 10:07:46 -0400123 # It is important that --no-log continues to work, as it is used by
124 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000125 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500126 if len(cleaned_lines) > log_limit:
maruel@chromium.org398ed342015-09-29 12:27:25 +0000127 # Keep the first N log entries.
128 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
129 log_section += logs
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500130 return header + log_section
maruel@chromium.org398ed342015-09-29 12:27:25 +0000131
maruel@chromium.org96550942015-05-22 18:46:51 +0000132
Edward Lesmesc772cf72018-04-03 14:47:30 -0400133def calculate_roll(full_dir, dependency, gclient_dict, roll_to):
134 """Calculates the roll for a dependency by processing gclient_dict, and
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500135 fetching the dependency via git.
136 """
Edward Lesmesa1df57c2018-04-03 20:00:07 -0400137 if dependency not in gclient_dict['deps']:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400138 raise Error(
139 '%s is not in the "deps" section of the DEPS file.' % dependency)
Edward Lesmesa1df57c2018-04-03 20:00:07 -0400140
141 head = None
142 if isinstance(gclient_dict['deps'][dependency], basestring):
143 _, _, head = gclient_dict['deps'][dependency].partition('@')
144 elif (isinstance(gclient_dict['deps'][dependency], collections.Mapping)
145 and 'url' in gclient_dict['deps'][dependency]):
146 _, _, head = gclient_dict['deps'][dependency]['url'].partition('@')
147 else:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400148 raise Error('%s is not a valid git dependency.' % dependency)
Edward Lesmesa1df57c2018-04-03 20:00:07 -0400149
Edward Lesmesc772cf72018-04-03 14:47:30 -0400150 if not head:
151 raise Error('%s is unpinned.' % dependency)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500152 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
153 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
154 return head, roll_to
155
156
157def gen_commit_msg(logs, cmdline, rolls, reviewers, bug):
158 """Returns the final commit message."""
159 commit_msg = ''
160 if len(logs) > 1:
161 commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
162 commit_msg += '\n\n'.join(logs)
Kenneth Russellebe839b2017-12-22 14:55:39 -0800163 commit_msg += '\nCreated with:\n ' + cmdline + '\n'
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500164 commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
165 commit_msg += 'BUG=%s\n' % bug if bug else ''
166 return commit_msg
167
168
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400169def finalize(commit_msg, deps_path, deps_content, rolls, is_relative, root_dir):
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500170 """Edits the DEPS file, commits it, then uploads a CL."""
maruel@chromium.org96550942015-05-22 18:46:51 +0000171 print('Commit message:')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500172 print('\n'.join(' ' + i for i in commit_msg.splitlines()))
173
174 with open(deps_path, 'wb') as f:
maruel@chromium.org96550942015-05-22 18:46:51 +0000175 f.write(deps_content)
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400176 current_dir = os.path.dirname(deps_path)
177 check_call(['git', 'add', 'DEPS'], cwd=current_dir)
178 check_call(['git', 'commit', '--quiet', '-m', commit_msg], cwd=current_dir)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000179
180 # Pull the dependency to the right revision. This is surprising to users
181 # otherwise.
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500182 for dependency, (_head, roll_to) in sorted(rolls.iteritems()):
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400183 full_dir = os.path.normpath(os.path.join(root_dir, dependency))
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500184 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000185
186
maruel@chromium.org96550942015-05-22 18:46:51 +0000187def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000188 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000189 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000190 '--ignore-dirty-tree', action='store_true',
191 help='Roll anyways, even if there is a diff.')
192 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000193 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000194 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000195 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000196 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
Eric Boren3be96a82017-09-29 10:07:46 -0400197 # It is important that --no-log continues to work, as it is used by
198 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000199 parser.add_argument(
200 '--no-log', action='store_true',
201 help='Do not include the short log in the commit message')
202 parser.add_argument(
203 '--log-limit', type=int, default=100,
204 help='Trim log after N commits (default: %(default)s)')
205 parser.add_argument(
206 '--roll-to', default='origin/master',
207 help='Specify the new commit to roll to (default: %(default)s)')
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500208 parser.add_argument(
209 '--key', action='append', default=[],
210 help='Regex(es) for dependency in DEPS file')
211 parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000212 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000213
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500214 if len(args.dep_path) > 1:
215 if args.roll_to != 'origin/master':
216 parser.error(
217 'Can\'t use multiple paths to roll simultaneously and --roll-to')
218 if args.key:
219 parser.error(
220 'Can\'t use multiple paths to roll simultaneously and --key')
maruel@chromium.org96550942015-05-22 18:46:51 +0000221 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000222 if args.reviewer:
223 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000224 for i, r in enumerate(reviewers):
225 if not '@' in r:
226 reviewers[i] = r + '@chromium.org'
227
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400228 gclient_root = get_gclient_root()
229 current_dir = os.getcwd()
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500230 dependencies = sorted(d.rstrip('/').rstrip('\\') for d in args.dep_path)
231 cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(
232 ' --key ' + k for k in args.key)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000233 try:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400234 if not args.ignore_dirty_tree and not is_pristine(current_dir):
235 raise Error(
236 'Ensure %s is clean first (no non-merged commits).' % current_dir)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500237 # First gather all the information without modifying anything, except for a
238 # git fetch.
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400239 deps_path, deps_content = get_deps(current_dir)
Edward Lesmesc772cf72018-04-03 14:47:30 -0400240 gclient_dict = gclient_eval.Parse(deps_content, True, True, deps_path)
Eric Boren0eb39562018-04-05 11:34:09 -0400241 is_relative = gclient_dict.get('use_relative_paths', False)
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400242 root_dir = current_dir if is_relative else gclient_root
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500243 rolls = {}
244 for dependency in dependencies:
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400245 full_dir = os.path.normpath(os.path.join(root_dir, dependency))
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500246 if not os.path.isdir(full_dir):
247 raise Error('Directory not found: %s (%s)' % (dependency, full_dir))
248 head, roll_to = calculate_roll(
Edward Lesmesc772cf72018-04-03 14:47:30 -0400249 full_dir, dependency, gclient_dict, args.roll_to)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500250 if roll_to == head:
251 if len(dependencies) == 1:
252 raise AlreadyRolledError('No revision to roll!')
253 print('%s: Already at latest commit %s' % (dependency, roll_to))
254 else:
255 print(
256 '%s: Rolling from %s to %s' % (dependency, head[:10], roll_to[:10]))
257 rolls[dependency] = (head, roll_to)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000258
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500259 logs = []
260 for dependency, (head, roll_to) in sorted(rolls.iteritems()):
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400261 full_dir = os.path.normpath(os.path.join(root_dir, dependency))
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500262 log = generate_commit_message(
263 full_dir, dependency, head, roll_to, args.no_log, args.log_limit)
264 logs.append(log)
Edward Lesmesc772cf72018-04-03 14:47:30 -0400265 gclient_eval.SetRevision(gclient_dict, dependency, roll_to)
266
267 deps_content = gclient_eval.RenderDEPSFile(gclient_dict)
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500268
269 commit_msg = gen_commit_msg(logs, cmdline, rolls, reviewers, args.bug)
Edward Lesmes3f277fc2018-04-06 15:32:51 -0400270 finalize(commit_msg, deps_path, deps_content, rolls, is_relative, root_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000271 except Error as e:
272 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700273 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000274
Marc-Antoine Ruel85a8c102017-12-12 15:42:25 -0500275 print('')
276 if not reviewers:
277 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
278 print('to the commit description before emailing.')
279 print('')
280 print('Run:')
281 print(' git cl upload --send-mail')
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000282 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000283
sbc@chromium.org98201122015-04-22 20:21:34 +0000284
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000285if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000286 sys.exit(main())