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