[PDNCF] Python 3.12 compatibility
[platform/framework/web/chromium-efl.git] / tools / roll_webgl_conformance.py
1 #!/usr/bin/env python3
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.
5
6 from __future__ import print_function
7
8 import argparse
9 import collections
10 import logging
11 import os
12 import re
13 import subprocess
14 import sys
15 import time
16
17 extra_trybots = [
18     {
19         "mastername": "luci.chromium.try",
20         "buildernames": ["win_optional_gpu_tests_rel"]
21     },
22     {
23         "mastername": "luci.chromium.try",
24         "buildernames": ["mac_optional_gpu_tests_rel"]
25     },
26     {
27         "mastername": "luci.chromium.try",
28         "buildernames": ["linux_optional_gpu_tests_rel"]
29     },
30     {
31         "mastername": "luci.chromium.try",
32         "buildernames": ["android_optional_gpu_tests_rel"]
33     },
34     {
35         "mastername": "luci.chromium.try",
36         "buildernames": ["gpu-fyi-cq-android-arm64"]
37     },
38 ]
39
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()
45
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
51
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')
57
58 CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
59                                                    'git_repo_url'])
60 CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'review_server'])
61
62
63 def _VarLookup(local_scope):
64   return lambda var_name: local_scope['vars'][var_name]
65
66
67 def _PosixPath(path):
68   """Convert a possibly-Windows path to a posix-style path."""
69   (_, path) = os.path.splitdrive(path)
70   return path.replace(os.sep, '/')
71
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)
77   sys.exit(-1)
78   return None
79
80
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)
86
87
88 def _ParseDepsDict(deps_content):
89   local_scope = {}
90   global_scope = {
91       'Str': lambda arg: str(arg),
92       'Var': _VarLookup(local_scope),
93       'deps_os': {},
94   }
95   exec(deps_content, global_scope, local_scope)
96   return local_scope
97
98
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]);
102
103   def GetChangeLogURL(git_repo_url, change_string):
104     return '%s/+log/%s' % (git_repo_url, change_string)
105
106   def GetBugString(bugs):
107     bug_str = 'Bug: '
108     for bug in bugs:
109       bug_str += str(bug) + ','
110     return bug_str.rstrip(',')
111
112   change_str = GetChangeString(webgl_current.git_commit,
113                                webgl_new.git_commit)
114   changelog_url = GetChangeLogURL(webgl_current.git_repo_url,
115                                   change_str)
116   if webgl_current.git_commit == webgl_new.git_commit:
117     print('WARNING: WebGL repository is unchanged; proceeding with no-op roll')
118
119   def GetExtraTrybotString():
120     s = ''
121     for t in extra_trybots:
122       if s:
123         s += ';'
124       s += t['mastername'] + ':' + ','.join(t['buildernames'])
125     return s
126
127   return ('Roll WebGL %s\n\n'
128           '%s\n\n'
129           '%s\n'
130           'Cq-Include-Trybots: %s\n') % (
131             change_str,
132             changelog_url,
133             GetBugString(bugs),
134             GetExtraTrybotString())
135
136
137 class 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/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)
177
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)
185
186   def _GetCLInfo(self):
187     cl_output = self._RunCommand(['git', 'cl', 'issue'])
188     m = CL_ISSUE_RE.match(cl_output.strip())
189     if not m:
190       logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
191       sys.exit(-1)
192     issue_number = int(m.group(1))
193     url = m.group(2)
194
195     # Parse the codereview host from the URL.
196     m = REVIEW_URL_RE.match(url)
197     if not m:
198       logging.error('Cannot parse codereview host from URL: %s', url)
199       sys.exit(-1)
200     review_server = m.group(1)
201     return CLInfo(issue_number, url, review_server)
202
203   def _GetCurrentBranchName(self):
204     return self._RunCommand(
205         ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
206
207   def _IsTreeClean(self):
208     lines = self._RunCommand(
209       ['git', 'status', '--porcelain', '-uno']).splitlines()
210     if len(lines) == 0:
211       return True
212
213     logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
214     return False
215
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(
221         ['git','log',
222             '%s..%s' % (webgl_current.git_commit, webgl_new.git_commit)],
223         working_dir=working_dir).split('\n')
224     bugs = set()
225     for line in lines:
226       line = line.strip()
227       bug_prefix = 'BUG='
228       if line.startswith(bug_prefix):
229         bugs_strings = line[len(bug_prefix):].split(',')
230         for bug_string in bugs_strings:
231           try:
232             bugs.add(int(bug_string))
233           except:
234             # skip this, it may be a project specific bug such as
235             # "angleproject:X" or an ill-formed BUG= message
236             pass
237     return bugs
238
239   def _UpdateReadmeFile(self, readme_path, new_revision):
240     readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
241     txt = readme.read()
242     m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
243         ('Revision: %s' % new_revision), txt)
244     readme.seek(0)
245     readme.write(m)
246     readme.truncate()
247
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.
251
252     if not ignore_checks:
253       if self._GetCurrentBranchName() != 'main':
254         logging.error('Please checkout the main branch.')
255         return -1
256       if not self._IsTreeClean():
257         logging.error('Please make sure you don\'t have any modified files.')
258         return -1
259
260     # Always clean up any previous roll.
261     self.Abort()
262
263     logging.debug('Pulling latest changes')
264     if not ignore_checks:
265       self._RunCommand(['git', 'pull'])
266       self._RunCommand(['gclient', 'sync'])
267
268     self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
269
270     # Modify Chromium's DEPS file.
271
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)
276
277     # Find ToT revisions.
278     webgl_latest = self._GetCommitInfo(WEBGL_PATH)
279
280     if IS_WIN:
281       # Make sure the roll script doesn't use windows line endings
282       self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
283
284     self._UpdateDep(deps_filename, WEBGL_PATH, webgl_latest)
285     self._UpdateWebGLRevTextFile(WEBGL_REVISION_TEXT_FILE, webgl_latest)
286
287     if self._IsTreeClean():
288       logging.debug('Tree is clean - no changes detected.')
289       self._DeleteRollBranch()
290     else:
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'})
300
301       if run_tryjobs:
302         # Kick off tryjobs.
303         base_try_cmd = ['git', 'cl', 'try']
304         self._RunCommand(base_try_cmd)
305
306       cl_info = self._GetCLInfo()
307       print('Issue: %d URL: %s' % (cl_info.issue, cl_info.url))
308
309     # Checkout main again.
310     self._RunCommand(['git', 'checkout', 'main'])
311     self._RunCommand(['gclient', 'sync'])
312     print('Roll branch left as ' + ROLL_BRANCH_NAME)
313     return 0
314
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)
318     self._RunCommand(
319         ['gclient', 'setdep', '-r', dep_revision],
320         working_dir=os.path.dirname(deps_filename))
321     self._RunCommand(['gclient', 'sync'])
322
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
330     # directory.
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)
335
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)
341
342
343   def _GetBranches(self):
344     """Returns a tuple of active,branches.
345
346     The 'active' is the name of the currently active branch and 'branches' is a
347     list of all branches.
348     """
349     lines = self._RunCommand(['git', 'branch']).split('\n')
350     branches = []
351     active = ''
352     for l in lines:
353       if '*' in l:
354         # The assumption is that the first char will always be the '*'.
355         active = l[1:].strip()
356         branches.append(active)
357       else:
358         b = l.strip()
359         if b:
360           branches.append(b)
361     return (active, branches)
362
363   def Abort(self):
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])
375     return 0
376
377
378 def main():
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'),
384     action='store_true')
385   parser.add_argument(
386       '--ignore-checks',
387       action='store_true',
388       default=False,
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 '
391             'Git branches.'))
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()
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:
409     return autoroller.PrepareRoll(args.ignore_checks, args.run_tryjobs)
410
411 if __name__ == '__main__':
412   sys.exit(main())