blob: 953b0e106d3bb207079116ef9064ce7a2c16a816 [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
19import os
20import re
21import sys
22
23from itertools import izip
borenet@google.com2674ae02014-09-15 21:00:23 +000024from subprocess import check_output, Popen, PIPE
szager@chromium.org03fd85b2014-06-09 23:43:33 +000025from textwrap import dedent
26
27
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000028SHA1_RE = re.compile('^[a-fA-F0-9]{40}$')
29GIT_SVN_ID_RE = re.compile('^git-svn-id: .*@([0-9]+) .*$')
borenet@google.com2674ae02014-09-15 21:00:23 +000030ROLL_DESCRIPTION_STR = (
31'''Roll %(dep_path)s %(before_rev)s:%(after_rev)s%(svn_range)s
borenet@google.com8eec89c2014-08-29 22:03:07 +000032
33Summary of changes available at:
borenet@google.com2674ae02014-09-15 21:00:23 +000034%(revlog_url)s
35''')
borenet@google.com8eec89c2014-08-29 22:03:07 +000036
37
38def shorten_dep_path(dep):
39 """Shorten the given dep path if necessary."""
40 while len(dep) > 31:
41 dep = '.../' + dep.lstrip('./').partition('/')[2]
42 return dep
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000043
44
szager@chromium.org03fd85b2014-06-09 23:43:33 +000045def posix_path(path):
46 """Convert a possibly-Windows path to a posix-style path."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000047 (_, path) = os.path.splitdrive(path)
48 return path.replace(os.sep, '/')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000049
50
51def platform_path(path):
52 """Convert a path to the native path format of the host OS."""
53 return path.replace('/', os.sep)
54
55
56def find_gclient_root():
57 """Find the directory containing the .gclient file."""
58 cwd = posix_path(os.getcwd())
59 result = ''
60 for _ in xrange(len(cwd.split('/'))):
61 if os.path.exists(os.path.join(result, '.gclient')):
62 return result
63 result = os.path.join(result, os.pardir)
64 assert False, 'Could not find root of your gclient checkout.'
65
66
67def get_solution(gclient_root, dep_path):
68 """Find the solution in .gclient containing the dep being rolled."""
69 dep_path = os.path.relpath(dep_path, gclient_root)
70 cwd = os.getcwd().rstrip(os.sep) + os.sep
71 gclient_root = os.path.realpath(gclient_root)
72 gclient_path = os.path.join(gclient_root, '.gclient')
73 gclient_locals = {}
74 execfile(gclient_path, {}, gclient_locals)
75 for soln in gclient_locals['solutions']:
76 soln_relpath = platform_path(soln['name'].rstrip('/')) + os.sep
77 if (dep_path.startswith(soln_relpath) or
78 cwd.startswith(os.path.join(gclient_root, soln_relpath))):
79 return soln
80 assert False, 'Could not determine the parent project for %s' % dep_path
81
82
83def verify_git_revision(dep_path, revision):
84 """Verify that a git revision exists in a repository."""
85 p = Popen(['git', 'rev-list', '-n', '1', revision],
86 cwd=dep_path, stdout=PIPE, stderr=PIPE)
87 result = p.communicate()[0].strip()
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000088 if p.returncode != 0 or not SHA1_RE.match(result):
szager@chromium.org03fd85b2014-06-09 23:43:33 +000089 result = None
90 return result
91
92
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000093def get_svn_revision(dep_path, git_revision):
94 """Given a git revision, return the corresponding svn revision."""
95 p = Popen(['git', 'log', '-n', '1', '--pretty=format:%B', git_revision],
96 stdout=PIPE, cwd=dep_path)
97 (log, _) = p.communicate()
98 assert p.returncode == 0, 'git log %s failed.' % git_revision
99 for line in reversed(log.splitlines()):
100 m = GIT_SVN_ID_RE.match(line.strip())
101 if m:
102 return m.group(1)
103 return None
104
105
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000106def convert_svn_revision(dep_path, revision):
107 """Find the git revision corresponding to an svn revision."""
108 err_msg = 'Unknown error'
109 revision = int(revision)
thestig@chromium.orgbf13f082014-09-24 23:48:33 +0000110 latest_svn_rev = None
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000111 with open(os.devnull, 'w') as devnull:
112 for ref in ('HEAD', 'origin/master'):
113 try:
114 log_p = Popen(['git', 'log', ref],
115 cwd=dep_path, stdout=PIPE, stderr=devnull)
116 grep_p = Popen(['grep', '-e', '^commit ', '-e', '^ *git-svn-id: '],
117 stdin=log_p.stdout, stdout=PIPE, stderr=devnull)
118 git_rev = None
119 prev_svn_rev = None
120 for line in grep_p.stdout:
121 if line.startswith('commit '):
122 git_rev = line.split()[1]
123 continue
124 try:
125 svn_rev = int(line.split()[1].partition('@')[2])
126 except (IndexError, ValueError):
127 print >> sys.stderr, (
128 'WARNING: Could not parse svn revision out of "%s"' % line)
129 continue
thestig@chromium.orgbf13f082014-09-24 23:48:33 +0000130 if not latest_svn_rev or int(svn_rev) > int(latest_svn_rev):
131 latest_svn_rev = svn_rev
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000132 if svn_rev == revision:
133 return git_rev
134 if svn_rev > revision:
135 prev_svn_rev = svn_rev
136 continue
137 if prev_svn_rev:
138 err_msg = 'git history skips from revision %d to revision %d.' % (
139 svn_rev, prev_svn_rev)
140 else:
141 err_msg = (
142 'latest available revision is %d; you may need to '
thestig@chromium.orgbf13f082014-09-24 23:48:33 +0000143 '"git fetch origin" to get the latest commits.' %
144 latest_svn_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000145 finally:
146 log_p.terminate()
147 grep_p.terminate()
148 raise RuntimeError('No match for revision %d; %s' % (revision, err_msg))
149
150
151def get_git_revision(dep_path, revision):
152 """Convert the revision argument passed to the script to a git revision."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000153 svn_revision = None
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000154 if revision.startswith('r'):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000155 git_revision = convert_svn_revision(dep_path, revision[1:])
156 svn_revision = revision[1:]
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000157 elif re.search('[a-fA-F]', revision):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000158 git_revision = verify_git_revision(dep_path, revision)
159 svn_revision = get_svn_revision(dep_path, git_revision)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000160 elif len(revision) > 6:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000161 git_revision = verify_git_revision(dep_path, revision)
162 if git_revision:
163 svn_revision = get_svn_revision(dep_path, git_revision)
164 else:
165 git_revision = convert_svn_revision(dep_path, revision)
166 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000167 else:
168 try:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000169 git_revision = convert_svn_revision(dep_path, revision)
170 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000171 except RuntimeError:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000172 git_revision = verify_git_revision(dep_path, revision)
173 if not git_revision:
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000174 raise
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000175 svn_revision = get_svn_revision(dep_path, git_revision)
176 return git_revision, svn_revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000177
178
179def ast_err_msg(node):
180 return 'ERROR: Undexpected DEPS file AST structure at line %d column %d' % (
181 node.lineno, node.col_offset)
182
183
184def find_deps_section(deps_ast, section):
185 """Find a top-level section of the DEPS file in the AST."""
186 try:
187 result = [n.value for n in deps_ast.body if
188 n.__class__ is ast.Assign and
189 n.targets[0].__class__ is ast.Name and
190 n.targets[0].id == section][0]
191 return result
192 except IndexError:
193 return None
194
195
196def find_dict_index(dict_node, key):
197 """Given a key, find the index of the corresponding dict entry."""
198 assert dict_node.__class__ is ast.Dict, ast_err_msg(dict_node)
199 indices = [i for i, n in enumerate(dict_node.keys) if
200 n.__class__ is ast.Str and n.s == key]
201 assert len(indices) < 2, (
202 'Found redundant dict entries for key "%s"' % key)
203 return indices[0] if indices else None
204
205
206def update_node(deps_lines, deps_ast, node, git_revision):
207 """Update an AST node with the new git revision."""
208 if node.__class__ is ast.Str:
209 return update_string(deps_lines, node, git_revision)
210 elif node.__class__ is ast.BinOp:
211 return update_binop(deps_lines, deps_ast, node, git_revision)
212 elif node.__class__ is ast.Call:
213 return update_call(deps_lines, deps_ast, node, git_revision)
214 else:
215 assert False, ast_err_msg(node)
216
217
218def update_string(deps_lines, string_node, git_revision):
219 """Update a string node in the AST with the new git revision."""
220 line_idx = string_node.lineno - 1
221 start_idx = string_node.col_offset - 1
222 line = deps_lines[line_idx]
223 (prefix, sep, old_rev) = string_node.s.partition('@')
224 if sep:
225 start_idx = line.find(prefix + sep, start_idx) + len(prefix + sep)
226 tail_idx = start_idx + len(old_rev)
227 else:
228 start_idx = line.find(prefix, start_idx)
229 tail_idx = start_idx + len(prefix)
230 old_rev = prefix
231 deps_lines[line_idx] = line[:start_idx] + git_revision + line[tail_idx:]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000232 return line_idx
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000233
234
235def update_binop(deps_lines, deps_ast, binop_node, git_revision):
236 """Update a binary operation node in the AST with the new git revision."""
237 # Since the revision part is always last, assume that it's the right-hand
238 # operand that needs to be updated.
239 return update_node(deps_lines, deps_ast, binop_node.right, git_revision)
240
241
242def update_call(deps_lines, deps_ast, call_node, git_revision):
243 """Update a function call node in the AST with the new git revision."""
244 # The only call we know how to handle is Var()
245 assert call_node.func.id == 'Var', ast_err_msg(call_node)
246 assert call_node.args and call_node.args[0].__class__ is ast.Str, (
247 ast_err_msg(call_node))
248 return update_var(deps_lines, deps_ast, call_node.args[0].s, git_revision)
249
250
251def update_var(deps_lines, deps_ast, var_name, git_revision):
252 """Update an entry in the vars section of the DEPS file with the new
253 git revision."""
254 vars_node = find_deps_section(deps_ast, 'vars')
255 assert vars_node, 'Could not find "vars" section of DEPS file.'
256 var_idx = find_dict_index(vars_node, var_name)
257 assert var_idx is not None, (
258 'Could not find definition of "%s" var in DEPS file.' % var_name)
259 val_node = vars_node.values[var_idx]
260 return update_node(deps_lines, deps_ast, val_node, git_revision)
261
262
borenet@google.com2674ae02014-09-15 21:00:23 +0000263def short_rev(rev, dep_path):
264 return check_output(['git', 'rev-parse', '--short', rev],
265 cwd=dep_path).rstrip()
266
267
268def generate_commit_message(deps_section, dep_path, dep_name, new_rev):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000269 (url, _, old_rev) = deps_section[dep_name].partition('@')
270 if url.endswith('.git'):
271 url = url[:-4]
borenet@google.com2674ae02014-09-15 21:00:23 +0000272 old_rev_short = short_rev(old_rev, dep_path)
273 new_rev_short = short_rev(new_rev, dep_path)
274 url += '/+log/%s..%s' % (old_rev_short, new_rev_short)
275 old_svn_rev = get_svn_revision(dep_path, old_rev)
276 new_svn_rev = get_svn_revision(dep_path, new_rev)
277 svn_range_str = ''
278 if old_svn_rev and new_svn_rev:
279 svn_range_str = ' (svn %s:%s)' % (old_svn_rev, new_svn_rev)
280 return dedent(ROLL_DESCRIPTION_STR % {
281 'dep_path': shorten_dep_path(dep_name),
282 'before_rev': old_rev_short,
283 'after_rev': new_rev_short,
284 'svn_range': svn_range_str,
285 'revlog_url': url,
286 })
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000287
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000288def update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment):
289 line_idx = update_node(deps_lines, deps_ast, value_node, new_rev)
290 (content, _, _) = deps_lines[line_idx].partition('#')
291 if comment:
292 deps_lines[line_idx] = '%s # %s' % (content.rstrip(), comment)
293 else:
294 deps_lines[line_idx] = content.rstrip()
295
borenet@google.com2674ae02014-09-15 21:00:23 +0000296def update_deps(soln_path, dep_path, dep_name, new_rev, comment):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000297 """Update the DEPS file with the new git revision."""
298 commit_msg = ''
299 deps_file = os.path.join(soln_path, 'DEPS')
300 with open(deps_file) as fh:
301 deps_content = fh.read()
302 deps_locals = {}
303 def _Var(key):
304 return deps_locals['vars'][key]
305 deps_locals['Var'] = _Var
306 exec deps_content in {}, deps_locals
307 deps_lines = deps_content.splitlines()
308 deps_ast = ast.parse(deps_content, deps_file)
309 deps_node = find_deps_section(deps_ast, 'deps')
310 assert deps_node, 'Could not find "deps" section of DEPS file'
311 dep_idx = find_dict_index(deps_node, dep_name)
312 if dep_idx is not None:
313 value_node = deps_node.values[dep_idx]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000314 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
borenet@google.com2674ae02014-09-15 21:00:23 +0000315 commit_msg = generate_commit_message(deps_locals['deps'], dep_path,
316 dep_name, new_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000317 deps_os_node = find_deps_section(deps_ast, 'deps_os')
318 if deps_os_node:
319 for (os_name, os_node) in izip(deps_os_node.keys, deps_os_node.values):
320 dep_idx = find_dict_index(os_node, dep_name)
321 if dep_idx is not None:
322 value_node = os_node.values[dep_idx]
323 if value_node.__class__ is ast.Name and value_node.id == 'None':
324 pass
325 else:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000326 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000327 commit_msg = generate_commit_message(
borenet@google.com2674ae02014-09-15 21:00:23 +0000328 deps_locals['deps_os'][os_name], dep_path, dep_name, new_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000329 if commit_msg:
330 print 'Pinning %s' % dep_name
331 print 'to revision %s' % new_rev
332 print 'in %s' % deps_file
333 with open(deps_file, 'w') as fh:
334 for line in deps_lines:
335 print >> fh, line
336 with open(os.path.join(soln_path, '.git', 'MERGE_MSG'), 'a') as fh:
337 fh.write(commit_msg)
338 else:
339 print 'Could not find an entry in %s to update.' % deps_file
340 return 0 if commit_msg else 1
341
342
343def main(argv):
344 if len(argv) != 2 :
345 print >> sys.stderr, 'Usage: roll_dep.py <dep path> <svn revision>'
346 return 1
347 (dep_path, revision) = argv[0:2]
348 dep_path = platform_path(dep_path)
349 assert os.path.isdir(dep_path), 'No such directory: %s' % dep_path
350 gclient_root = find_gclient_root()
351 soln = get_solution(gclient_root, dep_path)
352 soln_path = os.path.relpath(os.path.join(gclient_root, soln['name']))
353 dep_name = posix_path(os.path.relpath(dep_path, gclient_root))
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000354 (git_rev, svn_rev) = get_git_revision(dep_path, revision)
355 comment = ('from svn revision %s' % svn_rev) if svn_rev else None
356 assert git_rev, 'Could not find git revision matching %s.' % revision
borenet@google.com2674ae02014-09-15 21:00:23 +0000357 return update_deps(soln_path, dep_path, dep_name, git_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000358
359if __name__ == '__main__':
360 sys.exit(main(sys.argv[1:]))