OLD | NEW |
---|---|
(Empty) | |
1 #!/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 | |
7 parent repo's DEPS file with the corresponding git revision. Sample invocation: | |
8 | |
9 [chromium/src]$ roll-dep third_party/WebKit 12345 | |
10 | |
11 After the script completes, the DEPS file will be dirty with the new revision. | |
12 The user can then: | |
13 | |
14 $ git add DEPS | |
15 $ git commit | |
16 """ | |
17 | |
18 import ast | |
19 import os | |
20 import re | |
21 import sys | |
22 | |
23 from subprocess import Popen, PIPE | |
24 | |
25 def posix_path(path): | |
26 """Convert a possibly-Windows path to a posix-style path.""" | |
27 return re.sub('^[A-Z]:', '', path.replace(os.sep, '/')) | |
28 | |
29 def platform_path(path): | |
30 """Convert a possibly-posix path to a Windows-style path.""" | |
31 return path.replace('/', os.sep) | |
32 | |
33 def find_gclient_root(): | |
34 """Find the directory containing the .gclient file.""" | |
35 cwd = posix_path(os.getcwd()) | |
36 result = '' | |
37 for _ in xrange(len(cwd.split('/'))): | |
38 if os.path.exists(os.path.join(result, '.gclient')): | |
39 return result | |
40 result = os.path.join(result, os.pardir) | |
41 assert False, 'Could not find root of your gclient checkout.' | |
42 | |
43 def get_solution(gclient_root, dep_path): | |
44 """Find the solution in .gclient containing the dep being rolled.""" | |
45 cwd = os.getcwd().rstrip(os.sep) + os.sep | |
46 gclient_root = os.path.realpath(gclient_root) | |
47 gclient_path = os.path.join(gclient_root, '.gclient') | |
48 gclient_locals = {} | |
49 execfile(gclient_path, {}, gclient_locals) | |
50 for soln in gclient_locals['solutions']: | |
51 soln_relpath = platform_path(soln['name'].rstrip('/')) + os.sep | |
52 if (dep_path.startswith(soln_relpath) or | |
53 cwd.startswith(os.path.join(gclient_root, soln_relpath))): | |
54 return soln | |
55 assert False, 'Could not determine the parent project for %s' % dep_path | |
56 | |
57 def verify_git_revision(dep_path, revision): | |
58 """Verify that a git revision exists in a repository.""" | |
59 p = Popen(['git', 'rev-list', '-n', '1', revision], | |
60 cwd=dep_path, stdout=PIPE, stderr=PIPE) | |
61 result = p.communicate()[0].strip() | |
62 if p.returncode != 0 or not re.match('^[a-fA-F0-9]{40}$', result): | |
63 result = None | |
64 return result | |
65 | |
66 def convert_svn_revision(dep_path, revision): | |
67 """Find the git revision corresponding to an svn revision.""" | |
68 revision = int(revision) | |
69 with open(os.devnull, 'w') as devnull: | |
70 try: | |
71 log_p = Popen(['git', 'log', 'origin/master'], | |
Michael Moss
2014/06/09 16:01:34
What about branch revisions? Are we not worried ab
szager1
2014/06/09 19:05:32
I actually had an earlier version of this that sca
Michael Moss
2014/06/09 21:13:16
What about defaulting to 'HEAD' and then falling b
| |
72 cwd=dep_path, stdout=PIPE, stderr=devnull) | |
73 grep_p = Popen(['grep', '-e', '^commit ', '-e', '^ *git-svn-id: '], | |
74 stdin=log_p.stdout, stdout=PIPE, stderr=devnull) | |
75 git_rev = None | |
76 prev_svn_rev = None | |
77 for line in grep_p.stdout: | |
78 if line.startswith('commit '): | |
79 git_rev = line.split()[1] | |
80 continue | |
81 try: | |
82 svn_rev = int(line.split()[1].partition('@')[2]) | |
83 except (IndexError, ValueError): | |
84 print >> sys.stderr, ( | |
85 'WARNING: Could not parse svn revision out of "%s"' % line) | |
86 continue | |
87 if svn_rev == revision: | |
88 return git_rev | |
89 if svn_rev > revision: | |
90 prev_svn_rev = svn_rev | |
91 continue | |
92 if prev_svn_rev: | |
93 msg = 'git history skips from revision %d to revision %d.' % ( | |
94 svn_rev, prev_svn_rev) | |
95 else: | |
96 msg = ('latest available revision is %d; you may need to ' | |
97 '"git fetch origin" to get the latest commits.' % svn_rev) | |
Michael Moss
2014/06/09 16:01:34
Any reason not to make this automatic?
szager1
2014/06/09 19:05:32
Not a strong reason. I think it's kind of weird t
| |
98 raise RuntimeError('No match for revision %d; %s' % (revision, msg)) | |
99 finally: | |
100 log_p.terminate() | |
101 grep_p.terminate() | |
102 | |
103 def get_git_revision(dep_path, revision): | |
104 """Convert the revision argument passed to the script to a git revision.""" | |
105 if revision.startswith('r'): | |
106 result = convert_svn_revision(dep_path, revision[1:]) | |
107 elif re.search('[a-fA-F]', revision): | |
108 result = verify_git_revision(dep_path, revision) | |
109 elif len(revision) > 6: | |
110 result = verify_git_revision(dep_path, revision) | |
111 if not result: | |
112 result = convert_svn_revision(dep_path, revision) | |
113 else: | |
114 try: | |
115 result = convert_svn_revision(dep_path, revision) | |
116 except RuntimeError: | |
117 result = verify_git_revision(dep_path, revision) | |
118 if not result: | |
119 raise | |
120 return result | |
121 | |
122 def ast_err_msg(node): | |
123 return 'ERROR: Undexpected DEPS file AST structure at line %d column %d' % ( | |
124 node.lineno, node.col_offset) | |
125 | |
126 def find_deps_section(deps_ast, section): | |
127 """Find a top-level section of the DEPS file.""" | |
128 try: | |
129 result = [n.value for n in deps_ast.body if | |
130 n.__class__ is ast.Assign and | |
131 n.targets[0].__class__ is ast.Name and | |
132 n.targets[0].id == section][0] | |
133 return result | |
134 except IndexError: | |
135 return None | |
136 | |
137 def find_dict_index(dict_node, key): | |
138 """Given a key, find the index of the corresponding dict entry.""" | |
139 assert dict_node.__class__ is ast.Dict, ast_err_msg(dict_node) | |
140 indices = [i for i, n in enumerate(dict_node.keys) if | |
141 n.__class__ is ast.Str and n.s == key] | |
142 assert len(indices) < 2, ( | |
143 'Found redundant dict entries for key "%s"' % key) | |
144 return indices[0] if indices else None | |
145 | |
146 def update_node(deps_lines, deps_ast, node, git_revision): | |
147 """Update an AST node with the new git revision.""" | |
148 if node.__class__ is ast.Str: | |
149 update_string(deps_lines, node, git_revision) | |
150 elif node.__class__ is ast.BinOp: | |
151 update_binop(deps_lines, deps_ast, node, git_revision) | |
152 elif node.__class__ is ast.Call: | |
153 update_call(deps_lines, deps_ast, node, git_revision) | |
154 else: | |
155 assert False, ast_err_msg(node) | |
156 | |
157 def update_string(deps_lines, string_node, git_revision): | |
158 """Update a string node in the AST with the new git revision.""" | |
159 line_idx = string_node.lineno - 1 | |
160 start_idx = string_node.col_offset - 1 | |
161 line = deps_lines[line_idx] | |
162 (prefix, sep, rev) = string_node.s.partition('@') | |
163 if sep: | |
164 start_idx = line.find(prefix + sep, start_idx) + len(prefix + sep) | |
165 tail_idx = start_idx + len(rev) | |
166 else: | |
167 start_idx = line.find(prefix, start_idx) | |
168 tail_idx = start_idx + len(prefix) | |
169 deps_lines[line_idx] = line[:start_idx] + git_revision + line[tail_idx:] | |
170 | |
171 def update_binop(deps_lines, deps_ast, binop_node, git_revision): | |
172 """Update a binary operation node in the AST with the new git revision.""" | |
173 # Since the revision part is always last, assume that it's the right-hand | |
174 # operand that needs to be updated. | |
175 update_node(deps_lines, deps_ast, binop_node.right, git_revision) | |
176 | |
177 def update_call(deps_lines, deps_ast, call_node, git_revision): | |
178 """Update a function call node in the AST with the new git revision.""" | |
179 # The only call we know how to handle is Var() | |
180 assert call_node.func.id == 'Var', ast_err_msg(call_node) | |
181 assert call_node.args[0].__class__ is ast.Str, ast_err_msg(call_node) | |
182 update_var(deps_lines, deps_ast, call_node.args[0].s, git_revision) | |
183 | |
184 def update_var(deps_lines, deps_ast, var_name, git_revision): | |
185 """Update an entry in the vars section of the DEPS file with the new | |
186 git revision.""" | |
187 vars_node = find_deps_section(deps_ast, 'vars') | |
188 assert vars_node, 'Could not find "vars" section of DEPS file.' | |
189 var_idx = find_dict_index(vars_node, var_name) | |
190 assert var_idx is not None, ( | |
191 'Could not find definition of "%s" var in DEPS file.' % var_name) | |
192 val_node = vars_node.values[var_idx] | |
193 update_node(deps_lines, deps_ast, val_node, git_revision) | |
194 | |
195 def update_deps(soln, soln_path, dep_name, git_revision): | |
196 """Update the DEPS file with the new git revision.""" | |
197 deps_file = os.path.join(soln_path, soln.get('deps_file', 'DEPS')) | |
198 with open(deps_file) as fh: | |
199 deps_content = fh.read() | |
200 deps_lines = deps_content.splitlines() | |
201 deps_ast = ast.parse(deps_content, deps_file) | |
202 deps_node = find_deps_section(deps_ast, 'deps') | |
203 assert deps_node, 'Could not find "deps" section of DEPS file' | |
204 dep_idx = find_dict_index(deps_node, dep_name) | |
205 result = False | |
206 if dep_idx is not None: | |
207 value_node = deps_node.values[dep_idx] | |
208 update_node(deps_lines, deps_ast, value_node, git_revision) | |
209 result = True | |
210 deps_os_node = find_deps_section(deps_ast, 'deps_os') | |
211 if deps_os_node: | |
212 for os_node in deps_os_node.values: | |
Michael Moss
2014/06/09 16:01:34
Not sure it makes sense to always update os deps,
szager1
2014/06/09 19:05:32
I don't think gclient can even handle a deps_os en
| |
213 dep_idx = find_dict_index(os_node, dep_name) | |
214 if dep_idx is not None: | |
215 value_node = os_node.values[dep_idx] | |
216 if value_node.__class__ is ast.Name and value_node.id == 'None': | |
217 pass | |
218 else: | |
219 update_node(deps_lines, deps_ast, value_node, git_revision) | |
220 result = True | |
221 if result: | |
222 print 'Pinning %s' % dep_name | |
223 print 'to revision %s' % git_revision | |
224 print 'in %s' % deps_file | |
225 with open(deps_file, 'w') as fh: | |
226 for line in deps_lines: | |
227 print >> fh, line | |
228 return result | |
229 | |
230 | |
231 def main(argv): | |
232 if len(argv) !=2 : | |
Michael Moss
2014/06/09 16:01:34
Nit: space after !=
szager1
2014/06/09 19:05:32
Done.
| |
233 print >> sys.stderr, 'Usage: roll_dep.py <dep path> <svn revision>' | |
234 return 1 | |
235 (dep_path, revision) = argv[0:2] | |
236 dep_path = platform_path(dep_path) | |
237 assert os.path.isdir(dep_path), 'No such directory: %s' % dep_path | |
238 gclient_root = find_gclient_root() | |
239 soln = get_solution(gclient_root, dep_path) | |
240 soln_path = os.path.relpath(os.path.join(gclient_root, soln['name'])) | |
241 dep_name = posix_path(os.path.relpath(dep_path, gclient_root)) | |
242 git_revision = get_git_revision(dep_path, revision) | |
243 assert git_revision, 'Could not find git revision matching %s' % revision | |
244 update_deps(soln, soln_path, dep_name, git_revision) | |
245 | |
246 if __name__ == '__main__': | |
247 sys.exit(main(sys.argv[1:])) | |
OLD | NEW |