blob: f5c25b97e63e9dc50bc19f7d0b63f655ee6b9ab3 [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
szager@chromium.org03fd85b2014-06-09 23:43:33 +000013import os
14import re
maruel@chromium.org96550942015-05-22 18:46:51 +000015import subprocess
szager@chromium.org03fd85b2014-06-09 23:43:33 +000016import sys
17
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000018NEED_SHELL = sys.platform.startswith('win')
19
20
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000021class Error(Exception):
22 pass
23
24
smut7036c4f2016-06-09 14:28:48 -070025class AlreadyRolledError(Error):
26 pass
27
28
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000029def check_output(*args, **kwargs):
30 """subprocess.check_output() passing shell=True on Windows for git."""
31 kwargs.setdefault('shell', NEED_SHELL)
32 return subprocess.check_output(*args, **kwargs)
33
34
35def check_call(*args, **kwargs):
36 """subprocess.check_call() passing shell=True on Windows for git."""
37 kwargs.setdefault('shell', NEED_SHELL)
38 subprocess.check_call(*args, **kwargs)
39
40
maruel@chromium.org96550942015-05-22 18:46:51 +000041def is_pristine(root, merge_base='origin/master'):
42 """Returns True if a git checkout is pristine."""
43 cmd = ['git', 'diff', '--ignore-submodules', merge_base]
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000044 return not (check_output(cmd, cwd=root).strip() or
45 check_output(cmd + ['--cached'], cwd=root).strip())
szager@chromium.org03fd85b2014-06-09 23:43:33 +000046
47
maruel@chromium.org398ed342015-09-29 12:27:25 +000048def get_log_url(upstream_url, head, master):
49 """Returns an URL to read logs via a Web UI if applicable."""
50 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
51 # gitiles
52 return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
53 if upstream_url.startswith('https://github.com/'):
54 upstream_url = upstream_url.rstrip('/')
55 if upstream_url.endswith('.git'):
56 upstream_url = upstream_url[:-len('.git')]
57 return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
58 return None
59
60
61def should_show_log(upstream_url):
62 """Returns True if a short log should be included in the tree."""
63 # Skip logs for very active projects.
Eric Boren07efc5a2017-08-28 09:13:20 -040064 if upstream_url.endswith('/v8/v8.git'):
maruel@chromium.org398ed342015-09-29 12:27:25 +000065 return False
66 if 'webrtc' in upstream_url:
67 return False
68 return True
69
70
smut@google.com02d20872015-11-14 00:46:41 +000071def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit,
72 ignore_dirty_tree=False):
maruel@chromium.org96550942015-05-22 18:46:51 +000073 deps = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000074 try:
maruel@chromium.org96550942015-05-22 18:46:51 +000075 with open(deps, 'rb') as f:
76 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000077 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000078 raise Error('Ensure the script is run in the directory '
79 'containing DEPS file.')
sbc@chromium.org98201122015-04-22 20:21:34 +000080
smut@google.com02d20872015-11-14 00:46:41 +000081 if not ignore_dirty_tree and not is_pristine(root):
brucedawson@chromium.org8a6495c2015-12-07 21:46:41 +000082 raise Error('Ensure %s is clean first (no non-merged commits).' % root)
maruel@chromium.org96550942015-05-22 18:46:51 +000083
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000084 full_dir = os.path.normpath(os.path.join(os.path.dirname(root), deps_dir))
sbc@chromium.org30e5b232015-06-01 18:06:59 +000085 if not os.path.isdir(full_dir):
brucedawson@chromium.org8a6495c2015-12-07 21:46:41 +000086 raise Error('Directory not found: %s (%s)' % (deps_dir, full_dir))
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000087 head = check_output(['git', 'rev-parse', 'HEAD'], cwd=full_dir).strip()
maruel@chromium.org96550942015-05-22 18:46:51 +000088
89 if not head in deps_content:
90 print('Warning: %s is not checked out at the expected revision in DEPS' %
91 deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000092 if key is None:
93 print("Warning: no key specified. Using '%s'." % deps_dir)
94 key = deps_dir
95
maruel@chromium.org96550942015-05-22 18:46:51 +000096 # It happens if the user checked out a branch in the dependency by himself.
97 # Fall back to reading the DEPS to figure out the original commit.
98 for i in deps_content.splitlines():
rohitrao@chromium.orgd4ef5992016-02-18 00:05:22 +000099 m = re.match(r'\s+"' + key + '":.*"([a-z0-9]{40})",', i)
maruel@chromium.org96550942015-05-22 18:46:51 +0000100 if m:
101 head = m.group(1)
102 break
103 else:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000104 raise Error('Expected to find commit %s for %s in DEPS' % (head, key))
maruel@chromium.org96550942015-05-22 18:46:51 +0000105
106 print('Found old revision %s' % head)
107
maruel@chromium.org398ed342015-09-29 12:27:25 +0000108 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
109 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
110 print('Found new revision %s' % roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000111
maruel@chromium.org398ed342015-09-29 12:27:25 +0000112 if roll_to == head:
smut7036c4f2016-06-09 14:28:48 -0700113 raise AlreadyRolledError('No revision to roll!')
maruel@chromium.org96550942015-05-22 18:46:51 +0000114
maruel@chromium.org398ed342015-09-29 12:27:25 +0000115 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org96550942015-05-22 18:46:51 +0000116
maruel@chromium.org398ed342015-09-29 12:27:25 +0000117 upstream_url = check_output(
118 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
119 log_url = get_log_url(upstream_url, head, roll_to)
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000120 cmd = [
121 'git', 'log', commit_range, '--date=short', '--no-merges',
122 ]
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000123 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000124 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500125 cwd=full_dir).rstrip()
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000126 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 -0500127 lines = logs.splitlines()
128 cleaned_lines = [
129 l for l in lines
130 if not l.endswith('recipe-roller Roll recipe dependencies (trivial).')
131 ]
132 logs = '\n'.join(cleaned_lines) + '\n'
133 nb_commits = len(lines)
134 rolls = nb_commits - len(cleaned_lines)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000135
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500136 header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
maruel@chromium.org398ed342015-09-29 12:27:25 +0000137 deps_dir,
138 commit_range,
139 nb_commits,
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500140 's' if nb_commits > 1 else '',
141 ('; %s trivial rolls' % rolls) if rolls else '')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000142
143 log_section = ''
144 if log_url:
145 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000146 log_section += '$ %s ' % ' '.join(cmd)
147 log_section += '--format=\'%ad %ae %s\'\n'
Eric Boren3be96a82017-09-29 10:07:46 -0400148 # It is important that --no-log continues to work, as it is used by
149 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000150 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500151 if len(cleaned_lines) > log_limit:
maruel@chromium.org398ed342015-09-29 12:27:25 +0000152 # Keep the first N log entries.
153 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
154 log_section += logs
Achuith Bhandarkarf6b946d2017-11-29 16:54:53 -0800155 log_section += '\n\nCreated with:\n roll-dep ' + deps_dir
156 if key:
157 log_section += ' ' + key
158 log_section += '\n'
maruel@chromium.org398ed342015-09-29 12:27:25 +0000159
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000160 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
161 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000162 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000163
164 print('Commit message:')
165 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000166 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000167 with open(deps, 'wb') as f:
168 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000169 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000170 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
171
172 # Pull the dependency to the right revision. This is surprising to users
173 # otherwise.
174 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
175
maruel@chromium.org96550942015-05-22 18:46:51 +0000176 print('')
177 if not reviewers:
178 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
179 print('to the commit description before emailing.')
180 print('')
181 print('Run:')
182 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000183
184
maruel@chromium.org96550942015-05-22 18:46:51 +0000185def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000186 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000187 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000188 '--ignore-dirty-tree', action='store_true',
189 help='Roll anyways, even if there is a diff.')
190 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000191 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000192 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000193 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000194 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
Eric Boren3be96a82017-09-29 10:07:46 -0400195 # It is important that --no-log continues to work, as it is used by
196 # internal -> external rollers. Please do not remove or break it.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000197 parser.add_argument(
198 '--no-log', action='store_true',
199 help='Do not include the short log in the commit message')
200 parser.add_argument(
201 '--log-limit', type=int, default=100,
202 help='Trim log after N commits (default: %(default)s)')
203 parser.add_argument(
204 '--roll-to', default='origin/master',
205 help='Specify the new commit to roll to (default: %(default)s)')
206 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000207 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000208 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000209 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000210
211 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000212 if args.reviewer:
213 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000214 for i, r in enumerate(reviewers):
215 if not '@' in r:
216 reviewers[i] = r + '@chromium.org'
217
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000218 try:
219 roll(
220 os.getcwd(),
maruel@chromium.org261fa7d2015-11-23 19:20:09 +0000221 args.dep_path.rstrip('/').rstrip('\\'),
maruel@chromium.org398ed342015-09-29 12:27:25 +0000222 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000223 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000224 reviewers,
225 args.bug,
226 args.no_log,
smut@google.com02d20872015-11-14 00:46:41 +0000227 args.log_limit,
228 args.ignore_dirty_tree)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000229
230 except Error as e:
231 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700232 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000233
234 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000235
sbc@chromium.org98201122015-04-22 20:21:34 +0000236
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000237if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000238 sys.exit(main())