blob: cead95dcb163bc7ac1424a0940c8de1f3c478028 [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
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000025def check_output(*args, **kwargs):
26 """subprocess.check_output() passing shell=True on Windows for git."""
27 kwargs.setdefault('shell', NEED_SHELL)
28 return subprocess.check_output(*args, **kwargs)
29
30
31def check_call(*args, **kwargs):
32 """subprocess.check_call() passing shell=True on Windows for git."""
33 kwargs.setdefault('shell', NEED_SHELL)
34 subprocess.check_call(*args, **kwargs)
35
36
maruel@chromium.org96550942015-05-22 18:46:51 +000037def is_pristine(root, merge_base='origin/master'):
38 """Returns True if a git checkout is pristine."""
39 cmd = ['git', 'diff', '--ignore-submodules', merge_base]
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000040 return not (check_output(cmd, cwd=root).strip() or
41 check_output(cmd + ['--cached'], cwd=root).strip())
szager@chromium.org03fd85b2014-06-09 23:43:33 +000042
43
maruel@chromium.org398ed342015-09-29 12:27:25 +000044def get_log_url(upstream_url, head, master):
45 """Returns an URL to read logs via a Web UI if applicable."""
46 if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
47 # gitiles
48 return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
49 if upstream_url.startswith('https://github.com/'):
50 upstream_url = upstream_url.rstrip('/')
51 if upstream_url.endswith('.git'):
52 upstream_url = upstream_url[:-len('.git')]
53 return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
54 return None
55
56
57def should_show_log(upstream_url):
58 """Returns True if a short log should be included in the tree."""
59 # Skip logs for very active projects.
60 if upstream_url.endswith((
61 '/angle/angle.git',
62 '/catapult-project/catapult.git',
63 '/v8/v8.git')):
64 return False
65 if 'webrtc' in upstream_url:
66 return False
67 return True
68
69
70def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit):
maruel@chromium.org96550942015-05-22 18:46:51 +000071 deps = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000072 try:
maruel@chromium.org96550942015-05-22 18:46:51 +000073 with open(deps, 'rb') as f:
74 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000075 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000076 raise Error('Ensure the script is run in the directory '
77 'containing DEPS file.')
sbc@chromium.org98201122015-04-22 20:21:34 +000078
maruel@chromium.org96550942015-05-22 18:46:51 +000079 if not is_pristine(root):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000080 raise Error('Ensure %s is clean first.' % root)
maruel@chromium.org96550942015-05-22 18:46:51 +000081
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000082 full_dir = os.path.normpath(os.path.join(os.path.dirname(root), deps_dir))
sbc@chromium.org30e5b232015-06-01 18:06:59 +000083 if not os.path.isdir(full_dir):
84 raise Error('Directory not found: %s' % deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000085 head = check_output(['git', 'rev-parse', 'HEAD'], cwd=full_dir).strip()
maruel@chromium.org96550942015-05-22 18:46:51 +000086
87 if not head in deps_content:
88 print('Warning: %s is not checked out at the expected revision in DEPS' %
89 deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000090 if key is None:
91 print("Warning: no key specified. Using '%s'." % deps_dir)
92 key = deps_dir
93
maruel@chromium.org96550942015-05-22 18:46:51 +000094 # It happens if the user checked out a branch in the dependency by himself.
95 # Fall back to reading the DEPS to figure out the original commit.
96 for i in deps_content.splitlines():
97 m = re.match(r'\s+"' + key + '": "([a-z0-9]{40})",', i)
98 if m:
99 head = m.group(1)
100 break
101 else:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000102 raise Error('Expected to find commit %s for %s in DEPS' % (head, key))
maruel@chromium.org96550942015-05-22 18:46:51 +0000103
104 print('Found old revision %s' % head)
105
maruel@chromium.org398ed342015-09-29 12:27:25 +0000106 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
107 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
108 print('Found new revision %s' % roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000109
maruel@chromium.org398ed342015-09-29 12:27:25 +0000110 if roll_to == head:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000111 raise Error('No revision to roll!')
maruel@chromium.org96550942015-05-22 18:46:51 +0000112
maruel@chromium.org398ed342015-09-29 12:27:25 +0000113 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org96550942015-05-22 18:46:51 +0000114
maruel@chromium.org398ed342015-09-29 12:27:25 +0000115 upstream_url = check_output(
116 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
117 log_url = get_log_url(upstream_url, head, roll_to)
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000118 cmd = [
119 'git', 'log', commit_range, '--date=short', '--no-merges',
120 ]
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000121 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000122 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000123 cwd=full_dir)
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000124 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 +0000125 nb_commits = logs.count('\n')
126
127 header = 'Roll %s/ %s (%d commit%s).\n\n' % (
128 deps_dir,
129 commit_range,
130 nb_commits,
131 's' if nb_commits > 1 else '')
132
133 log_section = ''
134 if log_url:
135 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000136 log_section += '$ %s ' % ' '.join(cmd)
137 log_section += '--format=\'%ad %ae %s\'\n'
maruel@chromium.org398ed342015-09-29 12:27:25 +0000138 if not no_log and should_show_log(upstream_url):
139 if logs.count('\n') > log_limit:
140 # Keep the first N log entries.
141 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
142 log_section += logs
143 log_section += '\n'
144
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000145 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
146 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000147 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000148
149 print('Commit message:')
150 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000151 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000152 with open(deps, 'wb') as f:
153 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000154 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000155 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
156
157 # Pull the dependency to the right revision. This is surprising to users
158 # otherwise.
159 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
160
maruel@chromium.org96550942015-05-22 18:46:51 +0000161 print('')
162 if not reviewers:
163 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
164 print('to the commit description before emailing.')
165 print('')
166 print('Run:')
167 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000168
169
maruel@chromium.org96550942015-05-22 18:46:51 +0000170def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000171 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000172 parser.add_argument(
173 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000174 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000175 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000176 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
177 parser.add_argument(
178 '--no-log', action='store_true',
179 help='Do not include the short log in the commit message')
180 parser.add_argument(
181 '--log-limit', type=int, default=100,
182 help='Trim log after N commits (default: %(default)s)')
183 parser.add_argument(
184 '--roll-to', default='origin/master',
185 help='Specify the new commit to roll to (default: %(default)s)')
186 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000187 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000188 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000189 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000190
191 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000192 if args.reviewer:
193 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000194 for i, r in enumerate(reviewers):
195 if not '@' in r:
196 reviewers[i] = r + '@chromium.org'
197
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000198 try:
199 roll(
200 os.getcwd(),
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000201 args.dep_path,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000202 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000203 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000204 reviewers,
205 args.bug,
206 args.no_log,
207 args.log_limit)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000208
209 except Error as e:
210 sys.stderr.write('error: %s\n' % e)
211 return 1
212
213 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000214
sbc@chromium.org98201122015-04-22 20:21:34 +0000215
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000216if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000217 sys.exit(main())