2 # Copyright 2015 The Chromium Authors
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 from __future__ import print_function
19 "mastername": "luci.chromium.try",
20 "buildernames": ["win_optional_gpu_tests_rel"]
23 "mastername": "luci.chromium.try",
24 "buildernames": ["mac_optional_gpu_tests_rel"]
27 "mastername": "luci.chromium.try",
28 "buildernames": ["linux_optional_gpu_tests_rel"]
31 "mastername": "luci.chromium.try",
32 "buildernames": ["android_optional_gpu_tests_rel"]
35 "mastername": "luci.chromium.try",
36 "buildernames": ["gpu-fyi-cq-android-arm64"]
40 SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
41 SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir))
42 sys.path.insert(0, os.path.join(SRC_DIR, 'build'))
43 import find_depot_tools
44 find_depot_tools.add_depot_tools_to_path()
46 CHROMIUM_GIT_URL = 'https://chromium.googlesource.com/chromium/src.git'
47 CL_ISSUE_RE = re.compile('^Issue number: ([0-9]+) \((.*)\)$')
48 REVIEW_URL_RE = re.compile('^https?://(.*)/(.*)')
49 ROLL_BRANCH_NAME = 'special_webgl_roll_branch'
50 TRYJOB_STATUS_SLEEP_SECONDS = 30
52 # Use a shell for subcommands on Windows to get a PATH search.
53 IS_WIN = sys.platform.startswith('win')
54 WEBGL_PATH = os.path.join('third_party', 'webgl', 'src')
55 WEBGL_REVISION_TEXT_FILE = os.path.join(
56 'content', 'test', 'gpu', 'gpu_tests', 'webgl_conformance_revision.txt')
58 CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
60 CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'review_server'])
63 def _VarLookup(local_scope):
64 return lambda var_name: local_scope['vars'][var_name]
68 """Convert a possibly-Windows path to a posix-style path."""
69 (_, path) = os.path.splitdrive(path)
70 return path.replace(os.sep, '/')
72 def _ParseGitCommitHash(description):
73 for line in description.splitlines():
74 if line.startswith('commit '):
75 return line.split()[1]
76 logging.error('Failed to parse git commit id from:\n%s\n', description)
81 def _ParseDepsFile(filename):
82 logging.debug('Parsing deps file %s', filename)
83 with open(filename, 'rb') as f:
84 deps_content = f.read()
85 return _ParseDepsDict(deps_content)
88 def _ParseDepsDict(deps_content):
91 'Str': lambda arg: str(arg),
92 'Var': _VarLookup(local_scope),
95 exec(deps_content, global_scope, local_scope)
99 def _GenerateCLDescriptionCommand(webgl_current, webgl_new, bugs):
100 def GetChangeString(current_hash, new_hash):
101 return '%s..%s' % (current_hash[0:7], new_hash[0:7]);
103 def GetChangeLogURL(git_repo_url, change_string):
104 return '%s/+log/%s' % (git_repo_url, change_string)
106 def GetBugString(bugs):
109 bug_str += str(bug) + ','
110 return bug_str.rstrip(',')
112 change_str = GetChangeString(webgl_current.git_commit,
113 webgl_new.git_commit)
114 changelog_url = GetChangeLogURL(webgl_current.git_repo_url,
116 if webgl_current.git_commit == webgl_new.git_commit:
117 print('WARNING: WebGL repository is unchanged; proceeding with no-op roll')
119 def GetExtraTrybotString():
121 for t in extra_trybots:
124 s += t['mastername'] + ':' + ','.join(t['buildernames'])
127 return ('Roll WebGL %s\n\n'
130 'Cq-Include-Trybots: %s\n') % (
134 GetExtraTrybotString())
137 class AutoRoller(object):
138 def __init__(self, chromium_src):
139 self._chromium_src = chromium_src
141 def _RunCommand(self, command, working_dir=None, ignore_exit_code=False,
143 """Runs a command and returns the stdout from that command.
145 If the command fails (exit code != 0), the function will exit the process.
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()
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()
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)
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/main'
170 ret = self._RunCommand(
171 ['git', '--no-pager', 'log', revision_range,
172 '--no-abbrev-commit', '--pretty=full', '-1'],
173 working_dir=working_dir)
174 parsed_hash = _ParseGitCommitHash(ret)
175 logging.debug('parsed Git commit hash: %s', parsed_hash)
176 return CommitInfo(parsed_hash, git_repo_url)
178 def _GetDepsCommitInfo(self, deps_dict, path_below_src):
179 logging.debug('Getting deps commit info for %s', path_below_src)
180 entry = deps_dict['deps'][_PosixPath('src/%s' % path_below_src)]
181 at_index = entry.find('@')
182 git_repo_url = entry[:at_index]
183 git_hash = entry[at_index + 1:]
184 return self._GetCommitInfo(path_below_src, git_hash, git_repo_url)
186 def _GetCLInfo(self):
187 cl_output = self._RunCommand(['git', 'cl', 'issue'])
188 m = CL_ISSUE_RE.match(cl_output.strip())
190 logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
192 issue_number = int(m.group(1))
195 # Parse the codereview host from the URL.
196 m = REVIEW_URL_RE.match(url)
198 logging.error('Cannot parse codereview host from URL: %s', url)
200 review_server = m.group(1)
201 return CLInfo(issue_number, url, review_server)
203 def _GetCurrentBranchName(self):
204 return self._RunCommand(
205 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
207 def _IsTreeClean(self):
208 lines = self._RunCommand(
209 ['git', 'status', '--porcelain', '-uno']).splitlines()
213 logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
216 def _GetBugList(self, path_below_src, webgl_current, webgl_new):
217 # TODO(kbr): this isn't useful, at least not yet, when run against
218 # the WebGL Github repository.
219 working_dir = os.path.join(self._chromium_src, path_below_src)
220 lines = self._RunCommand(
222 '%s..%s' % (webgl_current.git_commit, webgl_new.git_commit)],
223 working_dir=working_dir).split('\n')
228 if line.startswith(bug_prefix):
229 bugs_strings = line[len(bug_prefix):].split(',')
230 for bug_string in bugs_strings:
232 bugs.add(int(bug_string))
234 # skip this, it may be a project specific bug such as
235 # "angleproject:X" or an ill-formed BUG= message
239 def _UpdateReadmeFile(self, readme_path, new_revision):
240 readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
242 m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
243 ('Revision: %s' % new_revision), txt)
248 def PrepareRoll(self, ignore_checks, run_tryjobs):
249 # TODO(kjellander): use os.path.normcase, os.path.join etc for all paths for
250 # cross platform compatibility.
252 if not ignore_checks:
253 if self._GetCurrentBranchName() != 'main':
254 logging.error('Please checkout the main branch.')
256 if not self._IsTreeClean():
257 logging.error('Please make sure you don\'t have any modified files.')
260 # Always clean up any previous roll.
263 logging.debug('Pulling latest changes')
264 if not ignore_checks:
265 self._RunCommand(['git', 'pull'])
266 self._RunCommand(['gclient', 'sync'])
268 self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
270 # Modify Chromium's DEPS file.
272 # Parse current hashes.
273 deps_filename = os.path.join(self._chromium_src, 'DEPS')
274 deps = _ParseDepsFile(deps_filename)
275 webgl_current = self._GetDepsCommitInfo(deps, WEBGL_PATH)
277 # Find ToT revisions.
278 webgl_latest = self._GetCommitInfo(WEBGL_PATH)
281 # Make sure the roll script doesn't use windows line endings
282 self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
284 self._UpdateDep(deps_filename, WEBGL_PATH, webgl_latest)
285 self._UpdateWebGLRevTextFile(WEBGL_REVISION_TEXT_FILE, webgl_latest)
287 if self._IsTreeClean():
288 logging.debug('Tree is clean - no changes detected.')
289 self._DeleteRollBranch()
291 bugs = self._GetBugList(WEBGL_PATH, webgl_current, webgl_latest)
292 description = _GenerateCLDescriptionCommand(
293 webgl_current, webgl_latest, bugs)
294 logging.debug('Committing changes locally.')
295 self._RunCommand(['git', 'add', '--update', '.'])
296 self._RunCommand(['git', 'commit', '-m', description])
297 logging.debug('Uploading changes...')
298 self._RunCommand(['git', 'cl', 'upload'],
299 extra_env={'EDITOR': 'true'})
303 base_try_cmd = ['git', 'cl', 'try']
304 self._RunCommand(base_try_cmd)
306 cl_info = self._GetCLInfo()
307 print('Issue: %d URL: %s' % (cl_info.issue, cl_info.url))
309 # Checkout main again.
310 self._RunCommand(['git', 'checkout', 'main'])
311 self._RunCommand(['gclient', 'sync'])
312 print('Roll branch left as ' + ROLL_BRANCH_NAME)
315 def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info):
316 dep_name = _PosixPath(os.path.join('src', dep_relative_to_src))
317 dep_revision = '%s@%s' % (dep_name, commit_info.git_commit)
319 ['gclient', 'setdep', '-r', dep_revision],
320 working_dir=os.path.dirname(deps_filename))
321 self._RunCommand(['gclient', 'sync'])
323 def _UpdateWebGLRevTextFile(self, txt_filename, commit_info):
324 # Rolling the WebGL conformance tests must cause at least all of
325 # the WebGL tests to run. There are already exclusions in
326 # trybot_analyze_config.json which force all tests to run if
327 # changes under src/content/test/gpu are made. (This rule
328 # typically only takes effect on the GPU bots.) To make sure this
329 # happens all the time, update an autogenerated text file in this
331 with open(txt_filename, 'w') as fh:
332 print('# AUTOGENERATED FILE - DO NOT EDIT', file=fh)
333 print('# SEE roll_webgl_conformance.py', file=fh)
334 print('Current webgl revision %s' % commit_info.git_commit, file=fh)
336 def _DeleteRollBranch(self):
337 self._RunCommand(['git', 'checkout', 'main'])
338 self._RunCommand(['gclient', 'sync'])
339 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
340 logging.debug('Deleted the local roll branch (%s)', ROLL_BRANCH_NAME)
343 def _GetBranches(self):
344 """Returns a tuple of active,branches.
346 The 'active' is the name of the currently active branch and 'branches' is a
347 list of all branches.
349 lines = self._RunCommand(['git', 'branch']).split('\n')
354 # The assumption is that the first char will always be the '*'.
355 active = l[1:].strip()
356 branches.append(active)
361 return (active, branches)
364 active_branch, branches = self._GetBranches()
365 if active_branch == ROLL_BRANCH_NAME:
366 active_branch = 'main'
367 if ROLL_BRANCH_NAME in branches:
368 print('Aborting pending roll.')
369 self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME])
370 # Ignore an error here in case an issue wasn't created for some reason.
371 self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True)
372 self._RunCommand(['git', 'checkout', active_branch])
373 self._RunCommand(['gclient', 'sync'])
374 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
379 parser = argparse.ArgumentParser(
380 description='Auto-generates a CL containing a WebGL conformance roll.')
381 parser.add_argument('--abort',
382 help=('Aborts a previously prepared roll. '
383 'Closes any associated issues and deletes the roll branches'),
389 help=('Skips checks for being on the main branch, dirty workspaces and '
390 'the updating of the checkout. Will still delete and create local '
392 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.'))
396 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()
401 logging.basicConfig(level=logging.DEBUG)
403 logging.basicConfig(level=logging.ERROR)
405 autoroller = AutoRoller(SRC_DIR)
407 return autoroller.Abort()
409 return autoroller.PrepareRoll(args.ignore_checks, args.run_tryjobs)
411 if __name__ == '__main__':