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