blob: 23ff130a05f844217bc341f8a6bd6dd31ccf0d98 [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'
maruel@chromium.org398ed342015-09-29 12:27:25 +0000148 if not no_log and should_show_log(upstream_url):
Marc-Antoine Ruel51104fe2017-03-01 17:57:41 -0500149 if len(cleaned_lines) > log_limit:
maruel@chromium.org398ed342015-09-29 12:27:25 +0000150 # Keep the first N log entries.
151 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
152 log_section += logs
Marc-Antoine Ruel22e7a272017-02-07 20:09:37 -0500153 log_section += '\n\nCreated with:\n roll-dep %s\n' % deps_dir
maruel@chromium.org398ed342015-09-29 12:27:25 +0000154
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000155 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
156 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000157 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000158
159 print('Commit message:')
160 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000161 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000162 with open(deps, 'wb') as f:
163 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000164 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000165 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
166
167 # Pull the dependency to the right revision. This is surprising to users
168 # otherwise.
169 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
170
maruel@chromium.org96550942015-05-22 18:46:51 +0000171 print('')
172 if not reviewers:
173 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
174 print('to the commit description before emailing.')
175 print('')
176 print('Run:')
177 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000178
179
maruel@chromium.org96550942015-05-22 18:46:51 +0000180def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000181 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000182 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000183 '--ignore-dirty-tree', action='store_true',
184 help='Roll anyways, even if there is a diff.')
185 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000186 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000187 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000188 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000189 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
190 parser.add_argument(
191 '--no-log', action='store_true',
192 help='Do not include the short log in the commit message')
193 parser.add_argument(
194 '--log-limit', type=int, default=100,
195 help='Trim log after N commits (default: %(default)s)')
196 parser.add_argument(
197 '--roll-to', default='origin/master',
198 help='Specify the new commit to roll to (default: %(default)s)')
199 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000200 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000201 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000202 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000203
204 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000205 if args.reviewer:
206 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000207 for i, r in enumerate(reviewers):
208 if not '@' in r:
209 reviewers[i] = r + '@chromium.org'
210
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000211 try:
212 roll(
213 os.getcwd(),
maruel@chromium.org261fa7d2015-11-23 19:20:09 +0000214 args.dep_path.rstrip('/').rstrip('\\'),
maruel@chromium.org398ed342015-09-29 12:27:25 +0000215 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000216 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000217 reviewers,
218 args.bug,
219 args.no_log,
smut@google.com02d20872015-11-14 00:46:41 +0000220 args.log_limit,
221 args.ignore_dirty_tree)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000222
223 except Error as e:
224 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700225 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000226
227 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000228
sbc@chromium.org98201122015-04-22 20:21:34 +0000229
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000230if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000231 sys.exit(main())