blob: a7c9a28033fa58d8ab11c6c187bfca9c5bd8a652 [file] [log] [blame]
Edward Lesmes7149d232019-08-12 21:04:04 +00001#!/usr/bin/env python
machenbach26a201f2016-08-30 00:43:13 -07002# 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"""Rolls a git-svn dependency.
7
8It takes the path to a dep and a git commit hash or svn revision, and updates
9the parent repo's DEPS file with the corresponding git commit hash.
10
11Sample invocation:
12
13[chromium/src]$ roll-dep-svn third_party/WebKit 12345
14
15After the script completes, the DEPS file will be dirty with the new revision.
16The user can then:
17
18$ git add DEPS
19$ git commit
20"""
21
Raul Tambre80ee78e2019-05-06 22:41:05 +000022from __future__ import print_function
23
machenbach26a201f2016-08-30 00:43:13 -070024import ast
25import optparse
26import os
27import re
28import sys
29
30from itertools import izip
31from subprocess import check_output, Popen, PIPE
32from textwrap import dedent
33
34
35SHA1_RE = re.compile('^[a-fA-F0-9]{40}$')
36GIT_SVN_ID_RE = re.compile('^git-svn-id: .*@([0-9]+) .*$')
37ROLL_DESCRIPTION_STR = (
38'''Roll %(dep_path)s %(before_rev)s:%(after_rev)s%(svn_range)s
39
40Summary of changes available at:
41%(revlog_url)s
42''')
43
44
45def shorten_dep_path(dep):
46 """Shorten the given dep path if necessary."""
47 while len(dep) > 31:
48 dep = '.../' + dep.lstrip('./').partition('/')[2]
49 return dep
50
51
52def posix_path(path):
53 """Convert a possibly-Windows path to a posix-style path."""
54 (_, path) = os.path.splitdrive(path)
55 return path.replace(os.sep, '/')
56
57
58def platform_path(path):
59 """Convert a path to the native path format of the host OS."""
60 return path.replace('/', os.sep)
61
62
63def find_gclient_root():
64 """Find the directory containing the .gclient file."""
65 cwd = posix_path(os.getcwd())
66 result = ''
67 for _ in xrange(len(cwd.split('/'))):
68 if os.path.exists(os.path.join(result, '.gclient')):
69 return result
70 result = os.path.join(result, os.pardir)
71 assert False, 'Could not find root of your gclient checkout.'
72
73
74def get_solution(gclient_root, dep_path):
75 """Find the solution in .gclient containing the dep being rolled."""
76 dep_path = os.path.relpath(dep_path, gclient_root)
77 cwd = os.getcwd().rstrip(os.sep) + os.sep
78 gclient_root = os.path.realpath(gclient_root)
79 gclient_path = os.path.join(gclient_root, '.gclient')
80 gclient_locals = {}
81 execfile(gclient_path, {}, gclient_locals)
82 for soln in gclient_locals['solutions']:
83 soln_relpath = platform_path(soln['name'].rstrip('/')) + os.sep
84 if (dep_path.startswith(soln_relpath) or
85 cwd.startswith(os.path.join(gclient_root, soln_relpath))):
86 return soln
87 assert False, 'Could not determine the parent project for %s' % dep_path
88
89
90def is_git_hash(revision):
91 """Determines if a given revision is a git hash."""
92 return SHA1_RE.match(revision)
93
94
95def verify_git_revision(dep_path, revision):
96 """Verify that a git revision exists in a repository."""
97 p = Popen(['git', 'rev-list', '-n', '1', revision],
98 cwd=dep_path, stdout=PIPE, stderr=PIPE)
99 result = p.communicate()[0].strip()
100 if p.returncode != 0 or not is_git_hash(result):
101 result = None
102 return result
103
104
105def get_svn_revision(dep_path, git_revision):
106 """Given a git revision, return the corresponding svn revision."""
107 p = Popen(['git', 'log', '-n', '1', '--pretty=format:%B', git_revision],
108 stdout=PIPE, cwd=dep_path)
109 (log, _) = p.communicate()
110 assert p.returncode == 0, 'git log %s failed.' % git_revision
111 for line in reversed(log.splitlines()):
112 m = GIT_SVN_ID_RE.match(line.strip())
113 if m:
114 return m.group(1)
115 return None
116
117
118def convert_svn_revision(dep_path, revision):
119 """Find the git revision corresponding to an svn revision."""
120 err_msg = 'Unknown error'
121 revision = int(revision)
122 latest_svn_rev = None
123 with open(os.devnull, 'w') as devnull:
124 for ref in ('HEAD', 'origin/master'):
125 try:
126 log_p = Popen(['git', 'log', ref],
127 cwd=dep_path, stdout=PIPE, stderr=devnull)
128 grep_p = Popen(['grep', '-e', '^commit ', '-e', '^ *git-svn-id: '],
129 stdin=log_p.stdout, stdout=PIPE, stderr=devnull)
130 git_rev = None
131 prev_svn_rev = None
132 for line in grep_p.stdout:
133 if line.startswith('commit '):
134 git_rev = line.split()[1]
135 continue
136 try:
137 svn_rev = int(line.split()[1].partition('@')[2])
138 except (IndexError, ValueError):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000139 print('WARNING: Could not parse svn revision out of "%s"' % line,
140 file=sys.stderr)
machenbach26a201f2016-08-30 00:43:13 -0700141 continue
142 if not latest_svn_rev or int(svn_rev) > int(latest_svn_rev):
143 latest_svn_rev = svn_rev
144 if svn_rev == revision:
145 return git_rev
146 if svn_rev > revision:
147 prev_svn_rev = svn_rev
148 continue
149 if prev_svn_rev:
150 err_msg = 'git history skips from revision %d to revision %d.' % (
151 svn_rev, prev_svn_rev)
152 else:
153 err_msg = (
154 'latest available revision is %d; you may need to '
155 '"git fetch origin" to get the latest commits.' %
156 latest_svn_rev)
157 finally:
158 log_p.terminate()
159 grep_p.terminate()
160 raise RuntimeError('No match for revision %d; %s' % (revision, err_msg))
161
162
163def get_git_revision(dep_path, revision):
164 """Convert the revision argument passed to the script to a git revision."""
165 svn_revision = None
166 if revision.startswith('r'):
167 git_revision = convert_svn_revision(dep_path, revision[1:])
168 svn_revision = revision[1:]
169 elif re.search('[a-fA-F]', revision):
170 git_revision = verify_git_revision(dep_path, revision)
171 if not git_revision:
172 raise RuntimeError('Please \'git fetch origin\' in %s' % dep_path)
173 svn_revision = get_svn_revision(dep_path, git_revision)
174 elif len(revision) > 6:
175 git_revision = verify_git_revision(dep_path, revision)
176 if git_revision:
177 svn_revision = get_svn_revision(dep_path, git_revision)
178 else:
179 git_revision = convert_svn_revision(dep_path, revision)
180 svn_revision = revision
181 else:
182 try:
183 git_revision = convert_svn_revision(dep_path, revision)
184 svn_revision = revision
185 except RuntimeError:
186 git_revision = verify_git_revision(dep_path, revision)
187 if not git_revision:
188 raise
189 svn_revision = get_svn_revision(dep_path, git_revision)
190 return git_revision, svn_revision
191
192
193def ast_err_msg(node):
194 return 'ERROR: Undexpected DEPS file AST structure at line %d column %d' % (
195 node.lineno, node.col_offset)
196
197
198def find_deps_section(deps_ast, section):
199 """Find a top-level section of the DEPS file in the AST."""
200 try:
201 result = [n.value for n in deps_ast.body if
202 n.__class__ is ast.Assign and
203 n.targets[0].__class__ is ast.Name and
204 n.targets[0].id == section][0]
205 return result
206 except IndexError:
207 return None
208
209
210def find_dict_index(dict_node, key):
211 """Given a key, find the index of the corresponding dict entry."""
212 assert dict_node.__class__ is ast.Dict, ast_err_msg(dict_node)
213 indices = [i for i, n in enumerate(dict_node.keys) if
214 n.__class__ is ast.Str and n.s == key]
215 assert len(indices) < 2, (
216 'Found redundant dict entries for key "%s"' % key)
217 return indices[0] if indices else None
218
219
220def update_node(deps_lines, deps_ast, node, git_revision):
221 """Update an AST node with the new git revision."""
222 if node.__class__ is ast.Str:
223 return update_string(deps_lines, node, git_revision)
224 elif node.__class__ is ast.BinOp:
225 return update_binop(deps_lines, deps_ast, node, git_revision)
226 elif node.__class__ is ast.Call:
227 return update_call(deps_lines, deps_ast, node, git_revision)
Paweł Hajdan, Jre83d0242017-10-10 12:14:10 +0200228 elif node.__class__ is ast.Dict:
229 return update_dict(deps_lines, deps_ast, node, git_revision)
machenbach26a201f2016-08-30 00:43:13 -0700230 else:
231 assert False, ast_err_msg(node)
232
233
234def update_string(deps_lines, string_node, git_revision):
235 """Update a string node in the AST with the new git revision."""
236 line_idx = string_node.lineno - 1
237 start_idx = string_node.col_offset - 1
238 line = deps_lines[line_idx]
239 (prefix, sep, old_rev) = string_node.s.partition('@')
240 if sep:
241 start_idx = line.find(prefix + sep, start_idx) + len(prefix + sep)
242 tail_idx = start_idx + len(old_rev)
243 else:
244 start_idx = line.find(prefix, start_idx)
245 tail_idx = start_idx + len(prefix)
246 old_rev = prefix
247 deps_lines[line_idx] = line[:start_idx] + git_revision + line[tail_idx:]
248 return line_idx
249
250
251def update_binop(deps_lines, deps_ast, binop_node, git_revision):
252 """Update a binary operation node in the AST with the new git revision."""
253 # Since the revision part is always last, assume that it's the right-hand
254 # operand that needs to be updated.
255 return update_node(deps_lines, deps_ast, binop_node.right, git_revision)
256
257
258def update_call(deps_lines, deps_ast, call_node, git_revision):
259 """Update a function call node in the AST with the new git revision."""
260 # The only call we know how to handle is Var()
261 assert call_node.func.id == 'Var', ast_err_msg(call_node)
262 assert call_node.args and call_node.args[0].__class__ is ast.Str, (
263 ast_err_msg(call_node))
264 return update_var(deps_lines, deps_ast, call_node.args[0].s, git_revision)
265
266
Paweł Hajdan, Jre83d0242017-10-10 12:14:10 +0200267def update_dict(deps_lines, deps_ast, dict_node, git_revision):
268 """Update a dict node in the AST with the new git revision."""
269 for key, value in zip(dict_node.keys, dict_node.values):
270 if key.__class__ is ast.Str and key.s == 'url':
271 return update_node(deps_lines, deps_ast, value, git_revision)
272
273
machenbach26a201f2016-08-30 00:43:13 -0700274def update_var(deps_lines, deps_ast, var_name, git_revision):
275 """Update an entry in the vars section of the DEPS file with the new
276 git revision."""
277 vars_node = find_deps_section(deps_ast, 'vars')
278 assert vars_node, 'Could not find "vars" section of DEPS file.'
279 var_idx = find_dict_index(vars_node, var_name)
280 assert var_idx is not None, (
281 'Could not find definition of "%s" var in DEPS file.' % var_name)
282 val_node = vars_node.values[var_idx]
283 return update_node(deps_lines, deps_ast, val_node, git_revision)
284
285
286def short_rev(rev, dep_path):
287 return check_output(['git', 'rev-parse', '--short', rev],
288 cwd=dep_path).rstrip()
289
290
291def generate_commit_message(deps_section, dep_path, dep_name, new_rev):
Paweł Hajdan, Jre83d0242017-10-10 12:14:10 +0200292 dep_url = deps_section[dep_name]
293 if isinstance(dep_url, dict):
294 dep_url = dep_url['url']
295
296 (url, _, old_rev) = dep_url.partition('@')
machenbach26a201f2016-08-30 00:43:13 -0700297 if url.endswith('.git'):
298 url = url[:-4]
299 old_rev_short = short_rev(old_rev, dep_path)
300 new_rev_short = short_rev(new_rev, dep_path)
301 url += '/+log/%s..%s' % (old_rev_short, new_rev_short)
302 try:
303 old_svn_rev = get_svn_revision(dep_path, old_rev)
304 new_svn_rev = get_svn_revision(dep_path, new_rev)
305 except Exception:
306 # Ignore failures that might arise from the repo not being checked out.
307 old_svn_rev = new_svn_rev = None
308 svn_range_str = ''
309 if old_svn_rev and new_svn_rev:
310 svn_range_str = ' (svn %s:%s)' % (old_svn_rev, new_svn_rev)
311 return dedent(ROLL_DESCRIPTION_STR % {
312 'dep_path': shorten_dep_path(dep_name),
313 'before_rev': old_rev_short,
314 'after_rev': new_rev_short,
315 'svn_range': svn_range_str,
316 'revlog_url': url,
317 })
318
319
320def update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment):
321 line_idx = update_node(deps_lines, deps_ast, value_node, new_rev)
322 (content, _, _) = deps_lines[line_idx].partition('#')
323 if comment:
324 deps_lines[line_idx] = '%s # %s' % (content.rstrip(), comment)
325 else:
326 deps_lines[line_idx] = content.rstrip()
327
328
329def update_deps(deps_file, dep_path, dep_name, new_rev, comment):
330 """Update the DEPS file with the new git revision."""
331 commit_msg = ''
332 with open(deps_file) as fh:
333 deps_content = fh.read()
334 deps_locals = {}
335 def _Var(key):
336 return deps_locals['vars'][key]
337 deps_locals['Var'] = _Var
338 exec deps_content in {}, deps_locals
339 deps_lines = deps_content.splitlines()
340 deps_ast = ast.parse(deps_content, deps_file)
341 deps_node = find_deps_section(deps_ast, 'deps')
342 assert deps_node, 'Could not find "deps" section of DEPS file'
343 dep_idx = find_dict_index(deps_node, dep_name)
344 if dep_idx is not None:
345 value_node = deps_node.values[dep_idx]
346 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
347 commit_msg = generate_commit_message(deps_locals['deps'], dep_path,
348 dep_name, new_rev)
349 deps_os_node = find_deps_section(deps_ast, 'deps_os')
350 if deps_os_node:
351 for (os_name, os_node) in izip(deps_os_node.keys, deps_os_node.values):
352 dep_idx = find_dict_index(os_node, dep_name)
353 if dep_idx is not None:
354 value_node = os_node.values[dep_idx]
355 if value_node.__class__ is ast.Name and value_node.id == 'None':
356 pass
357 else:
358 update_deps_entry(deps_lines, deps_ast, value_node, new_rev, comment)
359 commit_msg = generate_commit_message(
360 deps_locals['deps_os'][os_name.s], dep_path, dep_name, new_rev)
361 if not commit_msg:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000362 print('Could not find an entry in %s to update.' % deps_file)
machenbach26a201f2016-08-30 00:43:13 -0700363 return 1
364
Raul Tambre80ee78e2019-05-06 22:41:05 +0000365 print('Pinning %s' % dep_name)
366 print('to revision %s' % new_rev)
367 print('in %s' % deps_file)
machenbach26a201f2016-08-30 00:43:13 -0700368 with open(deps_file, 'w') as fh:
369 for line in deps_lines:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000370 print(line, file=fh)
machenbach26a201f2016-08-30 00:43:13 -0700371 deps_file_dir = os.path.normpath(os.path.dirname(deps_file))
372 deps_file_root = Popen(
373 ['git', 'rev-parse', '--show-toplevel'],
374 cwd=deps_file_dir, stdout=PIPE).communicate()[0].strip()
375 with open(os.path.join(deps_file_root, '.git', 'MERGE_MSG'), 'w') as fh:
376 fh.write(commit_msg)
377 return 0
378
379
380def main(argv):
381 usage = 'Usage: roll-dep-svn [options] <dep path> <rev> [ <DEPS file> ]'
382 parser = optparse.OptionParser(usage=usage, description=__doc__)
383 parser.add_option('--no-verify-revision',
384 help='Don\'t verify the revision passed in. This '
385 'also skips adding an svn revision comment '
386 'for git dependencies and requires the passed '
387 'revision to be a git hash.',
388 default=False, action='store_true')
389 options, args = parser.parse_args(argv)
390 if len(args) not in (2, 3):
391 parser.error('Expected either 2 or 3 positional parameters.')
392 arg_dep_path, revision = args[:2]
393 gclient_root = find_gclient_root()
394 dep_path = platform_path(arg_dep_path)
395 if not os.path.exists(dep_path):
396 dep_path = os.path.join(gclient_root, dep_path)
397 if not options.no_verify_revision:
398 # Only require the path to exist if the revision should be verified. A path
399 # to e.g. os deps might not be checked out.
400 if not os.path.isdir(dep_path):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000401 print('No such directory: %s' % arg_dep_path, file=sys.stderr)
machenbach26a201f2016-08-30 00:43:13 -0700402 return 1
403 if len(args) > 2:
404 deps_file = args[2]
405 else:
406 soln = get_solution(gclient_root, dep_path)
407 soln_path = os.path.relpath(os.path.join(gclient_root, soln['name']))
408 deps_file = os.path.join(soln_path, 'DEPS')
409 dep_name = posix_path(os.path.relpath(dep_path, gclient_root))
410 if options.no_verify_revision:
411 if not is_git_hash(revision):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000412 print(
machenbach26a201f2016-08-30 00:43:13 -0700413 'The passed revision %s must be a git hash when skipping revision '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000414 'verification.' % revision, file=sys.stderr)
machenbach26a201f2016-08-30 00:43:13 -0700415 return 1
416 git_rev = revision
417 comment = None
418 else:
419 git_rev, svn_rev = get_git_revision(dep_path, revision)
420 comment = ('from svn revision %s' % svn_rev) if svn_rev else None
421 if not git_rev:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000422 print('Could not find git revision matching %s.' % revision,
423 file=sys.stderr)
machenbach26a201f2016-08-30 00:43:13 -0700424 return 1
425 return update_deps(deps_file, dep_path, dep_name, git_rev, comment)
426
427
428if __name__ == '__main__':
429 try:
430 sys.exit(main(sys.argv[1:]))
431 except KeyboardInterrupt:
432 sys.stderr.write('interrupted\n')
433 sys.exit(1)