blob: 3344619bc5e964e8112971dc38eeace561caff2c [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
Raul Tambre66e754d2019-09-25 12:03:446from __future__ import print_function
7
kbre85ee562016-02-09 04:37:358import argparse
9import collections
10import logging
11import os
12import re
13import subprocess
14import sys
15import time
16
17extra_trybots = [
18 {
Corentin Wallezb78c44a2018-04-12 14:29:4719 "mastername": "luci.chromium.try",
kbre85ee562016-02-09 04:37:3520 "buildernames": ["win_optional_gpu_tests_rel"]
zmofb33cbfb2016-02-23 00:41:3521 },
22 {
Corentin Wallez5ba008952018-03-20 19:16:0623 "mastername": "luci.chromium.try",
zmofb33cbfb2016-02-23 00:41:3524 "buildernames": ["mac_optional_gpu_tests_rel"]
zmo3eaa0912016-04-16 00:03:0525 },
26 {
Corentin Wallez5ba008952018-03-20 19:16:0627 "mastername": "luci.chromium.try",
zmo3eaa0912016-04-16 00:03:0528 "buildernames": ["linux_optional_gpu_tests_rel"]
29 },
ynovikovcc292fc2016-09-01 21:58:4630 {
Yuly Novikov129c3282018-03-21 05:07:2931 "mastername": "luci.chromium.try",
ynovikovcc292fc2016-09-01 21:58:4632 "buildernames": ["android_optional_gpu_tests_rel"]
33 },
Kenneth Russell220f23b02017-12-05 09:02:2834 # Include the ANGLE tryservers which run the WebGL conformance tests
35 # in some non-default configurations.
36 {
Corentin Wallez5ba008952018-03-20 19:16:0637 "mastername": "luci.chromium.try",
Jamie Madilla25be152019-04-12 17:15:3338 "buildernames": ["linux-angle-rel"]
Kenneth Russell220f23b02017-12-05 09:02:2839 },
40 {
Corentin Wallezb78c44a2018-04-12 14:29:4741 "mastername": "luci.chromium.try",
Yuly Novikovbc1ccff2019-08-03 00:05:4942 "buildernames": ["win-angle-rel-32"]
43 },
44 {
45 "mastername": "luci.chromium.try",
46 "buildernames": ["win-angle-rel-64"]
Kenneth Russell220f23b02017-12-05 09:02:2847 },
kbre85ee562016-02-09 04:37:3548]
49
50SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
51SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir))
52sys.path.insert(0, os.path.join(SRC_DIR, 'build'))
53import find_depot_tools
54find_depot_tools.add_depot_tools_to_path()
kbre85ee562016-02-09 04:37:3555
56CHROMIUM_GIT_URL = 'https://chromium.googlesource.com/chromium/src.git'
57CL_ISSUE_RE = re.compile('^Issue number: ([0-9]+) \((.*)\)$')
Aaron Gable8a899722017-10-11 21:49:1558REVIEW_URL_RE = re.compile('^https?://(.*)/(.*)')
kbre85ee562016-02-09 04:37:3559ROLL_BRANCH_NAME = 'special_webgl_roll_branch'
60TRYJOB_STATUS_SLEEP_SECONDS = 30
61
62# Use a shell for subcommands on Windows to get a PATH search.
63IS_WIN = sys.platform.startswith('win')
64WEBGL_PATH = os.path.join('third_party', 'webgl', 'src')
kbr0ea13b4c2017-02-16 20:01:5065WEBGL_REVISION_TEXT_FILE = os.path.join(
66 'content', 'test', 'gpu', 'gpu_tests', 'webgl_conformance_revision.txt')
kbre85ee562016-02-09 04:37:3567
68CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
69 'git_repo_url'])
Aaron Gable8a899722017-10-11 21:49:1570CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'review_server'])
kbre85ee562016-02-09 04:37:3571
Kenneth Russell3c5f9252017-08-18 21:49:5472
73def _VarLookup(local_scope):
74 return lambda var_name: local_scope['vars'][var_name]
75
76
kbre85ee562016-02-09 04:37:3577def _PosixPath(path):
78 """Convert a possibly-Windows path to a posix-style path."""
79 (_, path) = os.path.splitdrive(path)
80 return path.replace(os.sep, '/')
81
82def _ParseGitCommitHash(description):
83 for line in description.splitlines():
84 if line.startswith('commit '):
85 return line.split()[1]
86 logging.error('Failed to parse git commit id from:\n%s\n', description)
87 sys.exit(-1)
88 return None
89
90
91def _ParseDepsFile(filename):
92 with open(filename, 'rb') as f:
93 deps_content = f.read()
94 return _ParseDepsDict(deps_content)
95
96
97def _ParseDepsDict(deps_content):
98 local_scope = {}
kbre85ee562016-02-09 04:37:3599 global_scope = {
Kenneth Russell3bf6fa12020-07-25 15:41:08100 'Str': lambda arg: str(arg),
101 'Var': _VarLookup(local_scope),
102 'deps_os': {},
kbre85ee562016-02-09 04:37:35103 }
104 exec(deps_content, global_scope, local_scope)
105 return local_scope
106
107
108def _GenerateCLDescriptionCommand(webgl_current, webgl_new, bugs):
109 def GetChangeString(current_hash, new_hash):
110 return '%s..%s' % (current_hash[0:7], new_hash[0:7]);
111
112 def GetChangeLogURL(git_repo_url, change_string):
113 return '%s/+log/%s' % (git_repo_url, change_string)
114
115 def GetBugString(bugs):
Kenneth Russell6792e642017-12-19 03:23:08116 bug_str = 'Bug: '
kbre85ee562016-02-09 04:37:35117 for bug in bugs:
118 bug_str += str(bug) + ','
119 return bug_str.rstrip(',')
120
kbr0ea13b4c2017-02-16 20:01:50121 change_str = GetChangeString(webgl_current.git_commit,
122 webgl_new.git_commit)
123 changelog_url = GetChangeLogURL(webgl_current.git_repo_url,
124 change_str)
125 if webgl_current.git_commit == webgl_new.git_commit:
Raul Tambre66e754d2019-09-25 12:03:44126 print('WARNING: WebGL repository is unchanged; proceeding with no-op roll')
kbre85ee562016-02-09 04:37:35127
128 def GetExtraTrybotString():
129 s = ''
130 for t in extra_trybots:
131 if s:
132 s += ';'
133 s += t['mastername'] + ':' + ','.join(t['buildernames'])
134 return s
135
Kenneth Russell6792e642017-12-19 03:23:08136 return ('Roll WebGL %s\n\n'
137 '%s\n\n'
138 '%s\n'
139 'Cq-Include-Trybots: %s\n') % (
140 change_str,
141 changelog_url,
142 GetBugString(bugs),
143 GetExtraTrybotString())
kbre85ee562016-02-09 04:37:35144
145
146class AutoRoller(object):
147 def __init__(self, chromium_src):
148 self._chromium_src = chromium_src
149
150 def _RunCommand(self, command, working_dir=None, ignore_exit_code=False,
151 extra_env=None):
152 """Runs a command and returns the stdout from that command.
153
154 If the command fails (exit code != 0), the function will exit the process.
155 """
156 working_dir = working_dir or self._chromium_src
157 logging.debug('cmd: %s cwd: %s', ' '.join(command), working_dir)
158 env = os.environ.copy()
159 if extra_env:
160 logging.debug('extra env: %s', extra_env)
161 env.update(extra_env)
162 p = subprocess.Popen(command, stdout=subprocess.PIPE,
163 stderr=subprocess.PIPE, shell=IS_WIN, env=env,
164 cwd=working_dir, universal_newlines=True)
165 output = p.stdout.read()
166 p.wait()
167 p.stdout.close()
168 p.stderr.close()
169
170 if not ignore_exit_code and p.returncode != 0:
171 logging.error('Command failed: %s\n%s', str(command), output)
172 sys.exit(p.returncode)
173 return output
174
175 def _GetCommitInfo(self, path_below_src, git_hash=None, git_repo_url=None):
176 working_dir = os.path.join(self._chromium_src, path_below_src)
177 self._RunCommand(['git', 'fetch', 'origin'], working_dir=working_dir)
178 revision_range = git_hash or 'origin'
179 ret = self._RunCommand(
agable2e9de0e82016-10-20 01:03:18180 ['git', '--no-pager', 'log', revision_range,
181 '--no-abbrev-commit', '--pretty=full', '-1'],
kbre85ee562016-02-09 04:37:35182 working_dir=working_dir)
183 return CommitInfo(_ParseGitCommitHash(ret), git_repo_url)
184
185 def _GetDepsCommitInfo(self, deps_dict, path_below_src):
186 entry = deps_dict['deps'][_PosixPath('src/%s' % path_below_src)]
187 at_index = entry.find('@')
188 git_repo_url = entry[:at_index]
189 git_hash = entry[at_index + 1:]
190 return self._GetCommitInfo(path_below_src, git_hash, git_repo_url)
191
192 def _GetCLInfo(self):
193 cl_output = self._RunCommand(['git', 'cl', 'issue'])
194 m = CL_ISSUE_RE.match(cl_output.strip())
195 if not m:
196 logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
197 sys.exit(-1)
198 issue_number = int(m.group(1))
199 url = m.group(2)
200
Aaron Gable8a899722017-10-11 21:49:15201 # Parse the codereview host from the URL.
202 m = REVIEW_URL_RE.match(url)
kbre85ee562016-02-09 04:37:35203 if not m:
Aaron Gable8a899722017-10-11 21:49:15204 logging.error('Cannot parse codereview host from URL: %s', url)
kbre85ee562016-02-09 04:37:35205 sys.exit(-1)
Aaron Gable8a899722017-10-11 21:49:15206 review_server = m.group(1)
207 return CLInfo(issue_number, url, review_server)
kbre85ee562016-02-09 04:37:35208
209 def _GetCurrentBranchName(self):
210 return self._RunCommand(
211 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
212
213 def _IsTreeClean(self):
214 lines = self._RunCommand(
215 ['git', 'status', '--porcelain', '-uno']).splitlines()
216 if len(lines) == 0:
217 return True
218
219 logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
220 return False
221
222 def _GetBugList(self, path_below_src, webgl_current, webgl_new):
223 # TODO(kbr): this isn't useful, at least not yet, when run against
224 # the WebGL Github repository.
225 working_dir = os.path.join(self._chromium_src, path_below_src)
226 lines = self._RunCommand(
227 ['git','log',
228 '%s..%s' % (webgl_current.git_commit, webgl_new.git_commit)],
229 working_dir=working_dir).split('\n')
230 bugs = set()
231 for line in lines:
232 line = line.strip()
233 bug_prefix = 'BUG='
234 if line.startswith(bug_prefix):
235 bugs_strings = line[len(bug_prefix):].split(',')
236 for bug_string in bugs_strings:
237 try:
238 bugs.add(int(bug_string))
239 except:
240 # skip this, it may be a project specific bug such as
241 # "angleproject:X" or an ill-formed BUG= message
242 pass
243 return bugs
244
245 def _UpdateReadmeFile(self, readme_path, new_revision):
246 readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
247 txt = readme.read()
248 m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
249 ('Revision: %s' % new_revision), txt)
250 readme.seek(0)
251 readme.write(m)
252 readme.truncate()
253
zmo3eaa0912016-04-16 00:03:05254 def PrepareRoll(self, ignore_checks, run_tryjobs):
kbre85ee562016-02-09 04:37:35255 # TODO(kjellander): use os.path.normcase, os.path.join etc for all paths for
256 # cross platform compatibility.
257
258 if not ignore_checks:
259 if self._GetCurrentBranchName() != 'master':
260 logging.error('Please checkout the master branch.')
261 return -1
262 if not self._IsTreeClean():
263 logging.error('Please make sure you don\'t have any modified files.')
264 return -1
265
266 # Always clean up any previous roll.
267 self.Abort()
268
269 logging.debug('Pulling latest changes')
270 if not ignore_checks:
271 self._RunCommand(['git', 'pull'])
272
273 self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
274
275 # Modify Chromium's DEPS file.
276
277 # Parse current hashes.
278 deps_filename = os.path.join(self._chromium_src, 'DEPS')
279 deps = _ParseDepsFile(deps_filename)
280 webgl_current = self._GetDepsCommitInfo(deps, WEBGL_PATH)
281
282 # Find ToT revisions.
283 webgl_latest = self._GetCommitInfo(WEBGL_PATH)
284
285 if IS_WIN:
286 # Make sure the roll script doesn't use windows line endings
287 self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
288
289 self._UpdateDep(deps_filename, WEBGL_PATH, webgl_latest)
kbr0ea13b4c2017-02-16 20:01:50290 self._UpdateWebGLRevTextFile(WEBGL_REVISION_TEXT_FILE, webgl_latest)
kbre85ee562016-02-09 04:37:35291
292 if self._IsTreeClean():
293 logging.debug('Tree is clean - no changes detected.')
294 self._DeleteRollBranch()
295 else:
296 bugs = self._GetBugList(WEBGL_PATH, webgl_current, webgl_latest)
297 description = _GenerateCLDescriptionCommand(
298 webgl_current, webgl_latest, bugs)
299 logging.debug('Committing changes locally.')
300 self._RunCommand(['git', 'add', '--update', '.'])
Kenneth Russell6792e642017-12-19 03:23:08301 self._RunCommand(['git', 'commit', '-m', description])
kbre85ee562016-02-09 04:37:35302 logging.debug('Uploading changes...')
303 self._RunCommand(['git', 'cl', 'upload'],
304 extra_env={'EDITOR': 'true'})
305
zmo3eaa0912016-04-16 00:03:05306 if run_tryjobs:
kbrb2921312016-04-06 20:52:10307 # Kick off tryjobs.
308 base_try_cmd = ['git', 'cl', 'try']
309 self._RunCommand(base_try_cmd)
kbre85ee562016-02-09 04:37:35310
311 cl_info = self._GetCLInfo()
Raul Tambre66e754d2019-09-25 12:03:44312 print('Issue: %d URL: %s' % (cl_info.issue, cl_info.url))
kbre85ee562016-02-09 04:37:35313
314 # Checkout master again.
315 self._RunCommand(['git', 'checkout', 'master'])
Raul Tambre66e754d2019-09-25 12:03:44316 print('Roll branch left as ' + ROLL_BRANCH_NAME)
kbre85ee562016-02-09 04:37:35317 return 0
318
319 def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info):
320 dep_name = _PosixPath(os.path.join('src', dep_relative_to_src))
Edward Lemur0cce209e2019-11-21 21:36:55321 dep_revision = '%s@%s' % (dep_name, commit_info.git_commit)
322 self._RunCommand(
323 ['gclient', 'setdep', '-r', dep_revision],
Jiajie Hufa24cfd42019-11-28 15:30:20324 working_dir=os.path.dirname(deps_filename))
kbre85ee562016-02-09 04:37:35325
kbr0ea13b4c2017-02-16 20:01:50326 def _UpdateWebGLRevTextFile(self, txt_filename, commit_info):
327 # Rolling the WebGL conformance tests must cause at least all of
328 # the WebGL tests to run. There are already exclusions in
329 # trybot_analyze_config.json which force all tests to run if
330 # changes under src/content/test/gpu are made. (This rule
331 # typically only takes effect on the GPU bots.) To make sure this
332 # happens all the time, update an autogenerated text file in this
333 # directory.
334 with open(txt_filename, 'w') as fh:
Raul Tambre66e754d2019-09-25 12:03:44335 print('# AUTOGENERATED FILE - DO NOT EDIT', file=fh)
336 print('# SEE roll_webgl_conformance.py', file=fh)
337 print('Current webgl revision %s' % commit_info.git_commit, file=fh)
kbr0ea13b4c2017-02-16 20:01:50338
kbre85ee562016-02-09 04:37:35339 def _DeleteRollBranch(self):
340 self._RunCommand(['git', 'checkout', 'master'])
341 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
342 logging.debug('Deleted the local roll branch (%s)', ROLL_BRANCH_NAME)
343
344
345 def _GetBranches(self):
346 """Returns a tuple of active,branches.
347
348 The 'active' is the name of the currently active branch and 'branches' is a
349 list of all branches.
350 """
351 lines = self._RunCommand(['git', 'branch']).split('\n')
352 branches = []
353 active = ''
354 for l in lines:
355 if '*' in l:
356 # The assumption is that the first char will always be the '*'.
357 active = l[1:].strip()
358 branches.append(active)
359 else:
360 b = l.strip()
361 if b:
362 branches.append(b)
363 return (active, branches)
364
365 def Abort(self):
366 active_branch, branches = self._GetBranches()
367 if active_branch == ROLL_BRANCH_NAME:
368 active_branch = 'master'
369 if ROLL_BRANCH_NAME in branches:
Raul Tambre66e754d2019-09-25 12:03:44370 print('Aborting pending roll.')
kbre85ee562016-02-09 04:37:35371 self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME])
372 # Ignore an error here in case an issue wasn't created for some reason.
373 self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True)
374 self._RunCommand(['git', 'checkout', active_branch])
375 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
376 return 0
377
378
379def main():
380 parser = argparse.ArgumentParser(
381 description='Auto-generates a CL containing a WebGL conformance roll.')
382 parser.add_argument('--abort',
383 help=('Aborts a previously prepared roll. '
384 'Closes any associated issues and deletes the roll branches'),
385 action='store_true')
386 parser.add_argument('--ignore-checks', action='store_true', default=False,
387 help=('Skips checks for being on the master branch, dirty workspaces and '
388 'the updating of the checkout. Will still delete and create local '
389 'Git branches.'))
zmo3eaa0912016-04-16 00:03:05390 parser.add_argument('--run-tryjobs', action='store_true', default=False,
391 help=('Start the dry-run tryjobs for the newly generated CL. Use this '
392 'when you have no need to make changes to the WebGL conformance '
393 'test expectations in the same CL and want to avoid.'))
kbre85ee562016-02-09 04:37:35394 parser.add_argument('-v', '--verbose', action='store_true', default=False,
395 help='Be extra verbose in printing of log messages.')
396 args = parser.parse_args()
397
398 if args.verbose:
399 logging.basicConfig(level=logging.DEBUG)
400 else:
401 logging.basicConfig(level=logging.ERROR)
402
403 autoroller = AutoRoller(SRC_DIR)
404 if args.abort:
405 return autoroller.Abort()
406 else:
zmo3eaa0912016-04-16 00:03:05407 return autoroller.PrepareRoll(args.ignore_checks, args.run_tryjobs)
kbre85ee562016-02-09 04:37:35408
409if __name__ == '__main__':
410 sys.exit(main())