blob: 326f2c4d3600c59f8d9c37582ce0f537aec9e542 [file] [log] [blame]
kbre85ee562016-02-09 04:37:351#!/usr/bin/env python
2# Copyright 2015 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
6import argparse
7import collections
8import logging
9import os
10import re
11import subprocess
12import sys
13import time
14
15extra_trybots = [
16 {
cwallez658540752016-07-14 19:38:0117 "mastername": "master.tryserver.chromium.win",
kbre85ee562016-02-09 04:37:3518 "buildernames": ["win_optional_gpu_tests_rel"]
zmofb33cbfb2016-02-23 00:41:3519 },
20 {
cwallez658540752016-07-14 19:38:0121 "mastername": "master.tryserver.chromium.mac",
zmofb33cbfb2016-02-23 00:41:3522 "buildernames": ["mac_optional_gpu_tests_rel"]
zmo3eaa0912016-04-16 00:03:0523 },
24 {
cwallez658540752016-07-14 19:38:0125 "mastername": "master.tryserver.chromium.linux",
zmo3eaa0912016-04-16 00:03:0526 "buildernames": ["linux_optional_gpu_tests_rel"]
27 },
ynovikovcc292fc2016-09-01 21:58:4628 {
29 "mastername": "master.tryserver.chromium.android",
30 "buildernames": ["android_optional_gpu_tests_rel"]
31 },
kbre85ee562016-02-09 04:37:3532]
33
34SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
35SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir))
36sys.path.insert(0, os.path.join(SRC_DIR, 'build'))
37import find_depot_tools
38find_depot_tools.add_depot_tools_to_path()
39import roll_dep_svn
kbre85ee562016-02-09 04:37:3540from third_party import upload
41
42# Avoid depot_tools/third_party/upload.py print verbose messages.
43upload.verbosity = 0 # Errors only.
44
45CHROMIUM_GIT_URL = 'https://chromium.googlesource.com/chromium/src.git'
46CL_ISSUE_RE = re.compile('^Issue number: ([0-9]+) \((.*)\)$')
47RIETVELD_URL_RE = re.compile('^https?://(.*)/(.*)')
48ROLL_BRANCH_NAME = 'special_webgl_roll_branch'
49TRYJOB_STATUS_SLEEP_SECONDS = 30
50
51# Use a shell for subcommands on Windows to get a PATH search.
52IS_WIN = sys.platform.startswith('win')
53WEBGL_PATH = os.path.join('third_party', 'webgl', 'src')
kbr0ea13b4c2017-02-16 20:01:5054WEBGL_REVISION_TEXT_FILE = os.path.join(
55 'content', 'test', 'gpu', 'gpu_tests', 'webgl_conformance_revision.txt')
kbre85ee562016-02-09 04:37:3556
57CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
58 'git_repo_url'])
59CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'rietveld_server'])
60
Kenneth Russell3c5f9252017-08-18 21:49:5461
62def _VarLookup(local_scope):
63 return lambda var_name: local_scope['vars'][var_name]
64
65
kbre85ee562016-02-09 04:37:3566def _PosixPath(path):
67 """Convert a possibly-Windows path to a posix-style path."""
68 (_, path) = os.path.splitdrive(path)
69 return path.replace(os.sep, '/')
70
71def _ParseGitCommitHash(description):
72 for line in description.splitlines():
73 if line.startswith('commit '):
74 return line.split()[1]
75 logging.error('Failed to parse git commit id from:\n%s\n', description)
76 sys.exit(-1)
77 return None
78
79
80def _ParseDepsFile(filename):
81 with open(filename, 'rb') as f:
82 deps_content = f.read()
83 return _ParseDepsDict(deps_content)
84
85
86def _ParseDepsDict(deps_content):
87 local_scope = {}
kbre85ee562016-02-09 04:37:3588 global_scope = {
Kenneth Russell3c5f9252017-08-18 21:49:5489 'Var': _VarLookup(local_scope),
kbre85ee562016-02-09 04:37:3590 'deps_os': {},
91 }
92 exec(deps_content, global_scope, local_scope)
93 return local_scope
94
95
96def _GenerateCLDescriptionCommand(webgl_current, webgl_new, bugs):
97 def GetChangeString(current_hash, new_hash):
98 return '%s..%s' % (current_hash[0:7], new_hash[0:7]);
99
100 def GetChangeLogURL(git_repo_url, change_string):
101 return '%s/+log/%s' % (git_repo_url, change_string)
102
103 def GetBugString(bugs):
104 bug_str = 'BUG='
105 for bug in bugs:
106 bug_str += str(bug) + ','
107 return bug_str.rstrip(',')
108
kbr0ea13b4c2017-02-16 20:01:50109 change_str = GetChangeString(webgl_current.git_commit,
110 webgl_new.git_commit)
111 changelog_url = GetChangeLogURL(webgl_current.git_repo_url,
112 change_str)
113 if webgl_current.git_commit == webgl_new.git_commit:
114 print 'WARNING: WebGL repository is unchanged; proceeding with no-op roll'
kbre85ee562016-02-09 04:37:35115
116 def GetExtraTrybotString():
117 s = ''
118 for t in extra_trybots:
119 if s:
120 s += ';'
121 s += t['mastername'] + ':' + ','.join(t['buildernames'])
122 return s
123
124 extra_trybot_args = []
125 if extra_trybots:
126 extra_trybot_string = GetExtraTrybotString()
127 extra_trybot_args = ['-m', 'CQ_INCLUDE_TRYBOTS=' + extra_trybot_string]
128
129 return [
130 '-m', 'Roll WebGL ' + change_str,
131 '-m', '%s' % changelog_url,
132 '-m', GetBugString(bugs),
133 '-m', 'TEST=bots',
134 ] + extra_trybot_args
135
136
137class AutoRoller(object):
138 def __init__(self, chromium_src):
139 self._chromium_src = chromium_src
140
141 def _RunCommand(self, command, working_dir=None, ignore_exit_code=False,
142 extra_env=None):
143 """Runs a command and returns the stdout from that command.
144
145 If the command fails (exit code != 0), the function will exit the process.
146 """
147 working_dir = working_dir or self._chromium_src
148 logging.debug('cmd: %s cwd: %s', ' '.join(command), working_dir)
149 env = os.environ.copy()
150 if extra_env:
151 logging.debug('extra env: %s', extra_env)
152 env.update(extra_env)
153 p = subprocess.Popen(command, stdout=subprocess.PIPE,
154 stderr=subprocess.PIPE, shell=IS_WIN, env=env,
155 cwd=working_dir, universal_newlines=True)
156 output = p.stdout.read()
157 p.wait()
158 p.stdout.close()
159 p.stderr.close()
160
161 if not ignore_exit_code and p.returncode != 0:
162 logging.error('Command failed: %s\n%s', str(command), output)
163 sys.exit(p.returncode)
164 return output
165
166 def _GetCommitInfo(self, path_below_src, git_hash=None, git_repo_url=None):
167 working_dir = os.path.join(self._chromium_src, path_below_src)
168 self._RunCommand(['git', 'fetch', 'origin'], working_dir=working_dir)
169 revision_range = git_hash or 'origin'
170 ret = self._RunCommand(
agable2e9de0e82016-10-20 01:03:18171 ['git', '--no-pager', 'log', revision_range,
172 '--no-abbrev-commit', '--pretty=full', '-1'],
kbre85ee562016-02-09 04:37:35173 working_dir=working_dir)
174 return CommitInfo(_ParseGitCommitHash(ret), git_repo_url)
175
176 def _GetDepsCommitInfo(self, deps_dict, path_below_src):
177 entry = deps_dict['deps'][_PosixPath('src/%s' % path_below_src)]
178 at_index = entry.find('@')
179 git_repo_url = entry[:at_index]
180 git_hash = entry[at_index + 1:]
181 return self._GetCommitInfo(path_below_src, git_hash, git_repo_url)
182
183 def _GetCLInfo(self):
184 cl_output = self._RunCommand(['git', 'cl', 'issue'])
185 m = CL_ISSUE_RE.match(cl_output.strip())
186 if not m:
187 logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
188 sys.exit(-1)
189 issue_number = int(m.group(1))
190 url = m.group(2)
191
192 # Parse the Rietveld host from the URL.
193 m = RIETVELD_URL_RE.match(url)
194 if not m:
195 logging.error('Cannot parse Rietveld host from URL: %s', url)
196 sys.exit(-1)
197 rietveld_server = m.group(1)
198 return CLInfo(issue_number, url, rietveld_server)
199
200 def _GetCurrentBranchName(self):
201 return self._RunCommand(
202 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
203
204 def _IsTreeClean(self):
205 lines = self._RunCommand(
206 ['git', 'status', '--porcelain', '-uno']).splitlines()
207 if len(lines) == 0:
208 return True
209
210 logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
211 return False
212
213 def _GetBugList(self, path_below_src, webgl_current, webgl_new):
214 # TODO(kbr): this isn't useful, at least not yet, when run against
215 # the WebGL Github repository.
216 working_dir = os.path.join(self._chromium_src, path_below_src)
217 lines = self._RunCommand(
218 ['git','log',
219 '%s..%s' % (webgl_current.git_commit, webgl_new.git_commit)],
220 working_dir=working_dir).split('\n')
221 bugs = set()
222 for line in lines:
223 line = line.strip()
224 bug_prefix = 'BUG='
225 if line.startswith(bug_prefix):
226 bugs_strings = line[len(bug_prefix):].split(',')
227 for bug_string in bugs_strings:
228 try:
229 bugs.add(int(bug_string))
230 except:
231 # skip this, it may be a project specific bug such as
232 # "angleproject:X" or an ill-formed BUG= message
233 pass
234 return bugs
235
236 def _UpdateReadmeFile(self, readme_path, new_revision):
237 readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
238 txt = readme.read()
239 m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
240 ('Revision: %s' % new_revision), txt)
241 readme.seek(0)
242 readme.write(m)
243 readme.truncate()
244
zmo3eaa0912016-04-16 00:03:05245 def PrepareRoll(self, ignore_checks, run_tryjobs):
kbre85ee562016-02-09 04:37:35246 # TODO(kjellander): use os.path.normcase, os.path.join etc for all paths for
247 # cross platform compatibility.
248
249 if not ignore_checks:
250 if self._GetCurrentBranchName() != 'master':
251 logging.error('Please checkout the master branch.')
252 return -1
253 if not self._IsTreeClean():
254 logging.error('Please make sure you don\'t have any modified files.')
255 return -1
256
257 # Always clean up any previous roll.
258 self.Abort()
259
260 logging.debug('Pulling latest changes')
261 if not ignore_checks:
262 self._RunCommand(['git', 'pull'])
263
264 self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
265
266 # Modify Chromium's DEPS file.
267
268 # Parse current hashes.
269 deps_filename = os.path.join(self._chromium_src, 'DEPS')
270 deps = _ParseDepsFile(deps_filename)
271 webgl_current = self._GetDepsCommitInfo(deps, WEBGL_PATH)
272
273 # Find ToT revisions.
274 webgl_latest = self._GetCommitInfo(WEBGL_PATH)
275
276 if IS_WIN:
277 # Make sure the roll script doesn't use windows line endings
278 self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
279
280 self._UpdateDep(deps_filename, WEBGL_PATH, webgl_latest)
kbr0ea13b4c2017-02-16 20:01:50281 self._UpdateWebGLRevTextFile(WEBGL_REVISION_TEXT_FILE, webgl_latest)
kbre85ee562016-02-09 04:37:35282
283 if self._IsTreeClean():
284 logging.debug('Tree is clean - no changes detected.')
285 self._DeleteRollBranch()
286 else:
287 bugs = self._GetBugList(WEBGL_PATH, webgl_current, webgl_latest)
288 description = _GenerateCLDescriptionCommand(
289 webgl_current, webgl_latest, bugs)
290 logging.debug('Committing changes locally.')
291 self._RunCommand(['git', 'add', '--update', '.'])
292 self._RunCommand(['git', 'commit'] + description)
293 logging.debug('Uploading changes...')
294 self._RunCommand(['git', 'cl', 'upload'],
295 extra_env={'EDITOR': 'true'})
296
zmo3eaa0912016-04-16 00:03:05297 if run_tryjobs:
kbrb2921312016-04-06 20:52:10298 # Kick off tryjobs.
299 base_try_cmd = ['git', 'cl', 'try']
300 self._RunCommand(base_try_cmd)
301 if extra_trybots:
302 # Run additional tryjobs.
303 # TODO(kbr): this should not be necessary -- the
304 # CQ_INCLUDE_TRYBOTS directive above should handle it.
305 # http://crbug.com/585237
306 for trybot in extra_trybots:
307 for builder in trybot['buildernames']:
308 self._RunCommand(base_try_cmd + [
309 '-m', trybot['mastername'],
310 '-b', builder])
kbre85ee562016-02-09 04:37:35311
312 cl_info = self._GetCLInfo()
313 print 'Issue: %d URL: %s' % (cl_info.issue, cl_info.url)
314
315 # Checkout master again.
316 self._RunCommand(['git', 'checkout', 'master'])
317 print 'Roll branch left as ' + ROLL_BRANCH_NAME
318 return 0
319
320 def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info):
321 dep_name = _PosixPath(os.path.join('src', dep_relative_to_src))
322
323 # roll_dep_svn.py relies on cwd being the Chromium checkout, so let's
324 # temporarily change the working directory and then change back.
325 cwd = os.getcwd()
326 os.chdir(os.path.dirname(deps_filename))
327 roll_dep_svn.update_deps(deps_filename, dep_relative_to_src, dep_name,
328 commit_info.git_commit, '')
329 os.chdir(cwd)
330
kbr0ea13b4c2017-02-16 20:01:50331 def _UpdateWebGLRevTextFile(self, txt_filename, commit_info):
332 # Rolling the WebGL conformance tests must cause at least all of
333 # the WebGL tests to run. There are already exclusions in
334 # trybot_analyze_config.json which force all tests to run if
335 # changes under src/content/test/gpu are made. (This rule
336 # typically only takes effect on the GPU bots.) To make sure this
337 # happens all the time, update an autogenerated text file in this
338 # directory.
339 with open(txt_filename, 'w') as fh:
340 print >> fh, '# AUTOGENERATED FILE - DO NOT EDIT'
341 print >> fh, '# SEE roll_webgl_conformance.py'
342 print >> fh, 'Current webgl revision %s' % commit_info.git_commit
343
kbre85ee562016-02-09 04:37:35344 def _DeleteRollBranch(self):
345 self._RunCommand(['git', 'checkout', 'master'])
346 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
347 logging.debug('Deleted the local roll branch (%s)', ROLL_BRANCH_NAME)
348
349
350 def _GetBranches(self):
351 """Returns a tuple of active,branches.
352
353 The 'active' is the name of the currently active branch and 'branches' is a
354 list of all branches.
355 """
356 lines = self._RunCommand(['git', 'branch']).split('\n')
357 branches = []
358 active = ''
359 for l in lines:
360 if '*' in l:
361 # The assumption is that the first char will always be the '*'.
362 active = l[1:].strip()
363 branches.append(active)
364 else:
365 b = l.strip()
366 if b:
367 branches.append(b)
368 return (active, branches)
369
370 def Abort(self):
371 active_branch, branches = self._GetBranches()
372 if active_branch == ROLL_BRANCH_NAME:
373 active_branch = 'master'
374 if ROLL_BRANCH_NAME in branches:
375 print 'Aborting pending roll.'
376 self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME])
377 # Ignore an error here in case an issue wasn't created for some reason.
378 self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True)
379 self._RunCommand(['git', 'checkout', active_branch])
380 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
381 return 0
382
383
384def main():
385 parser = argparse.ArgumentParser(
386 description='Auto-generates a CL containing a WebGL conformance roll.')
387 parser.add_argument('--abort',
388 help=('Aborts a previously prepared roll. '
389 'Closes any associated issues and deletes the roll branches'),
390 action='store_true')
391 parser.add_argument('--ignore-checks', action='store_true', default=False,
392 help=('Skips checks for being on the master branch, dirty workspaces and '
393 'the updating of the checkout. Will still delete and create local '
394 'Git branches.'))
zmo3eaa0912016-04-16 00:03:05395 parser.add_argument('--run-tryjobs', action='store_true', default=False,
396 help=('Start the dry-run tryjobs for the newly generated CL. Use this '
397 'when you have no need to make changes to the WebGL conformance '
398 'test expectations in the same CL and want to avoid.'))
kbre85ee562016-02-09 04:37:35399 parser.add_argument('-v', '--verbose', action='store_true', default=False,
400 help='Be extra verbose in printing of log messages.')
401 args = parser.parse_args()
402
403 if args.verbose:
404 logging.basicConfig(level=logging.DEBUG)
405 else:
406 logging.basicConfig(level=logging.ERROR)
407
408 autoroller = AutoRoller(SRC_DIR)
409 if args.abort:
410 return autoroller.Abort()
411 else:
zmo3eaa0912016-04-16 00:03:05412 return autoroller.PrepareRoll(args.ignore_checks, args.run_tryjobs)
kbre85ee562016-02-09 04:37:35413
414if __name__ == '__main__':
415 sys.exit(main())