blob: f071fcc01c8b82bc17097ed68e69a268e2cb8647 [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)
110 with open(os.devnull, 'w') as devnull:
111 for ref in ('HEAD', 'origin/master'):
112 try:
113 log_p = Popen(['git', 'log', ref],
114 cwd=dep_path, stdout=PIPE, stderr=devnull)
115 grep_p = Popen(['grep', '-e', '^commit ', '-e', '^ *git-svn-id: '],
116 stdin=log_p.stdout, stdout=PIPE, stderr=devnull)
117 git_rev = None
118 prev_svn_rev = None
119 for line in grep_p.stdout:
120 if line.startswith('commit '):
121 git_rev = line.split()[1]
122 continue
123 try:
124 svn_rev = int(line.split()[1].partition('@')[2])
125 except (IndexError, ValueError):
126 print >> sys.stderr, (
127 'WARNING: Could not parse svn revision out of "%s"' % line)
128 continue
129 if svn_rev == revision:
130 return git_rev
131 if svn_rev > revision:
132 prev_svn_rev = svn_rev
133 continue
134 if prev_svn_rev:
135 err_msg = 'git history skips from revision %d to revision %d.' % (
136 svn_rev, prev_svn_rev)
137 else:
138 err_msg = (
139 'latest available revision is %d; you may need to '
140 '"git fetch origin" to get the latest commits.' % svn_rev)
141 finally:
142 log_p.terminate()
143 grep_p.terminate()
144 raise RuntimeError('No match for revision %d; %s' % (revision, err_msg))
145
146
147def get_git_revision(dep_path, revision):
148 """Convert the revision argument passed to the script to a git revision."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000149 svn_revision = None
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000150 if revision.startswith('r'):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000151 git_revision = convert_svn_revision(dep_path, revision[1:])
152 svn_revision = revision[1:]
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000153 elif re.search('[a-fA-F]', revision):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000154 git_revision = verify_git_revision(dep_path, revision)
155 svn_revision = get_svn_revision(dep_path, git_revision)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000156 elif len(revision) > 6:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000157 git_revision = verify_git_revision(dep_path, revision)
158 if git_revision:
159 svn_revision = get_svn_revision(dep_path, git_revision)
160 else:
161 git_revision = convert_svn_revision(dep_path, revision)
162 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000163 else:
164 try:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000165 git_revision = convert_svn_revision(dep_path, revision)
166 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000167 except RuntimeError:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000168 git_revision = verify_git_revision(dep_path, revision)
169 if not git_revision:
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000170 raise
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000171 svn_revision = get_svn_revision(dep_path, git_revision)
172 return git_revision, svn_revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000173
174
175def ast_err_msg(node):
176 return 'ERROR: Undexpected DEPS file AST structure at line %d column %d' % (
177 node.lineno, node.col_offset)
178
179
180def find_deps_section(deps_ast, section):
181 """Find a top-level section of the DEPS file in the AST."""
182 try:
183 result = [n.value for n in deps_ast.body if
184 n.__class__ is ast.Assign and
185 n.targets[0].__class__ is ast.Name and
186 n.targets[0].id == section][0]
187 return result
188 except IndexError:
189 return None
190
191
192def find_dict_index(dict_node, key):
193 """Given a key, find the index of the corresponding dict entry."""
194 assert dict_node.__class__ is ast.Dict, ast_err_msg(dict_node)
195 indices = [i for i, n in enumerate(dict_node.keys) if
196 n.__class__ is ast.Str and n.s == key]
197 assert len(indices) < 2, (
198 'Found redundant dict entries for key "%s"' % key)
199 return indices[0] if indices else None
200
201
202def update_node(deps_lines, deps_ast, node, git_revision):
203 """Update an AST node with the new git revision."""
204 if node.__class__ is ast.Str:
205 return update_string(deps_lines, node, git_revision)
206 elif node.__class__ is ast.BinOp:
207 return update_binop(deps_lines, deps_ast, node, git_revision)
208 elif node.__class__ is ast.Call:
209 return update_call(deps_lines, deps_ast, node, git_revision)
210 else:
211 assert False, ast_err_msg(node)
212
213
214def update_string(deps_lines, string_node, git_revision):
215 """Update a string node in the AST with the new git revision."""
216 line_idx = string_node.lineno - 1
217 start_idx = string_node.col_offset - 1
218 line = deps_lines[line_idx]
219 (prefix, sep, old_rev) = string_node.s.partition('@')
220 if sep:
221 start_idx = line.find(prefix + sep, start_idx) + len(prefix + sep)
222 tail_idx = start_idx + len(old_rev)
223 else:
224 start_idx = line.find(prefix, start_idx)
225 tail_idx = start_idx + len(prefix)
226 old_rev = prefix
227 deps_lines[line_idx] = line[:start_idx] + git_revision + line[tail_idx:]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000228 return line_idx
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000229
230
231def update_binop(deps_lines, deps_ast, binop_node, git_revision):
232 """Update a binary operation node in the AST with the new git revision."""
233 # Since the revision part is always last, assume that it's the right-hand
234 # operand that needs to be updated.
235 return update_node(deps_lines, deps_ast, binop_node.right, git_revision)
236
237
238def update_call(deps_lines, deps_ast, call_node, git_revision):
239 """Update a function call node in the AST with the new git revision."""
240 # The only call we know how to handle is Var()
241 assert call_node.func.id == 'Var', ast_err_msg(call_node)
242 assert call_node.args and call_node.args[0].__class__ is ast.Str, (
243 ast_err_msg(call_node))
244 return update_var(deps_lines, deps_ast, call_node.args[0].s, git_revision)
245
246
247def update_var(deps_lines, deps_ast, var_name, git_revision):
248 """Update an entry in the vars section of the DEPS file with the new
249 git revision."""
250 vars_node = find_deps_section(deps_ast, 'vars')
251 assert vars_node, 'Could not find "vars" section of DEPS file.'
252 var_idx = find_dict_index(vars_node, var_name)
253 assert var_idx is not None, (
254 'Could not find definition of "%s" var in DEPS file.' % var_name)
255 val_node = vars_node.values[var_idx]
256 return update_node(deps_lines, deps_ast, val_node, git_revision)
257
258
borenet@google.com2674ae02014-09-15 21:00:23 +0000259def short_rev(rev, dep_path):
260 return check_output(['git', 'rev-parse', '--short', rev],
261 cwd=dep_path).rstrip()
262
263
264def generate_commit_message(deps_section, dep_path, dep_name, new_rev):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000265 (url, _, old_rev) = deps_section[dep_name].partition('@')
266 if url.endswith('.git'):
267 url = url[:-4]
borenet@google.com2674ae02014-09-15 21:00:23 +0000268 old_rev_short = short_rev(old_rev, dep_path)
269 new_rev_short = short_rev(new_rev, dep_path)
270 url += '/+log/%s..%s' % (old_rev_short, new_rev_short)
271 old_svn_rev = get_svn_revision(dep_path, old_rev)
272 new_svn_rev = get_svn_revision(dep_path, new_rev)
273 svn_range_str = ''
274 if old_svn_rev and new_svn_rev:
275 svn_range_str = ' (svn %s:%s)' % (old_svn_rev, new_svn_rev)
276 return dedent(ROLL_DESCRIPTION_STR % {
277 'dep_path': shorten_dep_path(dep_name),
278 'before_rev': old_rev_short,
279 'after_rev': new_rev_short,
280 'svn_range': svn_range_str,
281 'revlog_url': url,
282 })
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000283
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000284def update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment):
285 line_idx = update_node(deps_lines, deps_ast, value_node, new_rev)
286 (content, _, _) = deps_lines[line_idx].partition('#')
287 if comment:
288 deps_lines[line_idx] = '%s # %s' % (content.rstrip(), comment)
289 else:
290 deps_lines[line_idx] = content.rstrip()
291
borenet@google.com2674ae02014-09-15 21:00:23 +0000292def update_deps(soln_path, dep_path, dep_name, new_rev, comment):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000293 """Update the DEPS file with the new git revision."""
294 commit_msg = ''
295 deps_file = os.path.join(soln_path, 'DEPS')
296 with open(deps_file) as fh:
297 deps_content = fh.read()
298 deps_locals = {}
299 def _Var(key):
300 return deps_locals['vars'][key]
301 deps_locals['Var'] = _Var
302 exec deps_content in {}, deps_locals
303 deps_lines = deps_content.splitlines()
304 deps_ast = ast.parse(deps_content, deps_file)
305 deps_node = find_deps_section(deps_ast, 'deps')
306 assert deps_node, 'Could not find "deps" section of DEPS file'
307 dep_idx = find_dict_index(deps_node, dep_name)
308 if dep_idx is not None:
309 value_node = deps_node.values[dep_idx]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000310 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
borenet@google.com2674ae02014-09-15 21:00:23 +0000311 commit_msg = generate_commit_message(deps_locals['deps'], dep_path,
312 dep_name, new_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000313 deps_os_node = find_deps_section(deps_ast, 'deps_os')
314 if deps_os_node:
315 for (os_name, os_node) in izip(deps_os_node.keys, deps_os_node.values):
316 dep_idx = find_dict_index(os_node, dep_name)
317 if dep_idx is not None:
318 value_node = os_node.values[dep_idx]
319 if value_node.__class__ is ast.Name and value_node.id == 'None':
320 pass
321 else:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000322 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000323 commit_msg = generate_commit_message(
borenet@google.com2674ae02014-09-15 21:00:23 +0000324 deps_locals['deps_os'][os_name], dep_path, dep_name, new_rev)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000325 if commit_msg:
326 print 'Pinning %s' % dep_name
327 print 'to revision %s' % new_rev
328 print 'in %s' % deps_file
329 with open(deps_file, 'w') as fh:
330 for line in deps_lines:
331 print >> fh, line
332 with open(os.path.join(soln_path, '.git', 'MERGE_MSG'), 'a') as fh:
333 fh.write(commit_msg)
334 else:
335 print 'Could not find an entry in %s to update.' % deps_file
336 return 0 if commit_msg else 1
337
338
339def main(argv):
340 if len(argv) != 2 :
341 print >> sys.stderr, 'Usage: roll_dep.py <dep path> <svn revision>'
342 return 1
343 (dep_path, revision) = argv[0:2]
344 dep_path = platform_path(dep_path)
345 assert os.path.isdir(dep_path), 'No such directory: %s' % dep_path
346 gclient_root = find_gclient_root()
347 soln = get_solution(gclient_root, dep_path)
348 soln_path = os.path.relpath(os.path.join(gclient_root, soln['name']))
349 dep_name = posix_path(os.path.relpath(dep_path, gclient_root))
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000350 (git_rev, svn_rev) = get_git_revision(dep_path, revision)
351 comment = ('from svn revision %s' % svn_rev) if svn_rev else None
352 assert git_rev, 'Could not find git revision matching %s.' % revision
borenet@google.com2674ae02014-09-15 21:00:23 +0000353 return update_deps(soln_path, dep_path, dep_name, git_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000354
355if __name__ == '__main__':
356 sys.exit(main(sys.argv[1:]))