blob: e906809624e9bf6591711522f10ff034b168b992 [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:
Henrik Kjellander14771ac2015-06-02 13:10:04 +0200185 parts = path.split('/')
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200186 if all(part == parts[i]
Henrik Kjellander14771ac2015-06-02 13:10:04 +0200187 for i, part in enumerate(dir_path.split('/'))):
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200188 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
Henrik Kjellander1b76ca12015-06-09 12:58:44 +0200292def _IsTreeClean():
293 stdout, _ = _RunCommand(['git', 'status', '--porcelain'])
294 if len(stdout) == 0:
295 return True
296
297 logging.error('Dirty/unversioned files:\n%s', stdout)
298 return False
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200299
300def _CreateRollBranch(dry_run):
301 current_branch = _RunCommand(
302 ['git', 'rev-parse', '--abbrev-ref', 'HEAD'])[0].splitlines()[0]
303 if current_branch != 'master':
304 logging.error('Please checkout the master branch and re-run this script.')
305 if not dry_run:
306 sys.exit(-1)
307
Henrik Kjellander1b76ca12015-06-09 12:58:44 +0200308 logging.info('Updating master branch...')
309 if not dry_run:
310 _RunCommand(['git', 'pull'])
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200311 logging.info('Creating roll branch: %s', ROLL_BRANCH_NAME)
312 if not dry_run:
313 _RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
314
315
316def _RemovePreviousRollBranch(dry_run):
317 active_branch, branches = _GetBranches()
318 if active_branch == ROLL_BRANCH_NAME:
319 active_branch = 'master'
320 if ROLL_BRANCH_NAME in branches:
321 logging.info('Removing previous roll branch (%s)', ROLL_BRANCH_NAME)
322 if not dry_run:
323 _RunCommand(['git', 'checkout', active_branch])
324 _RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
325
326
327def _LocalCommit(commit_msg, dry_run):
328 logging.info('Committing changes locally.')
329 if not dry_run:
330 _RunCommand(['git', 'add', '--update', '.'])
331 _RunCommand(['git', 'commit', '-m', commit_msg])
332
333
334def _UploadCL(dry_run):
335 logging.info('Uploading CL...')
336 if not dry_run:
337 _RunCommand(['git', 'cl', 'upload'], extra_env={'EDITOR': 'true'})
338
339
Henrik Kjellanderec0feb62015-09-15 16:00:32 +0200340def _LaunchTrybots(dry_run, skip_try):
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200341 logging.info('Sending tryjobs...')
Henrik Kjellanderec0feb62015-09-15 16:00:32 +0200342 if not dry_run and not skip_try:
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200343 _RunCommand(['git', 'cl', 'try'])
344
345
346def main():
347 p = argparse.ArgumentParser()
348 p.add_argument('--clean', action='store_true', default=False,
349 help='Removes any previous local roll branch.')
350 p.add_argument('-r', '--revision',
351 help=('Chromium Git revision to roll to. Defaults to the '
352 'Chromium LKGR revision if omitted.'))
353 p.add_argument('--dry-run', action='store_true', default=False,
354 help=('Calculate changes and modify DEPS, but don\'t create '
355 'any local branch, commit, upload CL or send any '
356 'tryjobs.'))
Henrik Kjellanderec0feb62015-09-15 16:00:32 +0200357 p.add_argument('-s', '--skip-try', action='store_true', default=False,
358 help='Do everything except sending tryjobs.')
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200359 p.add_argument('-v', '--verbose', action='store_true', default=False,
360 help='Be extra verbose in printing of log messages.')
361 opts = p.parse_args()
362
363 if opts.verbose:
364 logging.basicConfig(level=logging.DEBUG)
365 else:
366 logging.basicConfig(level=logging.INFO)
367
Henrik Kjellander1b76ca12015-06-09 12:58:44 +0200368 if not _IsTreeClean():
369 logging.error('Please clean your local checkout first.')
370 return 1
371
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200372 if opts.clean:
373 _RemovePreviousRollBranch(opts.dry_run)
374
375 if not opts.revision:
376 lkgr_contents = ReadUrlContent(CHROMIUM_LKGR_URL)
377 logging.info('No revision specified. Using LKGR: %s', lkgr_contents[0])
378 opts.revision = lkgr_contents[0]
379
380 deps_filename = os.path.join(CHECKOUT_ROOT_DIR, 'DEPS')
381 local_deps = ParseLocalDepsFile(deps_filename)
382 current_cr_rev = local_deps['vars']['chromium_revision']
383
384 current_cr_deps = ParseRemoteCrDepsFile(current_cr_rev)
385 new_cr_deps = ParseRemoteCrDepsFile(opts.revision)
386
387 changed_deps = sorted(CalculateChangedDeps(current_cr_deps, new_cr_deps))
388 clang_change = CalculateChangedClang(opts.revision)
389 if changed_deps or clang_change:
390 commit_msg = GenerateCommitMessage(current_cr_rev, opts.revision,
391 changed_deps, clang_change)
392 logging.debug('Commit message:\n%s', commit_msg)
393 else:
394 logging.info('No deps changes detected when rolling from %s to %s. '
395 'Aborting without action.', current_cr_rev, opts.revision)
396 return 0
397
398 _CreateRollBranch(opts.dry_run)
399 UpdateDeps(deps_filename, current_cr_rev, opts.revision)
400 _LocalCommit(commit_msg, opts.dry_run)
401 _UploadCL(opts.dry_run)
Henrik Kjellanderec0feb62015-09-15 16:00:32 +0200402 _LaunchTrybots(opts.dry_run, opts.skip_try)
Henrik Kjellander8d3ad822015-05-26 19:52:05 +0200403 return 0
404
405
406if __name__ == '__main__':
407 sys.exit(main())