blob: a16a5cdce80c43ba0ebf6ad871e31fb1b238b77b [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
smut@google.com02d20872015-11-14 00:46:41 +000070def roll(root, deps_dir, roll_to, key, reviewers, bug, no_log, log_limit,
71 ignore_dirty_tree=False):
maruel@chromium.org96550942015-05-22 18:46:51 +000072 deps = os.path.join(root, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000073 try:
maruel@chromium.org96550942015-05-22 18:46:51 +000074 with open(deps, 'rb') as f:
75 deps_content = f.read()
maruel@chromium.orga7a229f2015-05-22 21:34:46 +000076 except (IOError, OSError):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000077 raise Error('Ensure the script is run in the directory '
78 'containing DEPS file.')
sbc@chromium.org98201122015-04-22 20:21:34 +000079
smut@google.com02d20872015-11-14 00:46:41 +000080 if not ignore_dirty_tree and not is_pristine(root):
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000081 raise Error('Ensure %s is clean first.' % root)
maruel@chromium.org96550942015-05-22 18:46:51 +000082
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +000083 full_dir = os.path.normpath(os.path.join(os.path.dirname(root), deps_dir))
sbc@chromium.org30e5b232015-06-01 18:06:59 +000084 if not os.path.isdir(full_dir):
85 raise Error('Directory not found: %s' % deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000086 head = check_output(['git', 'rev-parse', 'HEAD'], cwd=full_dir).strip()
maruel@chromium.org96550942015-05-22 18:46:51 +000087
88 if not head in deps_content:
89 print('Warning: %s is not checked out at the expected revision in DEPS' %
90 deps_dir)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +000091 if key is None:
92 print("Warning: no key specified. Using '%s'." % deps_dir)
93 key = deps_dir
94
maruel@chromium.org96550942015-05-22 18:46:51 +000095 # It happens if the user checked out a branch in the dependency by himself.
96 # Fall back to reading the DEPS to figure out the original commit.
97 for i in deps_content.splitlines():
98 m = re.match(r'\s+"' + key + '": "([a-z0-9]{40})",', i)
99 if m:
100 head = m.group(1)
101 break
102 else:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000103 raise Error('Expected to find commit %s for %s in DEPS' % (head, key))
maruel@chromium.org96550942015-05-22 18:46:51 +0000104
105 print('Found old revision %s' % head)
106
maruel@chromium.org398ed342015-09-29 12:27:25 +0000107 check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
108 roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
109 print('Found new revision %s' % roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000110
maruel@chromium.org398ed342015-09-29 12:27:25 +0000111 if roll_to == head:
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000112 raise Error('No revision to roll!')
maruel@chromium.org96550942015-05-22 18:46:51 +0000113
maruel@chromium.org398ed342015-09-29 12:27:25 +0000114 commit_range = '%s..%s' % (head[:9], roll_to[:9])
maruel@chromium.org96550942015-05-22 18:46:51 +0000115
maruel@chromium.org398ed342015-09-29 12:27:25 +0000116 upstream_url = check_output(
117 ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
118 log_url = get_log_url(upstream_url, head, roll_to)
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000119 cmd = [
120 'git', 'log', commit_range, '--date=short', '--no-merges',
121 ]
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000122 logs = check_output(
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000123 cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
maruel@chromium.org398ed342015-09-29 12:27:25 +0000124 cwd=full_dir)
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000125 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 +0000126 nb_commits = logs.count('\n')
127
128 header = 'Roll %s/ %s (%d commit%s).\n\n' % (
129 deps_dir,
130 commit_range,
131 nb_commits,
132 's' if nb_commits > 1 else '')
133
134 log_section = ''
135 if log_url:
136 log_section = log_url + '\n\n'
johannkoenig@google.com64f2fc32015-10-07 19:11:17 +0000137 log_section += '$ %s ' % ' '.join(cmd)
138 log_section += '--format=\'%ad %ae %s\'\n'
maruel@chromium.org398ed342015-09-29 12:27:25 +0000139 if not no_log and should_show_log(upstream_url):
140 if logs.count('\n') > log_limit:
141 # Keep the first N log entries.
142 logs = ''.join(logs.splitlines(True)[:log_limit]) + '(...)\n'
143 log_section += logs
144 log_section += '\n'
145
maruel@chromium.orgc6e39fe2015-09-23 13:45:52 +0000146 reviewer = 'R=%s\n' % ','.join(reviewers) if reviewers else ''
147 bug = 'BUG=%s\n' % bug if bug else ''
maruel@chromium.org398ed342015-09-29 12:27:25 +0000148 msg = header + log_section + reviewer + bug
maruel@chromium.org96550942015-05-22 18:46:51 +0000149
150 print('Commit message:')
151 print('\n'.join(' ' + i for i in msg.splitlines()))
maruel@chromium.org398ed342015-09-29 12:27:25 +0000152 deps_content = deps_content.replace(head, roll_to)
maruel@chromium.org96550942015-05-22 18:46:51 +0000153 with open(deps, 'wb') as f:
154 f.write(deps_content)
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000155 check_call(['git', 'add', 'DEPS'], cwd=root)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000156 check_call(['git', 'commit', '--quiet', '-m', msg], cwd=root)
157
158 # Pull the dependency to the right revision. This is surprising to users
159 # otherwise.
160 check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
161
maruel@chromium.org96550942015-05-22 18:46:51 +0000162 print('')
163 if not reviewers:
164 print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
165 print('to the commit description before emailing.')
166 print('')
167 print('Run:')
168 print(' git cl upload --send-mail')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000169
170
maruel@chromium.org96550942015-05-22 18:46:51 +0000171def main():
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000172 parser = argparse.ArgumentParser(description=__doc__)
maruel@chromium.org398ed342015-09-29 12:27:25 +0000173 parser.add_argument(
smut@google.com02d20872015-11-14 00:46:41 +0000174 '--ignore-dirty-tree', action='store_true',
175 help='Roll anyways, even if there is a diff.')
176 parser.add_argument(
maruel@chromium.org398ed342015-09-29 12:27:25 +0000177 '-r', '--reviewer',
maruel@chromium.org96550942015-05-22 18:46:51 +0000178 help='To specify multiple reviewers, use comma separated list, e.g. '
scottmg@chromium.orgc20f4702015-05-23 00:44:46 +0000179 '-r joe,jane,john. Defaults to @chromium.org')
maruel@chromium.org398ed342015-09-29 12:27:25 +0000180 parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
181 parser.add_argument(
182 '--no-log', action='store_true',
183 help='Do not include the short log in the commit message')
184 parser.add_argument(
185 '--log-limit', type=int, default=100,
186 help='Trim log after N commits (default: %(default)s)')
187 parser.add_argument(
188 '--roll-to', default='origin/master',
189 help='Specify the new commit to roll to (default: %(default)s)')
190 parser.add_argument('dep_path', help='Path to dependency')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000191 parser.add_argument('key', nargs='?',
maruel@chromium.org398ed342015-09-29 12:27:25 +0000192 help='Regexp for dependency in DEPS file')
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000193 args = parser.parse_args()
maruel@chromium.org96550942015-05-22 18:46:51 +0000194
195 reviewers = None
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000196 if args.reviewer:
197 reviewers = args.reviewer.split(',')
maruel@chromium.org96550942015-05-22 18:46:51 +0000198 for i, r in enumerate(reviewers):
199 if not '@' in r:
200 reviewers[i] = r + '@chromium.org'
201
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000202 try:
203 roll(
204 os.getcwd(),
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000205 args.dep_path,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000206 args.roll_to,
sbc@chromium.org30e5b232015-06-01 18:06:59 +0000207 args.key,
maruel@chromium.org398ed342015-09-29 12:27:25 +0000208 reviewers,
209 args.bug,
210 args.no_log,
smut@google.com02d20872015-11-14 00:46:41 +0000211 args.log_limit,
212 args.ignore_dirty_tree)
sbc@chromium.orge5d984b2015-05-29 22:09:39 +0000213
214 except Error as e:
215 sys.stderr.write('error: %s\n' % e)
216 return 1
217
218 return 0
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000219
sbc@chromium.org98201122015-04-22 20:21:34 +0000220
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000221if __name__ == '__main__':
maruel@chromium.org96550942015-05-22 18:46:51 +0000222 sys.exit(main())