blob: da9a1bda20d12b786629710d7dd1b48fe33f7a6b [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
40from gclient import GClientKeywords
41from third_party import upload
42
43# Avoid depot_tools/third_party/upload.py print verbose messages.
44upload.verbosity = 0 # Errors only.
45
46CHROMIUM_GIT_URL = 'https://chromium.googlesource.com/chromium/src.git'
47CL_ISSUE_RE = re.compile('^Issue number: ([0-9]+) \((.*)\)$')
48RIETVELD_URL_RE = re.compile('^https?://(.*)/(.*)')
49ROLL_BRANCH_NAME = 'special_webgl_roll_branch'
50TRYJOB_STATUS_SLEEP_SECONDS = 30
51
52# Use a shell for subcommands on Windows to get a PATH search.
53IS_WIN = sys.platform.startswith('win')
54WEBGL_PATH = os.path.join('third_party', 'webgl', 'src')
kbr0ea13b4c2017-02-16 20:01:5055WEBGL_REVISION_TEXT_FILE = os.path.join(
56 'content', 'test', 'gpu', 'gpu_tests', 'webgl_conformance_revision.txt')
kbre85ee562016-02-09 04:37:3557
58CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
59 'git_repo_url'])
60CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'rietveld_server'])
61
62def _PosixPath(path):
63 """Convert a possibly-Windows path to a posix-style path."""
64 (_, path) = os.path.splitdrive(path)
65 return path.replace(os.sep, '/')
66
67def _ParseGitCommitHash(description):
68 for line in description.splitlines():
69 if line.startswith('commit '):
70 return line.split()[1]
71 logging.error('Failed to parse git commit id from:\n%s\n', description)
72 sys.exit(-1)
73 return None
74
75
76def _ParseDepsFile(filename):
77 with open(filename, 'rb') as f:
78 deps_content = f.read()
79 return _ParseDepsDict(deps_content)
80
81
82def _ParseDepsDict(deps_content):
83 local_scope = {}
84 var = GClientKeywords.VarImpl({}, local_scope)
85 global_scope = {
kbre85ee562016-02-09 04:37:3586 'Var': var.Lookup,
87 'deps_os': {},
88 }
89 exec(deps_content, global_scope, local_scope)
90 return local_scope
91
92
93def _GenerateCLDescriptionCommand(webgl_current, webgl_new, bugs):
94 def GetChangeString(current_hash, new_hash):
95 return '%s..%s' % (current_hash[0:7], new_hash[0:7]);
96
97 def GetChangeLogURL(git_repo_url, change_string):
98 return '%s/+log/%s' % (git_repo_url, change_string)
99
100 def GetBugString(bugs):
101 bug_str = 'BUG='
102 for bug in bugs:
103 bug_str += str(bug) + ','
104 return bug_str.rstrip(',')
105
kbr0ea13b4c2017-02-16 20:01:50106 change_str = GetChangeString(webgl_current.git_commit,
107 webgl_new.git_commit)
108 changelog_url = GetChangeLogURL(webgl_current.git_repo_url,
109 change_str)
110 if webgl_current.git_commit == webgl_new.git_commit:
111 print 'WARNING: WebGL repository is unchanged; proceeding with no-op roll'
kbre85ee562016-02-09 04:37:35112
113 def GetExtraTrybotString():
114 s = ''
115 for t in extra_trybots:
116 if s:
117 s += ';'
118 s += t['mastername'] + ':' + ','.join(t['buildernames'])
119 return s
120
121 extra_trybot_args = []
122 if extra_trybots:
123 extra_trybot_string = GetExtraTrybotString()
124 extra_trybot_args = ['-m', 'CQ_INCLUDE_TRYBOTS=' + extra_trybot_string]
125
126 return [
127 '-m', 'Roll WebGL ' + change_str,
128 '-m', '%s' % changelog_url,
129 '-m', GetBugString(bugs),
130 '-m', 'TEST=bots',
131 ] + extra_trybot_args
132
133
134class AutoRoller(object):
135 def __init__(self, chromium_src):
136 self._chromium_src = chromium_src
137
138 def _RunCommand(self, command, working_dir=None, ignore_exit_code=False,
139 extra_env=None):
140 """Runs a command and returns the stdout from that command.
141
142 If the command fails (exit code != 0), the function will exit the process.
143 """
144 working_dir = working_dir or self._chromium_src
145 logging.debug('cmd: %s cwd: %s', ' '.join(command), working_dir)
146 env = os.environ.copy()
147 if extra_env:
148 logging.debug('extra env: %s', extra_env)
149 env.update(extra_env)
150 p = subprocess.Popen(command, stdout=subprocess.PIPE,
151 stderr=subprocess.PIPE, shell=IS_WIN, env=env,
152 cwd=working_dir, universal_newlines=True)
153 output = p.stdout.read()
154 p.wait()
155 p.stdout.close()
156 p.stderr.close()
157
158 if not ignore_exit_code and p.returncode != 0:
159 logging.error('Command failed: %s\n%s', str(command), output)
160 sys.exit(p.returncode)
161 return output
162
163 def _GetCommitInfo(self, path_below_src, git_hash=None, git_repo_url=None):
164 working_dir = os.path.join(self._chromium_src, path_below_src)
165 self._RunCommand(['git', 'fetch', 'origin'], working_dir=working_dir)
166 revision_range = git_hash or 'origin'
167 ret = self._RunCommand(
agable2e9de0e82016-10-20 01:03:18168 ['git', '--no-pager', 'log', revision_range,
169 '--no-abbrev-commit', '--pretty=full', '-1'],
kbre85ee562016-02-09 04:37:35170 working_dir=working_dir)
171 return CommitInfo(_ParseGitCommitHash(ret), git_repo_url)
172
173 def _GetDepsCommitInfo(self, deps_dict, path_below_src):
174 entry = deps_dict['deps'][_PosixPath('src/%s' % path_below_src)]
175 at_index = entry.find('@')
176 git_repo_url = entry[:at_index]
177 git_hash = entry[at_index + 1:]
178 return self._GetCommitInfo(path_below_src, git_hash, git_repo_url)
179
180 def _GetCLInfo(self):
181 cl_output = self._RunCommand(['git', 'cl', 'issue'])
182 m = CL_ISSUE_RE.match(cl_output.strip())
183 if not m:
184 logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
185 sys.exit(-1)
186 issue_number = int(m.group(1))
187 url = m.group(2)
188
189 # Parse the Rietveld host from the URL.
190 m = RIETVELD_URL_RE.match(url)
191 if not m:
192 logging.error('Cannot parse Rietveld host from URL: %s', url)
193 sys.exit(-1)
194 rietveld_server = m.group(1)
195 return CLInfo(issue_number, url, rietveld_server)
196
197 def _GetCurrentBranchName(self):
198 return self._RunCommand(
199 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
200
201 def _IsTreeClean(self):
202 lines = self._RunCommand(
203 ['git', 'status', '--porcelain', '-uno']).splitlines()
204 if len(lines) == 0:
205 return True
206
207 logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
208 return False
209
210 def _GetBugList(self, path_below_src, webgl_current, webgl_new):
211 # TODO(kbr): this isn't useful, at least not yet, when run against
212 # the WebGL Github repository.
213 working_dir = os.path.join(self._chromium_src, path_below_src)
214 lines = self._RunCommand(
215 ['git','log',
216 '%s..%s' % (webgl_current.git_commit, webgl_new.git_commit)],
217 working_dir=working_dir).split('\n')
218 bugs = set()
219 for line in lines:
220 line = line.strip()
221 bug_prefix = 'BUG='
222 if line.startswith(bug_prefix):
223 bugs_strings = line[len(bug_prefix):].split(',')
224 for bug_string in bugs_strings:
225 try:
226 bugs.add(int(bug_string))
227 except:
228 # skip this, it may be a project specific bug such as
229 # "angleproject:X" or an ill-formed BUG= message
230 pass
231 return bugs
232
233 def _UpdateReadmeFile(self, readme_path, new_revision):
234 readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
235 txt = readme.read()
236 m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
237 ('Revision: %s' % new_revision), txt)
238 readme.seek(0)
239 readme.write(m)
240 readme.truncate()
241
zmo3eaa0912016-04-16 00:03:05242 def PrepareRoll(self, ignore_checks, run_tryjobs):
kbre85ee562016-02-09 04:37:35243 # TODO(kjellander): use os.path.normcase, os.path.join etc for all paths for
244 # cross platform compatibility.
245
246 if not ignore_checks:
247 if self._GetCurrentBranchName() != 'master':
248 logging.error('Please checkout the master branch.')
249 return -1
250 if not self._IsTreeClean():
251 logging.error('Please make sure you don\'t have any modified files.')
252 return -1
253
254 # Always clean up any previous roll.
255 self.Abort()
256
257 logging.debug('Pulling latest changes')
258 if not ignore_checks:
259 self._RunCommand(['git', 'pull'])
260
261 self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
262
263 # Modify Chromium's DEPS file.
264
265 # Parse current hashes.
266 deps_filename = os.path.join(self._chromium_src, 'DEPS')
267 deps = _ParseDepsFile(deps_filename)
268 webgl_current = self._GetDepsCommitInfo(deps, WEBGL_PATH)
269
270 # Find ToT revisions.
271 webgl_latest = self._GetCommitInfo(WEBGL_PATH)
272
273 if IS_WIN:
274 # Make sure the roll script doesn't use windows line endings
275 self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
276
277 self._UpdateDep(deps_filename, WEBGL_PATH, webgl_latest)
kbr0ea13b4c2017-02-16 20:01:50278 self._UpdateWebGLRevTextFile(WEBGL_REVISION_TEXT_FILE, webgl_latest)
kbre85ee562016-02-09 04:37:35279
280 if self._IsTreeClean():
281 logging.debug('Tree is clean - no changes detected.')
282 self._DeleteRollBranch()
283 else:
284 bugs = self._GetBugList(WEBGL_PATH, webgl_current, webgl_latest)
285 description = _GenerateCLDescriptionCommand(
286 webgl_current, webgl_latest, bugs)
287 logging.debug('Committing changes locally.')
288 self._RunCommand(['git', 'add', '--update', '.'])
289 self._RunCommand(['git', 'commit'] + description)
290 logging.debug('Uploading changes...')
291 self._RunCommand(['git', 'cl', 'upload'],
292 extra_env={'EDITOR': 'true'})
293
zmo3eaa0912016-04-16 00:03:05294 if run_tryjobs:
kbrb2921312016-04-06 20:52:10295 # Kick off tryjobs.
296 base_try_cmd = ['git', 'cl', 'try']
297 self._RunCommand(base_try_cmd)
298 if extra_trybots:
299 # Run additional tryjobs.
300 # TODO(kbr): this should not be necessary -- the
301 # CQ_INCLUDE_TRYBOTS directive above should handle it.
302 # http://crbug.com/585237
303 for trybot in extra_trybots:
304 for builder in trybot['buildernames']:
305 self._RunCommand(base_try_cmd + [
306 '-m', trybot['mastername'],
307 '-b', builder])
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())