blob: 10c58295659a33c75b1d48fe7b39f45a0aeed7d4 [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.
64 if upstream_url.endswith((
65 '/angle/angle.git',
66 '/catapult-project/catapult.git',
67 '/v8/v8.git')):
68 return False
69 if 'webrtc' in upstream_url:
70 return False
71 return True
72
73
smut@google.com02d20872015-11-14 00:46:41 +000074def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit,
75 ignore_dirty_tree=False):
maruel@chromium.org96550942015-05-22 18:46:51 +000076 deps = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000077 try:
maruel@chromium.org96550942015-05-22 18:46:51 +000078 with open(deps, 'rb') as f:
79 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000080 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000081 raise Error('Ensure the script is run in the directory '
82 'containing DEPS file.')
sbc@chromium.org98201122015-04-22 20:21:34 +000083
smut@google.com02d20872015-11-14 00:46:41 +000084 if not ignore_dirty_tree and not is_pristine(root):
brucedawson@chromium.org8a6495c2015-12-07 21:46:41 +000085 raise Error('Ensure %s is clean first (no non-merged commits).' % root)
maruel@chromium.org96550942015-05-22 18:46:51 +000086
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000087 full_dir = os.path.normpath(os.path.join(os.path.dirname(root), deps_dir))
sbc@chromium.org30e5b232015-06-01 18:06:59 +000088 if not os.path.isdir(full_dir):
brucedawson@chromium.org8a6495c2015-12-07 21:46:41 +000089 raise Error('Directory not found: %s (%s)' % (deps_dir, full_dir))
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000090 head = check_output(['git', 'rev-parse', 'HEAD'], cwd=full_dir).strip()
maruel@chromium.org96550942015-05-22 18:46:51 +000091
92 if not head in deps_content:
93 print('Warning: %s is not checked out at the expected revision in DEPS' %
94 deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000095 if key is None:
96 print("Warning: no key specified. Using '%s'." % deps_dir)
97 key = deps_dir
98
maruel@chromium.org96550942015-05-22 18:46:51 +000099 # It happens if the user checked out a branch in the dependency by himself.
100 # Fall back to reading the DEPS to figure out the original commit.
101 for i in deps_content.splitlines():
rohitrao@chromium.orgd4ef5992016-02-18 00:05:22 +0000102 m = re.match(r'\s+"' + key + '":.*"([a-z0-9]{40})",', i)
maruel@chromium.org96550942015-05-22 18:46:51 +0000103 if m:
104 head = m.group(1)
105 break
106 else:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000107 raise Error('Expected to find commit %s for %s in DEPS' % (head, key))
maruel@chromium.org96550942015-05-22 18:46:51 +0000108
109 print('Found old revision %s' % head)
110
maruel@chromium.org398ed342015-09-29 12:27:25 +0000111 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
112 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
113 print('Found new revision %s' % roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000114
maruel@chromium.org398ed342015-09-29 12:27:25 +0000115 if roll_to == head:
smut7036c4f2016-06-09 14:28:48 -0700116 raise AlreadyRolledError('No revision to roll!')
maruel@chromium.org96550942015-05-22 18:46:51 +0000117
maruel@chromium.org398ed342015-09-29 12:27:25 +0000118 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org96550942015-05-22 18:46:51 +0000119
maruel@chromium.org398ed342015-09-29 12:27:25 +0000120 upstream_url = check_output(
121 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
122 log_url = get_log_url(upstream_url, head, roll_to)
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000123 cmd = [
124 'git', 'log', commit_range, '--date=short', '--no-merges',
125 ]
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000126 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000127 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000128 cwd=full_dir)
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000129 logs = re.sub(r'(?m)^(\d\d\d\d-\d\d-\d\d [^@]+)@[^ ]+( .*)$', r'\1\2', logs)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000130 nb_commits = logs.count('\n')
131
132 header = 'Roll %s/ %s (%d commit%s).\n\n' % (
133 deps_dir,
134 commit_range,
135 nb_commits,
136 's' if nb_commits > 1 else '')
137
138 log_section = ''
139 if log_url:
140 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000141 log_section += '$ %s ' % ' '.join(cmd)
142 log_section += '--format=\'%ad %ae %s\'\n'
maruel@chromium.org398ed342015-09-29 12:27:25 +0000143 if not no_log and should_show_log(upstream_url):
144 if logs.count('\n') > log_limit:
145 # Keep the first N log entries.
146 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
147 log_section += logs
148 log_section += '\n'
149
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000150 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
151 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000152 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000153
154 print('Commit message:')
155 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000156 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000157 with open(deps, 'wb') as f:
158 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000159 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000160 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
161
162 # Pull the dependency to the right revision. This is surprising to users
163 # otherwise.
164 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
165
maruel@chromium.org96550942015-05-22 18:46:51 +0000166 print('')
167 if not reviewers:
168 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
169 print('to the commit description before emailing.')
170 print('')
171 print('Run:')
172 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000173
174
maruel@chromium.org96550942015-05-22 18:46:51 +0000175def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000176 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000177 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000178 '--ignore-dirty-tree', action='store_true',
179 help='Roll anyways, even if there is a diff.')
180 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000181 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000182 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000183 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000184 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
185 parser.add_argument(
186 '--no-log', action='store_true',
187 help='Do not include the short log in the commit message')
188 parser.add_argument(
189 '--log-limit', type=int, default=100,
190 help='Trim log after N commits (default: %(default)s)')
191 parser.add_argument(
192 '--roll-to', default='origin/master',
193 help='Specify the new commit to roll to (default: %(default)s)')
194 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000195 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000196 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000197 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000198
199 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000200 if args.reviewer:
201 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000202 for i, r in enumerate(reviewers):
203 if not '@' in r:
204 reviewers[i] = r + '@chromium.org'
205
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000206 try:
207 roll(
208 os.getcwd(),
maruel@chromium.org261fa7d2015-11-23 19:20:09 +0000209 args.dep_path.rstrip('/').rstrip('\\'),
maruel@chromium.org398ed342015-09-29 12:27:25 +0000210 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000211 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000212 reviewers,
213 args.bug,
214 args.no_log,
smut@google.com02d20872015-11-14 00:46:41 +0000215 args.log_limit,
216 args.ignore_dirty_tree)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000217
218 except Error as e:
219 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700220 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000221
222 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000223
sbc@chromium.org98201122015-04-22 20:21:34 +0000224
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000225if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000226 sys.exit(main())