blob: 2f78983b270b9c717f750ab6b7099e29d68e4170 [file] [log] [blame]
szager@chromium.org03fd85b2014-06-09 23:43:33 +00001#!/usr/bin/env python
2# Copyright (c) 2014 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""This scripts takes the path to a dep and an svn revision, and updates the
7parent repo's DEPS file with the corresponding git revision. Sample invocation:
8
9[chromium/src]$ roll-dep third_party/WebKit 12345
10
11After the script completes, the DEPS file will be dirty with the new revision.
12The user can then:
13
14$ git add DEPS
15$ git commit
16"""
17
18import ast
machenbach@chromium.orge0c89732014-12-18 15:42:43 +000019import optparse
szager@chromium.org03fd85b2014-06-09 23:43:33 +000020import os
21import re
22import sys
23
24from itertools import izip
borenet@google.com2674ae02014-09-15 21:00:23 +000025from subprocess import check_output, Popen, PIPE
szager@chromium.org03fd85b2014-06-09 23:43:33 +000026from textwrap import dedent
27
28
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000029SHA1_RE = re.compile('^[a-fA-F0-9]{40}$')
30GIT_SVN_ID_RE = re.compile('^git-svn-id: .*@([0-9]+) .*$')
borenet@google.com2674ae02014-09-15 21:00:23 +000031ROLL_DESCRIPTION_STR = (
32'''Roll %(dep_path)s %(before_rev)s:%(after_rev)s%(svn_range)s
borenet@google.com8eec89c2014-08-29 22:03:07 +000033
34Summary of changes available at:
borenet@google.com2674ae02014-09-15 21:00:23 +000035%(revlog_url)s
36''')
borenet@google.com8eec89c2014-08-29 22:03:07 +000037
38
39def shorten_dep_path(dep):
40 """Shorten the given dep path if necessary."""
41 while len(dep) > 31:
42 dep = '.../' + dep.lstrip('./').partition('/')[2]
43 return dep
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000044
45
szager@chromium.org03fd85b2014-06-09 23:43:33 +000046def posix_path(path):
47 """Convert a possibly-Windows path to a posix-style path."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000048 (_, path) = os.path.splitdrive(path)
49 return path.replace(os.sep, '/')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000050
51
52def platform_path(path):
53 """Convert a path to the native path format of the host OS."""
54 return path.replace('/', os.sep)
55
56
57def find_gclient_root():
58 """Find the directory containing the .gclient file."""
59 cwd = posix_path(os.getcwd())
60 result = ''
61 for _ in xrange(len(cwd.split('/'))):
62 if os.path.exists(os.path.join(result, '.gclient')):
63 return result
64 result = os.path.join(result, os.pardir)
65 assert False, 'Could not find root of your gclient checkout.'
66
67
68def get_solution(gclient_root, dep_path):
69 """Find the solution in .gclient containing the dep being rolled."""
70 dep_path = os.path.relpath(dep_path, gclient_root)
71 cwd = os.getcwd().rstrip(os.sep) + os.sep
72 gclient_root = os.path.realpath(gclient_root)
73 gclient_path = os.path.join(gclient_root, '.gclient')
74 gclient_locals = {}
75 execfile(gclient_path, {}, gclient_locals)
76 for soln in gclient_locals['solutions']:
77 soln_relpath = platform_path(soln['name'].rstrip('/')) + os.sep
78 if (dep_path.startswith(soln_relpath) or
79 cwd.startswith(os.path.join(gclient_root, soln_relpath))):
80 return soln
81 assert False, 'Could not determine the parent project for %s' % dep_path
82
83
machenbach@chromium.orge0c89732014-12-18 15:42:43 +000084def is_git_hash(revision):
85 """Determines if a given revision is a git hash."""
86 return SHA1_RE.match(revision)
87
88
szager@chromium.org03fd85b2014-06-09 23:43:33 +000089def verify_git_revision(dep_path, revision):
90 """Verify that a git revision exists in a repository."""
91 p = Popen(['git', 'rev-list', '-n', '1', revision],
92 cwd=dep_path, stdout=PIPE, stderr=PIPE)
93 result = p.communicate()[0].strip()
machenbach@chromium.orge0c89732014-12-18 15:42:43 +000094 if p.returncode != 0 or not is_git_hash(result):
szager@chromium.org03fd85b2014-06-09 23:43:33 +000095 result = None
96 return result
97
98
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000099def get_svn_revision(dep_path, git_revision):
100 """Given a git revision, return the corresponding svn revision."""
101 p = Popen(['git', 'log', '-n', '1', '--pretty=format:%B', git_revision],
102 stdout=PIPE, cwd=dep_path)
103 (log, _) = p.communicate()
104 assert p.returncode == 0, 'git log %s failed.' % git_revision
105 for line in reversed(log.splitlines()):
106 m = GIT_SVN_ID_RE.match(line.strip())
107 if m:
108 return m.group(1)
109 return None
110
111
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000112def convert_svn_revision(dep_path, revision):
113 """Find the git revision corresponding to an svn revision."""
114 err_msg = 'Unknown error'
115 revision = int(revision)
thestig@chromium.orgbf13f082014-09-24 23:48:33 +0000116 latest_svn_rev = None
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000117 with open(os.devnull, 'w') as devnull:
118 for ref in ('HEAD', 'origin/master'):
119 try:
120 log_p = Popen(['git', 'log', ref],
121 cwd=dep_path, stdout=PIPE, stderr=devnull)
122 grep_p = Popen(['grep', '-e', '^commit ', '-e', '^ *git-svn-id: '],
123 stdin=log_p.stdout, stdout=PIPE, stderr=devnull)
124 git_rev = None
125 prev_svn_rev = None
126 for line in grep_p.stdout:
127 if line.startswith('commit '):
128 git_rev = line.split()[1]
129 continue
130 try:
131 svn_rev = int(line.split()[1].partition('@')[2])
132 except (IndexError, ValueError):
133 print >> sys.stderr, (
134 'WARNING: Could not parse svn revision out of "%s"' % line)
135 continue
thestig@chromium.orgbf13f082014-09-24 23:48:33 +0000136 if not latest_svn_rev or int(svn_rev) > int(latest_svn_rev):
137 latest_svn_rev = svn_rev
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000138 if svn_rev == revision:
139 return git_rev
140 if svn_rev > revision:
141 prev_svn_rev = svn_rev
142 continue
143 if prev_svn_rev:
144 err_msg = 'git history skips from revision %d to revision %d.' % (
145 svn_rev, prev_svn_rev)
146 else:
147 err_msg = (
148 'latest available revision is %d; you may need to '
thestig@chromium.orgbf13f082014-09-24 23:48:33 +0000149 '"git fetch origin" to get the latest commits.' %
150 latest_svn_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000151 finally:
152 log_p.terminate()
153 grep_p.terminate()
154 raise RuntimeError('No match for revision %d; %s' % (revision, err_msg))
155
156
157def get_git_revision(dep_path, revision):
158 """Convert the revision argument passed to the script to a git revision."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000159 svn_revision = None
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000160 if revision.startswith('r'):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000161 git_revision = convert_svn_revision(dep_path, revision[1:])
162 svn_revision = revision[1:]
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000163 elif re.search('[a-fA-F]', revision):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000164 git_revision = verify_git_revision(dep_path, revision)
machenbach@chromium.orge0c89732014-12-18 15:42:43 +0000165 if not git_revision:
166 raise RuntimeError('Please \'git fetch origin\' in %s' % dep_path)
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000167 svn_revision = get_svn_revision(dep_path, git_revision)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000168 elif len(revision) > 6:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000169 git_revision = verify_git_revision(dep_path, revision)
170 if git_revision:
171 svn_revision = get_svn_revision(dep_path, git_revision)
172 else:
173 git_revision = convert_svn_revision(dep_path, revision)
174 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000175 else:
176 try:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000177 git_revision = convert_svn_revision(dep_path, revision)
178 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000179 except RuntimeError:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000180 git_revision = verify_git_revision(dep_path, revision)
181 if not git_revision:
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000182 raise
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000183 svn_revision = get_svn_revision(dep_path, git_revision)
184 return git_revision, svn_revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000185
186
187def ast_err_msg(node):
188 return 'ERROR: Undexpected DEPS file AST structure at line %d column %d' % (
189 node.lineno, node.col_offset)
190
191
192def find_deps_section(deps_ast, section):
193 """Find a top-level section of the DEPS file in the AST."""
194 try:
195 result = [n.value for n in deps_ast.body if
196 n.__class__ is ast.Assign and
197 n.targets[0].__class__ is ast.Name and
198 n.targets[0].id == section][0]
199 return result
200 except IndexError:
201 return None
202
203
204def find_dict_index(dict_node, key):
205 """Given a key, find the index of the corresponding dict entry."""
206 assert dict_node.__class__ is ast.Dict, ast_err_msg(dict_node)
207 indices = [i for i, n in enumerate(dict_node.keys) if
208 n.__class__ is ast.Str and n.s == key]
209 assert len(indices) < 2, (
210 'Found redundant dict entries for key "%s"' % key)
211 return indices[0] if indices else None
212
213
214def update_node(deps_lines, deps_ast, node, git_revision):
215 """Update an AST node with the new git revision."""
216 if node.__class__ is ast.Str:
217 return update_string(deps_lines, node, git_revision)
218 elif node.__class__ is ast.BinOp:
219 return update_binop(deps_lines, deps_ast, node, git_revision)
220 elif node.__class__ is ast.Call:
221 return update_call(deps_lines, deps_ast, node, git_revision)
222 else:
223 assert False, ast_err_msg(node)
224
225
226def update_string(deps_lines, string_node, git_revision):
227 """Update a string node in the AST with the new git revision."""
228 line_idx = string_node.lineno - 1
229 start_idx = string_node.col_offset - 1
230 line = deps_lines[line_idx]
231 (prefix, sep, old_rev) = string_node.s.partition('@')
232 if sep:
233 start_idx = line.find(prefix + sep, start_idx) + len(prefix + sep)
234 tail_idx = start_idx + len(old_rev)
235 else:
236 start_idx = line.find(prefix, start_idx)
237 tail_idx = start_idx + len(prefix)
238 old_rev = prefix
239 deps_lines[line_idx] = line[:start_idx] + git_revision + line[tail_idx:]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000240 return line_idx
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000241
242
243def update_binop(deps_lines, deps_ast, binop_node, git_revision):
244 """Update a binary operation node in the AST with the new git revision."""
245 # Since the revision part is always last, assume that it's the right-hand
246 # operand that needs to be updated.
247 return update_node(deps_lines, deps_ast, binop_node.right, git_revision)
248
249
250def update_call(deps_lines, deps_ast, call_node, git_revision):
251 """Update a function call node in the AST with the new git revision."""
252 # The only call we know how to handle is Var()
253 assert call_node.func.id == 'Var', ast_err_msg(call_node)
254 assert call_node.args and call_node.args[0].__class__ is ast.Str, (
255 ast_err_msg(call_node))
256 return update_var(deps_lines, deps_ast, call_node.args[0].s, git_revision)
257
258
259def update_var(deps_lines, deps_ast, var_name, git_revision):
260 """Update an entry in the vars section of the DEPS file with the new
261 git revision."""
262 vars_node = find_deps_section(deps_ast, 'vars')
263 assert vars_node, 'Could not find "vars" section of DEPS file.'
264 var_idx = find_dict_index(vars_node, var_name)
265 assert var_idx is not None, (
266 'Could not find definition of "%s" var in DEPS file.' % var_name)
267 val_node = vars_node.values[var_idx]
268 return update_node(deps_lines, deps_ast, val_node, git_revision)
269
270
borenet@google.com2674ae02014-09-15 21:00:23 +0000271def short_rev(rev, dep_path):
272 return check_output(['git', 'rev-parse', '--short', rev],
273 cwd=dep_path).rstrip()
274
275
276def generate_commit_message(deps_section, dep_path, dep_name, new_rev):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000277 (url, _, old_rev) = deps_section[dep_name].partition('@')
278 if url.endswith('.git'):
279 url = url[:-4]
borenet@google.com2674ae02014-09-15 21:00:23 +0000280 old_rev_short = short_rev(old_rev, dep_path)
281 new_rev_short = short_rev(new_rev, dep_path)
282 url += '/+log/%s..%s' % (old_rev_short, new_rev_short)
machenbach@chromium.orge0c89732014-12-18 15:42:43 +0000283 try:
284 old_svn_rev = get_svn_revision(dep_path, old_rev)
285 new_svn_rev = get_svn_revision(dep_path, new_rev)
286 except Exception:
287 # Ignore failures that might arise from the repo not being checked out.
288 old_svn_rev = new_svn_rev = None
borenet@google.com2674ae02014-09-15 21:00:23 +0000289 svn_range_str = ''
290 if old_svn_rev and new_svn_rev:
291 svn_range_str = ' (svn %s:%s)' % (old_svn_rev, new_svn_rev)
292 return dedent(ROLL_DESCRIPTION_STR % {
293 'dep_path': shorten_dep_path(dep_name),
294 'before_rev': old_rev_short,
295 'after_rev': new_rev_short,
296 'svn_range': svn_range_str,
297 'revlog_url': url,
298 })
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000299
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000300def update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment):
301 line_idx = update_node(deps_lines, deps_ast, value_node, new_rev)
302 (content, _, _) = deps_lines[line_idx].partition('#')
303 if comment:
304 deps_lines[line_idx] = '%s # %s' % (content.rstrip(), comment)
305 else:
306 deps_lines[line_idx] = content.rstrip()
307
szager@chromium.org00253802014-10-21 19:00:06 +0000308def update_deps(deps_file, dep_path, dep_name, new_rev, comment):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000309 """Update the DEPS file with the new git revision."""
310 commit_msg = ''
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000311 with open(deps_file) as fh:
312 deps_content = fh.read()
313 deps_locals = {}
314 def _Var(key):
315 return deps_locals['vars'][key]
316 deps_locals['Var'] = _Var
317 exec deps_content in {}, deps_locals
318 deps_lines = deps_content.splitlines()
319 deps_ast = ast.parse(deps_content, deps_file)
320 deps_node = find_deps_section(deps_ast, 'deps')
321 assert deps_node, 'Could not find "deps" section of DEPS file'
322 dep_idx = find_dict_index(deps_node, dep_name)
323 if dep_idx is not None:
324 value_node = deps_node.values[dep_idx]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000325 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
borenet@google.com2674ae02014-09-15 21:00:23 +0000326 commit_msg = generate_commit_message(deps_locals['deps'], dep_path,
327 dep_name, new_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000328 deps_os_node = find_deps_section(deps_ast, 'deps_os')
329 if deps_os_node:
330 for (os_name, os_node) in izip(deps_os_node.keys, deps_os_node.values):
331 dep_idx = find_dict_index(os_node, dep_name)
332 if dep_idx is not None:
333 value_node = os_node.values[dep_idx]
334 if value_node.__class__ is ast.Name and value_node.id == 'None':
335 pass
336 else:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000337 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000338 commit_msg = generate_commit_message(
szager@chromium.org42937872014-10-29 22:19:26 +0000339 deps_locals['deps_os'][os_name.s], dep_path, dep_name, new_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000340 if commit_msg:
341 print 'Pinning %s' % dep_name
342 print 'to revision %s' % new_rev
343 print 'in %s' % deps_file
344 with open(deps_file, 'w') as fh:
345 for line in deps_lines:
346 print >> fh, line
szager@chromium.org00253802014-10-21 19:00:06 +0000347 deps_file_dir = os.path.normpath(os.path.dirname(deps_file))
348 deps_file_root = Popen(
349 ['git', 'rev-parse', '--show-toplevel'],
350 cwd=deps_file_dir, stdout=PIPE).communicate()[0].strip()
351 with open(os.path.join(deps_file_root, '.git', 'MERGE_MSG'), 'w') as fh:
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000352 fh.write(commit_msg)
353 else:
354 print 'Could not find an entry in %s to update.' % deps_file
355 return 0 if commit_msg else 1
356
357
358def main(argv):
machenbach@chromium.orge0c89732014-12-18 15:42:43 +0000359 parser = optparse.OptionParser()
360 parser.add_option('--no-verify-revision',
361 help='Don\'t verify the revision passed in. This '
362 'also skips adding an svn revision comment '
363 'for git dependencies and requires the passed '
364 'revision to be a git hash.',
365 default=False, action='store_true')
366 (options, argv) = parser.parse_args(argv)
szager@chromium.org00253802014-10-21 19:00:06 +0000367 if len(argv) not in (2, 3):
368 print >> sys.stderr, (
machenbach@chromium.orge0c89732014-12-18 15:42:43 +0000369 'Usage: roll_dep.py [options] <dep path> <svn revision> '
370 '[ <DEPS file> ]')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000371 return 1
szager@chromium.org00253802014-10-21 19:00:06 +0000372 (arg_dep_path, revision) = argv[0:2]
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000373 gclient_root = find_gclient_root()
szager@chromium.org00253802014-10-21 19:00:06 +0000374 dep_path = platform_path(arg_dep_path)
375 if not os.path.exists(dep_path):
376 dep_path = os.path.join(gclient_root, dep_path)
machenbach@chromium.orge0c89732014-12-18 15:42:43 +0000377 if not options.no_verify_revision:
378 # Only require the path to exist if the revision should be verified. A path
379 # to e.g. os deps might not be checked out.
380 assert os.path.isdir(dep_path), 'No such directory: %s' % arg_dep_path
szager@chromium.org00253802014-10-21 19:00:06 +0000381 if len(argv) > 2:
382 deps_file = argv[2]
383 else:
384 soln = get_solution(gclient_root, dep_path)
385 soln_path = os.path.relpath(os.path.join(gclient_root, soln['name']))
386 deps_file = os.path.join(soln_path, 'DEPS')
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000387 dep_name = posix_path(os.path.relpath(dep_path, gclient_root))
machenbach@chromium.orge0c89732014-12-18 15:42:43 +0000388 if options.no_verify_revision:
389 assert is_git_hash(revision), (
390 'The passed revision %s must be a git hash when skipping revision '
391 'verification.' % revision)
392 git_rev = revision
393 comment = None
394 else:
395 (git_rev, svn_rev) = get_git_revision(dep_path, revision)
396 comment = ('from svn revision %s' % svn_rev) if svn_rev else None
397 assert git_rev, 'Could not find git revision matching %s.' % revision
szager@chromium.org00253802014-10-21 19:00:06 +0000398 return update_deps(deps_file, dep_path, dep_name, git_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000399
400if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000401 try:
402 sys.exit(main(sys.argv[1:]))
403 except KeyboardInterrupt:
404 sys.stderr.write('interrupted\n')
405 sys.exit(1)