blob: 9097b832176dc8df357ef939ad1b7803fc2c7959 [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)
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000118 logs = check_output(
119 ['git', 'log', commit_range, '--date=short', '--format=%ad %ae %s'],
maruel@chromium.org398ed342015-09-29 12:27:25 +0000120 cwd=full_dir)
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000121 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 +0000122 nb_commits = logs.count('\n')
123
124 header = 'Roll %s/ %s (%d commit%s).\n\n' % (
125 deps_dir,
126 commit_range,
127 nb_commits,
128 's' if nb_commits > 1 else '')
129
130 log_section = ''
131 if log_url:
132 log_section = log_url + '\n\n'
133 log_section += '$ git log %s --date=short --format=\'%%ad %%ae %%s\'\n' % (
134 commit_range)
135 if not no_log and should_show_log(upstream_url):
136 if logs.count('\n') > log_limit:
137 # Keep the first N log entries.
138 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
139 log_section += logs
140 log_section += '\n'
141
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000142 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
143 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000144 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000145
146 print('Commit message:')
147 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000148 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000149 with open(deps, 'wb') as f:
150 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000151 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000152 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
153
154 # Pull the dependency to the right revision. This is surprising to users
155 # otherwise.
156 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
157
maruel@chromium.org96550942015-05-22 18:46:51 +0000158 print('')
159 if not reviewers:
160 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
161 print('to the commit description before emailing.')
162 print('')
163 print('Run:')
164 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000165
166
maruel@chromium.org96550942015-05-22 18:46:51 +0000167def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000168 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000169 parser.add_argument(
170 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000171 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000172 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000173 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
174 parser.add_argument(
175 '--no-log', action='store_true',
176 help='Do not include the short log in the commit message')
177 parser.add_argument(
178 '--log-limit', type=int, default=100,
179 help='Trim log after N commits (default: %(default)s)')
180 parser.add_argument(
181 '--roll-to', default='origin/master',
182 help='Specify the new commit to roll to (default: %(default)s)')
183 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000184 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000185 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000186 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000187
188 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000189 if args.reviewer:
190 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000191 for i, r in enumerate(reviewers):
192 if not '@' in r:
193 reviewers[i] = r + '@chromium.org'
194
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000195 try:
196 roll(
197 os.getcwd(),
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000198 args.dep_path,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000199 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000200 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000201 reviewers,
202 args.bug,
203 args.no_log,
204 args.log_limit)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000205
206 except Error as e:
207 sys.stderr.write('error: %s\n' % e)
208 return 1
209
210 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000211
sbc@chromium.org98201122015-04-22 20:21:34 +0000212
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000213if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000214 sys.exit(main())