blob: c5cef840313277c0bd6caaa2d5775f6080dc0f3e [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',
maruel@chromium.org398ed342015-09-29 12:27:25 +000066 '/v8/v8.git')):
67 return False
68 if 'webrtc' in upstream_url:
69 return False
70 return True
71
72
smut@google.com02d20872015-11-14 00:46:41 +000073def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit,
74 ignore_dirty_tree=False):
maruel@chromium.org96550942015-05-22 18:46:51 +000075 deps = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000076 try:
maruel@chromium.org96550942015-05-22 18:46:51 +000077 with open(deps, 'rb') as f:
78 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000079 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000080 raise Error('Ensure the script is run in the directory '
81 'containing DEPS file.')
sbc@chromium.org98201122015-04-22 20:21:34 +000082
smut@google.com02d20872015-11-14 00:46:41 +000083 if not ignore_dirty_tree and not is_pristine(root):
brucedawson@chromium.org8a6495c2015-12-07 21:46:41 +000084 raise Error('Ensure %s is clean first (no non-merged commits).' % root)
maruel@chromium.org96550942015-05-22 18:46:51 +000085
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000086 full_dir = os.path.normpath(os.path.join(os.path.dirname(root), deps_dir))
sbc@chromium.org30e5b232015-06-01 18:06:59 +000087 if not os.path.isdir(full_dir):
brucedawson@chromium.org8a6495c2015-12-07 21:46:41 +000088 raise Error('Directory not found: %s (%s)' % (deps_dir, full_dir))
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000089 head = check_output(['git', 'rev-parse', 'HEAD'], cwd=full_dir).strip()
maruel@chromium.org96550942015-05-22 18:46:51 +000090
91 if not head in deps_content:
92 print('Warning: %s is not checked out at the expected revision in DEPS' %
93 deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000094 if key is None:
95 print("Warning: no key specified. Using '%s'." % deps_dir)
96 key = deps_dir
97
maruel@chromium.org96550942015-05-22 18:46:51 +000098 # It happens if the user checked out a branch in the dependency by himself.
99 # Fall back to reading the DEPS to figure out the original commit.
100 for i in deps_content.splitlines():
rohitrao@chromium.orgd4ef5992016-02-18 00:05:22 +0000101 m = re.match(r'\s+"' + key + '":.*"([a-z0-9]{40})",', i)
maruel@chromium.org96550942015-05-22 18:46:51 +0000102 if m:
103 head = m.group(1)
104 break
105 else:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000106 raise Error('Expected to find commit %s for %s in DEPS' % (head, key))
maruel@chromium.org96550942015-05-22 18:46:51 +0000107
108 print('Found old revision %s' % head)
109
maruel@chromium.org398ed342015-09-29 12:27:25 +0000110 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
111 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
112 print('Found new revision %s' % roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000113
maruel@chromium.org398ed342015-09-29 12:27:25 +0000114 if roll_to == head:
smut7036c4f2016-06-09 14:28:48 -0700115 raise AlreadyRolledError('No revision to roll!')
maruel@chromium.org96550942015-05-22 18:46:51 +0000116
maruel@chromium.org398ed342015-09-29 12:27:25 +0000117 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org96550942015-05-22 18:46:51 +0000118
maruel@chromium.org398ed342015-09-29 12:27:25 +0000119 upstream_url = check_output(
120 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
121 log_url = get_log_url(upstream_url, head, roll_to)
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000122 cmd = [
123 'git', 'log', commit_range, '--date=short', '--no-merges',
124 ]
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000125 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000126 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000127 cwd=full_dir)
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000128 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 +0000129 nb_commits = logs.count('\n')
130
131 header = 'Roll %s/ %s (%d commit%s).\n\n' % (
132 deps_dir,
133 commit_range,
134 nb_commits,
135 's' if nb_commits > 1 else '')
136
137 log_section = ''
138 if log_url:
139 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000140 log_section += '$ %s ' % ' '.join(cmd)
141 log_section += '--format=\'%ad %ae %s\'\n'
maruel@chromium.org398ed342015-09-29 12:27:25 +0000142 if not no_log and should_show_log(upstream_url):
143 if logs.count('\n') > log_limit:
144 # Keep the first N log entries.
145 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
146 log_section += logs
147 log_section += '\n'
148
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000149 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
150 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000151 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000152
153 print('Commit message:')
154 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000155 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000156 with open(deps, 'wb') as f:
157 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000158 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000159 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
160
161 # Pull the dependency to the right revision. This is surprising to users
162 # otherwise.
163 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
164
maruel@chromium.org96550942015-05-22 18:46:51 +0000165 print('')
166 if not reviewers:
167 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
168 print('to the commit description before emailing.')
169 print('')
170 print('Run:')
171 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000172
173
maruel@chromium.org96550942015-05-22 18:46:51 +0000174def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000175 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000176 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000177 '--ignore-dirty-tree', action='store_true',
178 help='Roll anyways, even if there is a diff.')
179 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000180 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000181 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000182 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000183 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
184 parser.add_argument(
185 '--no-log', action='store_true',
186 help='Do not include the short log in the commit message')
187 parser.add_argument(
188 '--log-limit', type=int, default=100,
189 help='Trim log after N commits (default: %(default)s)')
190 parser.add_argument(
191 '--roll-to', default='origin/master',
192 help='Specify the new commit to roll to (default: %(default)s)')
193 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000194 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000195 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000196 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000197
198 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000199 if args.reviewer:
200 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000201 for i, r in enumerate(reviewers):
202 if not '@' in r:
203 reviewers[i] = r + '@chromium.org'
204
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000205 try:
206 roll(
207 os.getcwd(),
maruel@chromium.org261fa7d2015-11-23 19:20:09 +0000208 args.dep_path.rstrip('/').rstrip('\\'),
maruel@chromium.org398ed342015-09-29 12:27:25 +0000209 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000210 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000211 reviewers,
212 args.bug,
213 args.no_log,
smut@google.com02d20872015-11-14 00:46:41 +0000214 args.log_limit,
215 args.ignore_dirty_tree)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000216
217 except Error as e:
218 sys.stderr.write('error: %s\n' % e)
smut7036c4f2016-06-09 14:28:48 -0700219 return 2 if isinstance(e, AlreadyRolledError) else 1
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000220
221 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000222
sbc@chromium.org98201122015-04-22 20:21:34 +0000223
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000224if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000225 sys.exit(main())