blob: 57a882b0d7915ab17a2f272c21a9af2a9e072308 [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
24from subprocess import Popen, PIPE
25from 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.com8eec89c2014-08-29 22:03:07 +000030ROLL_DESCRIPTION_STR = '''Roll %s from %s to %s
31
32Summary of changes available at:
33%s
34'''
35
36
37def shorten_dep_path(dep):
38 """Shorten the given dep path if necessary."""
39 while len(dep) > 31:
40 dep = '.../' + dep.lstrip('./').partition('/')[2]
41 return dep
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000042
43
szager@chromium.org03fd85b2014-06-09 23:43:33 +000044def posix_path(path):
45 """Convert a possibly-Windows path to a posix-style path."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000046 (_, path) = os.path.splitdrive(path)
47 return path.replace(os.sep, '/')
szager@chromium.org03fd85b2014-06-09 23:43:33 +000048
49
50def platform_path(path):
51 """Convert a path to the native path format of the host OS."""
52 return path.replace('/', os.sep)
53
54
55def find_gclient_root():
56 """Find the directory containing the .gclient file."""
57 cwd = posix_path(os.getcwd())
58 result = ''
59 for _ in xrange(len(cwd.split('/'))):
60 if os.path.exists(os.path.join(result, '.gclient')):
61 return result
62 result = os.path.join(result, os.pardir)
63 assert False, 'Could not find root of your gclient checkout.'
64
65
66def get_solution(gclient_root, dep_path):
67 """Find the solution in .gclient containing the dep being rolled."""
68 dep_path = os.path.relpath(dep_path, gclient_root)
69 cwd = os.getcwd().rstrip(os.sep) + os.sep
70 gclient_root = os.path.realpath(gclient_root)
71 gclient_path = os.path.join(gclient_root, '.gclient')
72 gclient_locals = {}
73 execfile(gclient_path, {}, gclient_locals)
74 for soln in gclient_locals['solutions']:
75 soln_relpath = platform_path(soln['name'].rstrip('/')) + os.sep
76 if (dep_path.startswith(soln_relpath) or
77 cwd.startswith(os.path.join(gclient_root, soln_relpath))):
78 return soln
79 assert False, 'Could not determine the parent project for %s' % dep_path
80
81
82def verify_git_revision(dep_path, revision):
83 """Verify that a git revision exists in a repository."""
84 p = Popen(['git', 'rev-list', '-n', '1', revision],
85 cwd=dep_path, stdout=PIPE, stderr=PIPE)
86 result = p.communicate()[0].strip()
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000087 if p.returncode != 0 or not SHA1_RE.match(result):
szager@chromium.org03fd85b2014-06-09 23:43:33 +000088 result = None
89 return result
90
91
szager@chromium.org9e43b8b2014-08-01 18:53:45 +000092def get_svn_revision(dep_path, git_revision):
93 """Given a git revision, return the corresponding svn revision."""
94 p = Popen(['git', 'log', '-n', '1', '--pretty=format:%B', git_revision],
95 stdout=PIPE, cwd=dep_path)
96 (log, _) = p.communicate()
97 assert p.returncode == 0, 'git log %s failed.' % git_revision
98 for line in reversed(log.splitlines()):
99 m = GIT_SVN_ID_RE.match(line.strip())
100 if m:
101 return m.group(1)
102 return None
103
104
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000105def convert_svn_revision(dep_path, revision):
106 """Find the git revision corresponding to an svn revision."""
107 err_msg = 'Unknown error'
108 revision = int(revision)
109 with open(os.devnull, 'w') as devnull:
110 for ref in ('HEAD', 'origin/master'):
111 try:
112 log_p = Popen(['git', 'log', ref],
113 cwd=dep_path, stdout=PIPE, stderr=devnull)
114 grep_p = Popen(['grep', '-e', '^commit ', '-e', '^ *git-svn-id: '],
115 stdin=log_p.stdout, stdout=PIPE, stderr=devnull)
116 git_rev = None
117 prev_svn_rev = None
118 for line in grep_p.stdout:
119 if line.startswith('commit '):
120 git_rev = line.split()[1]
121 continue
122 try:
123 svn_rev = int(line.split()[1].partition('@')[2])
124 except (IndexError, ValueError):
125 print >> sys.stderr, (
126 'WARNING: Could not parse svn revision out of "%s"' % line)
127 continue
128 if svn_rev == revision:
129 return git_rev
130 if svn_rev > revision:
131 prev_svn_rev = svn_rev
132 continue
133 if prev_svn_rev:
134 err_msg = 'git history skips from revision %d to revision %d.' % (
135 svn_rev, prev_svn_rev)
136 else:
137 err_msg = (
138 'latest available revision is %d; you may need to '
139 '"git fetch origin" to get the latest commits.' % svn_rev)
140 finally:
141 log_p.terminate()
142 grep_p.terminate()
143 raise RuntimeError('No match for revision %d; %s' % (revision, err_msg))
144
145
146def get_git_revision(dep_path, revision):
147 """Convert the revision argument passed to the script to a git revision."""
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000148 svn_revision = None
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000149 if revision.startswith('r'):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000150 git_revision = convert_svn_revision(dep_path, revision[1:])
151 svn_revision = revision[1:]
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000152 elif re.search('[a-fA-F]', revision):
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000153 git_revision = verify_git_revision(dep_path, revision)
154 svn_revision = get_svn_revision(dep_path, git_revision)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000155 elif len(revision) > 6:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000156 git_revision = verify_git_revision(dep_path, revision)
157 if git_revision:
158 svn_revision = get_svn_revision(dep_path, git_revision)
159 else:
160 git_revision = convert_svn_revision(dep_path, revision)
161 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000162 else:
163 try:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000164 git_revision = convert_svn_revision(dep_path, revision)
165 svn_revision = revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000166 except RuntimeError:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000167 git_revision = verify_git_revision(dep_path, revision)
168 if not git_revision:
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000169 raise
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000170 svn_revision = get_svn_revision(dep_path, git_revision)
171 return git_revision, svn_revision
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000172
173
174def ast_err_msg(node):
175 return 'ERROR: Undexpected DEPS file AST structure at line %d column %d' % (
176 node.lineno, node.col_offset)
177
178
179def find_deps_section(deps_ast, section):
180 """Find a top-level section of the DEPS file in the AST."""
181 try:
182 result = [n.value for n in deps_ast.body if
183 n.__class__ is ast.Assign and
184 n.targets[0].__class__ is ast.Name and
185 n.targets[0].id == section][0]
186 return result
187 except IndexError:
188 return None
189
190
191def find_dict_index(dict_node, key):
192 """Given a key, find the index of the corresponding dict entry."""
193 assert dict_node.__class__ is ast.Dict, ast_err_msg(dict_node)
194 indices = [i for i, n in enumerate(dict_node.keys) if
195 n.__class__ is ast.Str and n.s == key]
196 assert len(indices) < 2, (
197 'Found redundant dict entries for key "%s"' % key)
198 return indices[0] if indices else None
199
200
201def update_node(deps_lines, deps_ast, node, git_revision):
202 """Update an AST node with the new git revision."""
203 if node.__class__ is ast.Str:
204 return update_string(deps_lines, node, git_revision)
205 elif node.__class__ is ast.BinOp:
206 return update_binop(deps_lines, deps_ast, node, git_revision)
207 elif node.__class__ is ast.Call:
208 return update_call(deps_lines, deps_ast, node, git_revision)
209 else:
210 assert False, ast_err_msg(node)
211
212
213def update_string(deps_lines, string_node, git_revision):
214 """Update a string node in the AST with the new git revision."""
215 line_idx = string_node.lineno - 1
216 start_idx = string_node.col_offset - 1
217 line = deps_lines[line_idx]
218 (prefix, sep, old_rev) = string_node.s.partition('@')
219 if sep:
220 start_idx = line.find(prefix + sep, start_idx) + len(prefix + sep)
221 tail_idx = start_idx + len(old_rev)
222 else:
223 start_idx = line.find(prefix, start_idx)
224 tail_idx = start_idx + len(prefix)
225 old_rev = prefix
226 deps_lines[line_idx] = line[:start_idx] + git_revision + line[tail_idx:]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000227 return line_idx
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000228
229
230def update_binop(deps_lines, deps_ast, binop_node, git_revision):
231 """Update a binary operation node in the AST with the new git revision."""
232 # Since the revision part is always last, assume that it's the right-hand
233 # operand that needs to be updated.
234 return update_node(deps_lines, deps_ast, binop_node.right, git_revision)
235
236
237def update_call(deps_lines, deps_ast, call_node, git_revision):
238 """Update a function call node in the AST with the new git revision."""
239 # The only call we know how to handle is Var()
240 assert call_node.func.id == 'Var', ast_err_msg(call_node)
241 assert call_node.args and call_node.args[0].__class__ is ast.Str, (
242 ast_err_msg(call_node))
243 return update_var(deps_lines, deps_ast, call_node.args[0].s, git_revision)
244
245
246def update_var(deps_lines, deps_ast, var_name, git_revision):
247 """Update an entry in the vars section of the DEPS file with the new
248 git revision."""
249 vars_node = find_deps_section(deps_ast, 'vars')
250 assert vars_node, 'Could not find "vars" section of DEPS file.'
251 var_idx = find_dict_index(vars_node, var_name)
252 assert var_idx is not None, (
253 'Could not find definition of "%s" var in DEPS file.' % var_name)
254 val_node = vars_node.values[var_idx]
255 return update_node(deps_lines, deps_ast, val_node, git_revision)
256
257
258def generate_commit_message(deps_section, dep_name, new_rev):
259 (url, _, old_rev) = deps_section[dep_name].partition('@')
260 if url.endswith('.git'):
261 url = url[:-4]
262 url += '/+log/%s..%s' % (old_rev[:12], new_rev[:12])
borenet@google.com8eec89c2014-08-29 22:03:07 +0000263 return dedent(ROLL_DESCRIPTION_STR % (
264 shorten_dep_path(dep_name), old_rev[:12], new_rev[:12], url))
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000265
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000266def update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment):
267 line_idx = update_node(deps_lines, deps_ast, value_node, new_rev)
268 (content, _, _) = deps_lines[line_idx].partition('#')
269 if comment:
270 deps_lines[line_idx] = '%s # %s' % (content.rstrip(), comment)
271 else:
272 deps_lines[line_idx] = content.rstrip()
273
274def update_deps(soln_path, dep_name, new_rev, comment):
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000275 """Update the DEPS file with the new git revision."""
276 commit_msg = ''
277 deps_file = os.path.join(soln_path, 'DEPS')
278 with open(deps_file) as fh:
279 deps_content = fh.read()
280 deps_locals = {}
281 def _Var(key):
282 return deps_locals['vars'][key]
283 deps_locals['Var'] = _Var
284 exec deps_content in {}, deps_locals
285 deps_lines = deps_content.splitlines()
286 deps_ast = ast.parse(deps_content, deps_file)
287 deps_node = find_deps_section(deps_ast, 'deps')
288 assert deps_node, 'Could not find "deps" section of DEPS file'
289 dep_idx = find_dict_index(deps_node, dep_name)
290 if dep_idx is not None:
291 value_node = deps_node.values[dep_idx]
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000292 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000293 commit_msg = generate_commit_message(deps_locals['deps'], dep_name, new_rev)
294 deps_os_node = find_deps_section(deps_ast, 'deps_os')
295 if deps_os_node:
296 for (os_name, os_node) in izip(deps_os_node.keys, deps_os_node.values):
297 dep_idx = find_dict_index(os_node, dep_name)
298 if dep_idx is not None:
299 value_node = os_node.values[dep_idx]
300 if value_node.__class__ is ast.Name and value_node.id == 'None':
301 pass
302 else:
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000303 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000304 commit_msg = generate_commit_message(
305 deps_locals['deps_os'][os_name], dep_name, new_rev)
306 if commit_msg:
307 print 'Pinning %s' % dep_name
308 print 'to revision %s' % new_rev
309 print 'in %s' % deps_file
310 with open(deps_file, 'w') as fh:
311 for line in deps_lines:
312 print >> fh, line
313 with open(os.path.join(soln_path, '.git', 'MERGE_MSG'), 'a') as fh:
314 fh.write(commit_msg)
315 else:
316 print 'Could not find an entry in %s to update.' % deps_file
317 return 0 if commit_msg else 1
318
319
320def main(argv):
321 if len(argv) != 2 :
322 print >> sys.stderr, 'Usage: roll_dep.py <dep path> <svn revision>'
323 return 1
324 (dep_path, revision) = argv[0:2]
325 dep_path = platform_path(dep_path)
326 assert os.path.isdir(dep_path), 'No such directory: %s' % dep_path
327 gclient_root = find_gclient_root()
328 soln = get_solution(gclient_root, dep_path)
329 soln_path = os.path.relpath(os.path.join(gclient_root, soln['name']))
330 dep_name = posix_path(os.path.relpath(dep_path, gclient_root))
szager@chromium.org9e43b8b2014-08-01 18:53:45 +0000331 (git_rev, svn_rev) = get_git_revision(dep_path, revision)
332 comment = ('from svn revision %s' % svn_rev) if svn_rev else None
333 assert git_rev, 'Could not find git revision matching %s.' % revision
334 return update_deps(soln_path, dep_name, git_rev, comment)
szager@chromium.org03fd85b2014-06-09 23:43:33 +0000335
336if __name__ == '__main__':
337 sys.exit(main(sys.argv[1:]))