blob: 46acdade4d99f7b5a9a4b5edc53154092624122e [file] [log] [blame]
Henrik Kjellander8d3ad822015-05-26 19:52:05 +02001#!/usr/bin/env python
2# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3#
4# Use of this source code is governed by a BSD-style license
5# that can be found in the LICENSE file in the root of the source
6# tree. An additional intellectual property rights grant can be found
7# in the file PATENTS. All contributing project authors may
8# be found in the AUTHORS file in the root of the source tree.
9
10"""Script to roll chromium_revision in the WebRTC DEPS file."""
11
12import argparse
13import base64
14import collections
15import logging
16import os
17import re
18import subprocess
19import sys
20import urllib
21
22
23CHROMIUM_LKGR_URL = 'https://chromium-status.appspot.com/lkgr'
24CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src'
25CHROMIUM_COMMIT_TEMPLATE = CHROMIUM_SRC_URL + '/+/%s'
26CHROMIUM_FILE_TEMPLATE = CHROMIUM_SRC_URL + '/+/%s/%s'
27
28COMMIT_POSITION_RE = re.compile('^Cr-Commit-Position: .*#([0-9]+).*$')
29CLANG_REVISION_RE = re.compile(r'^CLANG_REVISION=(\d+)$')
30ROLL_BRANCH_NAME = 'roll_chromium_revision'
31
32SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
33CHECKOUT_ROOT_DIR = os.path.realpath(os.path.join(SCRIPT_DIR, os.pardir,
34 os.pardir))
35sys.path.append(CHECKOUT_ROOT_DIR)
36import setup_links
37
38sys.path.append(os.path.join(CHECKOUT_ROOT_DIR, 'tools'))
39import find_depot_tools
40find_depot_tools.add_depot_tools_to_path()
41from gclient import GClientKeywords
42
43CLANG_UPDATE_SCRIPT_URL_PATH = 'tools/clang/scripts/update.sh'
44CLANG_UPDATE_SCRIPT_LOCAL_PATH = os.path.join('tools', 'clang', 'scripts',
45 'update.sh')
46
47DepsEntry = collections.namedtuple('DepsEntry', 'path url revision')
48ChangedDep = collections.namedtuple('ChangedDep', 'path current_rev new_rev')
49
50
51def ParseDepsDict(deps_content):
52 local_scope = {}
53 var = GClientKeywords.VarImpl({}, local_scope)
54 global_scope = {
55 'File': GClientKeywords.FileImpl,
56 'From': GClientKeywords.FromImpl,
57 'Var': var.Lookup,
58 'deps_os': {},
59 }
60 exec(deps_content, global_scope, local_scope)
61 return local_scope
62
63
64def ParseLocalDepsFile(filename):
65 with open(filename, 'rb') as f:
66 deps_content = f.read()
67 return ParseDepsDict(deps_content)
68
69
70def ParseRemoteCrDepsFile(revision):
71 deps_content = ReadRemoteCrFile('DEPS', revision)
72 return ParseDepsDict(deps_content)
73
74
75def ParseCommitPosition(commit_message):
76 for line in reversed(commit_message.splitlines()):
77 m = COMMIT_POSITION_RE.match(line.strip())
78 if m:
79 return m.group(1)
80 logging.error('Failed to parse commit position id from:\n%s\n',
81 commit_message)
82 sys.exit(-1)
83
84
85def _RunCommand(command, working_dir=None, ignore_exit_code=False,
86 extra_env=None):
87 """Runs a command and returns the output from that command.
88
89 If the command fails (exit code != 0), the function will exit the process.
90
91 Returns:
92 A tuple containing the stdout and stderr outputs as strings.
93 """
94 working_dir = working_dir or CHECKOUT_ROOT_DIR
95 logging.debug('CMD: %s CWD: %s', ' '.join(command), working_dir)
96 env = os.environ.copy()
97 if extra_env:
98 assert all(type(value) == str for value in extra_env.values())
99 logging.debug('extra env: %s', extra_env)
100 env.update(extra_env)
101 p = subprocess.Popen(command, stdout=subprocess.PIPE,
102 stderr=subprocess.PIPE, env=env,
103 cwd=working_dir, universal_newlines=True)
104 std_output = p.stdout.read()
105 err_output = p.stderr.read()
106 p.wait()
107 p.stdout.close()
108 p.stderr.close()
109 if not ignore_exit_code and p.returncode != 0:
110 logging.error('Command failed: %s\n'
111 'stdout:\n%s\n'
112 'stderr:\n%s\n', ' '.join(command), std_output, err_output)
113 sys.exit(p.returncode)
114 return std_output, err_output
115
116
117def _GetBranches():
118 """Returns a tuple of active,branches.
119
120 The 'active' is the name of the currently active branch and 'branches' is a
121 list of all branches.
122 """
123 lines = _RunCommand(['git', 'branch'])[0].split('\n')
124 branches = []
125 active = ''
126 for line in lines:
127 if '*' in line:
128 # The assumption is that the first char will always be the '*'.
129 active = line[1:].strip()
130 branches.append(active)
131 else:
132 branch = line.strip()
133 if branch:
134 branches.append(branch)
135 return active, branches
136
137
138def _ReadGitilesContent(url):
139 # Download and decode BASE64 content until
140 # https://code.google.com/p/gitiles/issues/detail?id=7 is fixed.
141 base64_content = ReadUrlContent(url + '?format=TEXT')
142 return base64.b64decode(base64_content[0])
143
144
145def ReadRemoteCrFile(path_below_src, revision):
146 """Reads a remote Chromium file of a specific revision. Returns a string."""
147 return _ReadGitilesContent(CHROMIUM_FILE_TEMPLATE % (revision,
148 path_below_src))
149
150
151def ReadRemoteCrCommit(revision):
152 """Reads a remote Chromium commit message. Returns a string."""
153 return _ReadGitilesContent(CHROMIUM_COMMIT_TEMPLATE % revision)
154
155
156def ReadUrlContent(url):
157 """Connect to a remote host and read the contents. Returns a list of lines."""
158 conn = urllib.urlopen(url)
159 try:
160 return conn.readlines()
161 except IOError as e:
162 logging.exception('Error connecting to %s. Error: %s', url, e)
163 raise
164 finally:
165 conn.close()
166
167
168def GetMatchingDepsEntries(depsentry_dict, dir_path):
169 """Gets all deps entries matching the provided path.
170
171 This list may contain more than one DepsEntry object.
172 Example: dir_path='src/testing' would give results containing both
173 'src/testing/gtest' and 'src/testing/gmock' deps entries for Chromium's DEPS.
174 Example 2: dir_path='src/build' should return 'src/build' but not
175 'src/buildtools'.
176
177 Returns:
178 A list of DepsEntry objects.
179 """
180 result = []
181 for path, depsentry in depsentry_dict.iteritems():
182 if path == dir_path:
183 result.append(depsentry)
184 else:
185 parts = path.split(os.sep)
186 if all(part == parts[i]
187 for i, part in enumerate(dir_path.split(os.sep))):
188 result.append(depsentry)
189 return result
190
191
192def BuildDepsentryDict(deps_dict):
193 """Builds a dict of DepsEntry object from a raw parsed deps dict."""
194 result = {}
195 def AddDepsEntries(deps_subdict):
196 for path, deps_url in deps_subdict.iteritems():
197 if not result.has_key(path):
198 url, revision = deps_url.split('@') if deps_url else (None, None)
199 result[path] = DepsEntry(path, url, revision)
200
201 AddDepsEntries(deps_dict['deps'])
202 for deps_os in ['win', 'mac', 'unix', 'android', 'ios', 'unix']:
203 AddDepsEntries(deps_dict['deps_os'].get(deps_os, {}))
204 return result
205
206
207def CalculateChangedDeps(current_deps, new_deps):
208 result = []
209 current_entries = BuildDepsentryDict(current_deps)
210 new_entries = BuildDepsentryDict(new_deps)
211
212 all_deps_dirs = setup_links.DIRECTORIES
213 for deps_dir in all_deps_dirs:
214 # All deps have 'src' prepended to the path in the Chromium DEPS file.
215 dir_path = 'src/%s' % deps_dir
216
217 for entry in GetMatchingDepsEntries(current_entries, dir_path):
218 new_matching_entries = GetMatchingDepsEntries(new_entries, entry.path)
219 assert len(new_matching_entries) <= 1, (
220 'Should never find more than one entry matching %s in %s, found %d' %
221 (entry.path, new_entries, len(new_matching_entries)))
222 if not new_matching_entries:
223 result.append(ChangedDep(entry.path, entry.revision, 'None'))
224 elif entry != new_matching_entries[0]:
225 result.append(ChangedDep(entry.path, entry.revision,
226 new_matching_entries[0].revision))
227 return result
228
229
230def CalculateChangedClang(new_cr_rev):
231 def GetClangRev(lines):
232 for line in lines:
233 match = CLANG_REVISION_RE.match(line)
234 if match:
235 return match.group(1)
236 return None
237
238 chromium_src_path = os.path.join(CHECKOUT_ROOT_DIR, 'chromium', 'src',
239 CLANG_UPDATE_SCRIPT_LOCAL_PATH)
240 with open(chromium_src_path, 'rb') as f:
241 current_lines = f.readlines()
242 current_rev = GetClangRev(current_lines)
243
244 new_clang_update_sh = ReadRemoteCrFile(CLANG_UPDATE_SCRIPT_URL_PATH,
245 new_cr_rev).splitlines()
246 new_rev = GetClangRev(new_clang_update_sh)
247 return ChangedDep(CLANG_UPDATE_SCRIPT_LOCAL_PATH, current_rev, new_rev)
248
249
250def GenerateCommitMessage(current_cr_rev, new_cr_rev, changed_deps_list,
251 clang_change):
252 current_cr_rev = current_cr_rev[0:7]
253 new_cr_rev = new_cr_rev[0:7]
254 rev_interval = '%s..%s' % (current_cr_rev, new_cr_rev)
255
256 current_git_number = ParseCommitPosition(ReadRemoteCrCommit(current_cr_rev))
257 new_git_number = ParseCommitPosition(ReadRemoteCrCommit(new_cr_rev))
258 git_number_interval = '%s:%s' % (current_git_number, new_git_number)
259
260 commit_msg = ['Roll chromium_revision %s (%s)' % (rev_interval,
261 git_number_interval)]
262
263 if changed_deps_list:
264 commit_msg.append('\nRelevant changes:')
265
266 for c in changed_deps_list:
267 commit_msg.append('* %s: %s..%s' % (c.path, c.current_rev[0:7],
268 c.new_rev[0:7]))
269
270 change_url = CHROMIUM_FILE_TEMPLATE % (rev_interval, 'DEPS')
271 commit_msg.append('Details: %s' % change_url)
272
273 if clang_change.current_rev != clang_change.new_rev:
274 commit_msg.append('\nClang version changed %s:%s' %
275 (clang_change.current_rev, clang_change.new_rev))
276 change_url = CHROMIUM_FILE_TEMPLATE % (rev_interval,
277 CLANG_UPDATE_SCRIPT_URL_PATH)
278 commit_msg.append('Details: %s' % change_url)
279 else:
280 commit_msg.append('\nClang version was not updated in this roll.')
281 return '\n'.join(commit_msg)
282
283
284def UpdateDeps(deps_filename, old_cr_revision, new_cr_revision):
285 """Update the DEPS file with the new revision."""
286 with open(deps_filename, 'rb') as deps_file:
287 deps_content = deps_file.read()
288 deps_content = deps_content.replace(old_cr_revision, new_cr_revision)
289 with open(deps_filename, 'wb') as deps_file:
290 deps_file.write(deps_content)
291
292
293def _CreateRollBranch(dry_run):
294 current_branch = _RunCommand(
295 ['git', 'rev-parse', '--abbrev-ref', 'HEAD'])[0].splitlines()[0]
296 if current_branch != 'master':
297 logging.error('Please checkout the master branch and re-run this script.')
298 if not dry_run:
299 sys.exit(-1)
300
301 logging.info('Creating roll branch: %s', ROLL_BRANCH_NAME)
302 if not dry_run:
303 _RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
304
305
306def _RemovePreviousRollBranch(dry_run):
307 active_branch, branches = _GetBranches()
308 if active_branch == ROLL_BRANCH_NAME:
309 active_branch = 'master'
310 if ROLL_BRANCH_NAME in branches:
311 logging.info('Removing previous roll branch (%s)', ROLL_BRANCH_NAME)
312 if not dry_run:
313 _RunCommand(['git', 'checkout', active_branch])
314 _RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
315
316
317def _LocalCommit(commit_msg, dry_run):
318 logging.info('Committing changes locally.')
319 if not dry_run:
320 _RunCommand(['git', 'add', '--update', '.'])
321 _RunCommand(['git', 'commit', '-m', commit_msg])
322
323
324def _UploadCL(dry_run):
325 logging.info('Uploading CL...')
326 if not dry_run:
327 _RunCommand(['git', 'cl', 'upload'], extra_env={'EDITOR': 'true'})
328
329
330def _LaunchTrybots(dry_run):
331 logging.info('Sending tryjobs...')
332 if not dry_run:
333 _RunCommand(['git', 'cl', 'try'])
334
335
336def main():
337 p = argparse.ArgumentParser()
338 p.add_argument('--clean', action='store_true', default=False,
339 help='Removes any previous local roll branch.')
340 p.add_argument('-r', '--revision',
341 help=('Chromium Git revision to roll to. Defaults to the '
342 'Chromium LKGR revision if omitted.'))
343 p.add_argument('--dry-run', action='store_true', default=False,
344 help=('Calculate changes and modify DEPS, but don\'t create '
345 'any local branch, commit, upload CL or send any '
346 'tryjobs.'))
347 p.add_argument('-v', '--verbose', action='store_true', default=False,
348 help='Be extra verbose in printing of log messages.')
349 opts = p.parse_args()
350
351 if opts.verbose:
352 logging.basicConfig(level=logging.DEBUG)
353 else:
354 logging.basicConfig(level=logging.INFO)
355
356 if opts.clean:
357 _RemovePreviousRollBranch(opts.dry_run)
358
359 if not opts.revision:
360 lkgr_contents = ReadUrlContent(CHROMIUM_LKGR_URL)
361 logging.info('No revision specified. Using LKGR: %s', lkgr_contents[0])
362 opts.revision = lkgr_contents[0]
363
364 deps_filename = os.path.join(CHECKOUT_ROOT_DIR, 'DEPS')
365 local_deps = ParseLocalDepsFile(deps_filename)
366 current_cr_rev = local_deps['vars']['chromium_revision']
367
368 current_cr_deps = ParseRemoteCrDepsFile(current_cr_rev)
369 new_cr_deps = ParseRemoteCrDepsFile(opts.revision)
370
371 changed_deps = sorted(CalculateChangedDeps(current_cr_deps, new_cr_deps))
372 clang_change = CalculateChangedClang(opts.revision)
373 if changed_deps or clang_change:
374 commit_msg = GenerateCommitMessage(current_cr_rev, opts.revision,
375 changed_deps, clang_change)
376 logging.debug('Commit message:\n%s', commit_msg)
377 else:
378 logging.info('No deps changes detected when rolling from %s to %s. '
379 'Aborting without action.', current_cr_rev, opts.revision)
380 return 0
381
382 _CreateRollBranch(opts.dry_run)
383 UpdateDeps(deps_filename, current_cr_rev, opts.revision)
384 _LocalCommit(commit_msg, opts.dry_run)
385 _UploadCL(opts.dry_run)
386 _LaunchTrybots(opts.dry_run)
387 return 0
388
389
390if __name__ == '__main__':
391 sys.exit(main())