blob: fe4c0fdcee2c738942f480f96742205095d6c81a [file] [log] [blame]
Kevin Lubick7f7b6ab2021-08-16 15:00:15 -04001#!/usr/bin/env python3
rmistry@google.com8e3ff8c2013-01-17 12:55:34 +00002# Copyright (c) 2013 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
6
7"""Top-level presubmit script for Skia.
8
9See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
10for more details about the presubmit API built into gcl.
11"""
12
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +000013import fnmatch
rmistry@google.comf6c5f752013-03-29 17:26:00 +000014import os
commit-bot@chromium.orgcfdc5962014-01-31 17:33:04 +000015import re
rmistryd223fb22015-02-26 10:16:13 -080016import subprocess
rmistry@google.comf6c5f752013-03-29 17:26:00 +000017import sys
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +000018import traceback
rmistry@google.comf6c5f752013-03-29 17:26:00 +000019
rmistry@google.comc2993442013-01-23 14:35:58 +000020
commit-bot@chromium.orgcfdc5962014-01-31 17:33:04 +000021REVERT_CL_SUBJECT_PREFIX = 'Revert '
22
rmistryf2d83ca2014-08-26 10:30:29 -070023# Please add the complete email address here (and not just 'xyz@' or 'xyz').
rmistry@google.comfb4a68d2013-08-12 14:51:20 +000024PUBLIC_API_OWNERS = (
Mike Klein3f041f82021-02-03 09:36:14 -060025 'brianosman@google.com',
rmistry@google.comfb4a68d2013-08-12 14:51:20 +000026 'bsalomon@google.com',
rmistry83fab472014-07-18 05:25:56 -070027 'djsollen@chromium.org',
28 'djsollen@google.com',
Ravi Mistryfbff3292017-01-19 12:00:08 -050029 'hcm@chromium.org',
30 'hcm@google.com',
Mike Klein3f041f82021-02-03 09:36:14 -060031 'reed@chromium.org',
32 'reed@google.com',
rmistry@google.comfb4a68d2013-08-12 14:51:20 +000033)
34
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +000035AUTHORS_FILE_NAME = 'AUTHORS'
Ravi Mistry57735162019-07-25 13:45:15 -040036RELEASE_NOTES_FILE_NAME = 'RELEASE_NOTES.txt'
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +000037
rmistryd88b0be2016-05-20 03:50:01 -070038GOLD_TRYBOT_URL = 'https://gold.skia.org/search?issue='
rmistryd223fb22015-02-26 10:16:13 -080039
Eric Boren1eec99c2018-04-26 13:09:48 -040040SERVICE_ACCOUNT_SUFFIX = [
Eric Boren47ed6f12018-04-26 14:02:43 -040041 '@%s.iam.gserviceaccount.com' % project for project in [
Eric Boren6ad3ca42018-09-07 14:22:16 -040042 'skia-buildbots.google.com', 'skia-swarming-bots', 'skia-public',
Ravi Mistry53c44232019-03-12 08:51:42 -040043 'skia-corp.google.com', 'chops-service-accounts']]
Eric Borendd988292018-01-02 13:29:21 -050044
rmistry@google.com547012d2013-04-12 19:45:46 +000045
rmistry@google.com713276b2013-01-25 18:27:34 +000046def _CheckChangeHasEol(input_api, output_api, source_file_filter=None):
Edward Lemur2b7876c2020-01-17 18:48:13 -050047 """Checks that files end with at least one \n (LF)."""
rmistry@google.com713276b2013-01-25 18:27:34 +000048 eof_files = []
49 for f in input_api.AffectedSourceFiles(source_file_filter):
50 contents = input_api.ReadFile(f, 'rb')
Edward Lemur2b7876c2020-01-17 18:48:13 -050051 # Check that the file ends in at least one newline character.
rmistry@google.com713276b2013-01-25 18:27:34 +000052 if len(contents) > 1 and contents[-1:] != '\n':
53 eof_files.append(f.LocalPath())
54
55 if eof_files:
56 return [output_api.PresubmitPromptWarning(
57 'These files should end in a newline character:',
58 items=eof_files)]
59 return []
60
61
Ben Wagnercf42e982018-02-09 17:41:20 -050062def _JsonChecks(input_api, output_api):
63 """Run checks on any modified json files."""
64 failing_files = []
65 for affected_file in input_api.AffectedFiles(None):
66 affected_file_path = affected_file.LocalPath()
67 is_json = affected_file_path.endswith('.json')
68 is_metadata = (affected_file_path.startswith('site/') and
69 affected_file_path.endswith('/METADATA'))
70 if is_json or is_metadata:
71 try:
72 input_api.json.load(open(affected_file_path, 'r'))
73 except ValueError:
74 failing_files.append(affected_file_path)
75
76 results = []
77 if failing_files:
78 results.append(
79 output_api.PresubmitError(
80 'The following files contain invalid json:\n%s\n\n' %
81 '\n'.join(failing_files)))
82 return results
83
84
rmistry01cbf6c2015-03-12 07:48:40 -070085def _IfDefChecks(input_api, output_api):
86 """Ensures if/ifdef are not before includes. See skbug/3362 for details."""
87 comment_block_start_pattern = re.compile('^\s*\/\*.*$')
88 comment_block_middle_pattern = re.compile('^\s+\*.*')
89 comment_block_end_pattern = re.compile('^\s+\*\/.*$')
90 single_line_comment_pattern = re.compile('^\s*//.*$')
91 def is_comment(line):
92 return (comment_block_start_pattern.match(line) or
93 comment_block_middle_pattern.match(line) or
94 comment_block_end_pattern.match(line) or
95 single_line_comment_pattern.match(line))
96
97 empty_line_pattern = re.compile('^\s*$')
98 def is_empty_line(line):
99 return empty_line_pattern.match(line)
100
101 failing_files = []
102 for affected_file in input_api.AffectedSourceFiles(None):
103 affected_file_path = affected_file.LocalPath()
104 if affected_file_path.endswith('.cpp') or affected_file_path.endswith('.h'):
105 f = open(affected_file_path)
106 for line in f.xreadlines():
107 if is_comment(line) or is_empty_line(line):
108 continue
109 # The below will be the first real line after comments and newlines.
110 if line.startswith('#if 0 '):
111 pass
112 elif line.startswith('#if ') or line.startswith('#ifdef '):
113 failing_files.append(affected_file_path)
114 break
115
116 results = []
117 if failing_files:
118 results.append(
119 output_api.PresubmitError(
120 'The following files have #if or #ifdef before includes:\n%s\n\n'
halcanary6950de62015-11-07 05:29:00 -0800121 'See https://bug.skia.org/3362 for why this should be fixed.' %
rmistry01cbf6c2015-03-12 07:48:40 -0700122 '\n'.join(failing_files)))
123 return results
124
125
borenetc7c91802015-03-25 04:47:02 -0700126def _CopyrightChecks(input_api, output_api, source_file_filter=None):
127 results = []
128 year_pattern = r'\d{4}'
129 year_range_pattern = r'%s(-%s)?' % (year_pattern, year_pattern)
130 years_pattern = r'%s(,%s)*,?' % (year_range_pattern, year_range_pattern)
131 copyright_pattern = (
132 r'Copyright (\([cC]\) )?%s \w+' % years_pattern)
133
134 for affected_file in input_api.AffectedSourceFiles(source_file_filter):
John Stilesd836f842020-09-14 10:21:44 -0400135 if ('third_party/' in affected_file.LocalPath() or
136 'tests/sksl/' in affected_file.LocalPath()):
borenetc7c91802015-03-25 04:47:02 -0700137 continue
138 contents = input_api.ReadFile(affected_file, 'rb')
139 if not re.search(copyright_pattern, contents):
140 results.append(output_api.PresubmitError(
141 '%s is missing a correct copyright header.' % affected_file))
142 return results
143
144
borenet2dbbfa52016-10-14 06:32:09 -0700145def _InfraTests(input_api, output_api):
146 """Run the infra tests."""
borenet1ed2ae42016-07-26 11:52:17 -0700147 results = []
mtklein3da80f52016-07-27 04:14:07 -0700148 if not any(f.LocalPath().startswith('infra')
149 for f in input_api.AffectedFiles()):
150 return results
151
borenet2dbbfa52016-10-14 06:32:09 -0700152 cmd = ['python', os.path.join('infra', 'bots', 'infra_tests.py')]
borenet60b0a2d2016-10-04 12:45:41 -0700153 try:
154 subprocess.check_output(cmd)
155 except subprocess.CalledProcessError as e:
156 results.append(output_api.PresubmitError(
157 '`%s` failed:\n%s' % (' '.join(cmd), e.output)))
158 return results
159
160
mtklein4db3b792016-08-03 14:18:22 -0700161def _CheckGNFormatted(input_api, output_api):
162 """Make sure any .gn files we're changing have been formatted."""
Ben Wagner3c4a9d32020-02-14 14:28:33 -0500163 files = []
Corentin Wallez6a5187a2020-04-08 10:24:04 +0200164 for f in input_api.AffectedFiles(include_deletes=False):
Ben Wagner3c4a9d32020-02-14 14:28:33 -0500165 if (f.LocalPath().endswith('.gn') or
166 f.LocalPath().endswith('.gni')):
167 files.append(f)
168 if not files:
169 return []
mtklein4db3b792016-08-03 14:18:22 -0700170
Ben Wagner3c4a9d32020-02-14 14:28:33 -0500171 cmd = ['python', os.path.join('bin', 'fetch-gn')]
172 try:
173 subprocess.check_output(cmd)
174 except subprocess.CalledProcessError as e:
175 return [output_api.PresubmitError(
176 '`%s` failed:\n%s' % (' '.join(cmd), e.output))]
177
178 results = []
179 for f in files:
Brian Osman70f24af2020-02-18 15:08:27 -0500180 gn = 'gn.exe' if 'win32' in sys.platform else 'gn'
Ben Wagner06265e02020-02-13 19:02:46 -0500181 gn = os.path.join(input_api.PresubmitLocalPath(), 'bin', gn)
Mike Klein7a1c53d2016-10-11 14:03:06 -0400182 cmd = [gn, 'format', '--dry-run', f.LocalPath()]
mtklein4db3b792016-08-03 14:18:22 -0700183 try:
184 subprocess.check_output(cmd)
185 except subprocess.CalledProcessError:
Ben Wagner06265e02020-02-13 19:02:46 -0500186 fix = 'bin/gn format ' + f.LocalPath()
mtklein4db3b792016-08-03 14:18:22 -0700187 results.append(output_api.PresubmitError(
mtkleind434b012016-08-10 07:30:58 -0700188 '`%s` failed, try\n\t%s' % (' '.join(cmd), fix)))
mtklein4db3b792016-08-03 14:18:22 -0700189 return results
190
Ravi Mistry6eca5792020-12-16 11:42:29 -0500191
192def _CheckGitConflictMarkers(input_api, output_api):
193 pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
194 results = []
195 for f in input_api.AffectedFiles():
196 for line_num, line in f.ChangedContents():
197 if f.LocalPath().endswith('.md'):
198 # First-level headers in markdown look a lot like version control
199 # conflict markers. http://daringfireball.net/projects/markdown/basics
200 continue
201 if pattern.match(line):
202 results.append(
203 output_api.PresubmitError(
204 'Git conflict markers found in %s:%d %s' % (
205 f.LocalPath(), line_num, line)))
206 return results
207
208
Mike Kleinbb413432019-07-26 11:55:40 -0500209def _CheckIncludesFormatted(input_api, output_api):
210 """Make sure #includes in files we're changing have been formatted."""
Mike Kleinf9ad5ba2019-07-29 12:34:39 -0500211 files = [str(f) for f in input_api.AffectedFiles() if f.Action() != 'D']
Mike Kleinbb413432019-07-26 11:55:40 -0500212 cmd = ['python',
213 'tools/rewrite_includes.py',
Mike Kleinf9ad5ba2019-07-29 12:34:39 -0500214 '--dry-run'] + files
Hal Canary4df3d532019-07-30 13:49:45 -0400215 if 0 != subprocess.call(cmd):
Mike Kleinbb413432019-07-26 11:55:40 -0500216 return [output_api.PresubmitError('`%s` failed' % ' '.join(cmd))]
217 return []
borenet1ed2ae42016-07-26 11:52:17 -0700218
Eric Boren58d1f762019-07-19 08:07:44 -0400219
Ben Wagner88855502017-10-12 17:55:19 -0400220class _WarningsAsErrors():
221 def __init__(self, output_api):
222 self.output_api = output_api
223 self.old_warning = None
224 def __enter__(self):
225 self.old_warning = self.output_api.PresubmitPromptWarning
226 self.output_api.PresubmitPromptWarning = self.output_api.PresubmitError
227 return self.output_api
228 def __exit__(self, ex_type, ex_value, ex_traceback):
229 self.output_api.PresubmitPromptWarning = self.old_warning
230
231
Eric Boren6dc00212019-07-24 15:15:43 -0400232def _CheckDEPSValid(input_api, output_api):
233 """Ensure that DEPS contains valid entries."""
234 results = []
235 script = os.path.join('infra', 'bots', 'check_deps.py')
236 relevant_files = ('DEPS', script)
237 for f in input_api.AffectedFiles():
238 if f.LocalPath() in relevant_files:
239 break
240 else:
241 return results
242 cmd = ['python', script]
243 try:
244 subprocess.check_output(cmd, stderr=subprocess.STDOUT)
245 except subprocess.CalledProcessError as e:
246 results.append(output_api.PresubmitError(e.output))
247 return results
248
249
Kevin Lubick2cd80672021-07-01 11:03:36 -0400250def _RegenerateAllExamplesCPP(input_api, output_api):
251 """Regenerates all_examples.cpp if an example was added or deleted."""
252 if not any(f.LocalPath().startswith('docs/examples/')
253 for f in input_api.AffectedFiles()):
254 return []
255 command_str = 'tools/fiddle/make_all_examples_cpp.py'
256 cmd = ['python', command_str]
257 if 0 != subprocess.call(cmd):
258 return [output_api.PresubmitError('`%s` failed' % ' '.join(cmd))]
259
260 results = []
261 git_diff_output = input_api.subprocess.check_output(
262 ['git', 'diff', '--no-ext-diff'])
263 if git_diff_output:
264 results += [output_api.PresubmitError(
265 'Diffs found after running "%s":\n\n%s\n'
266 'Please commit or discard the above changes.' % (
267 command_str,
268 git_diff_output,
269 )
270 )]
271 return results
272
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000273def _CommonChecks(input_api, output_api):
274 """Presubmit checks common to upload and commit."""
275 results = []
276 sources = lambda x: (x.LocalPath().endswith('.h') or
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000277 x.LocalPath().endswith('.py') or
278 x.LocalPath().endswith('.sh') or
mtklein18e55802015-03-25 07:21:20 -0700279 x.LocalPath().endswith('.m') or
280 x.LocalPath().endswith('.mm') or
281 x.LocalPath().endswith('.go') or
282 x.LocalPath().endswith('.c') or
283 x.LocalPath().endswith('.cc') or
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000284 x.LocalPath().endswith('.cpp'))
Ben Wagner88855502017-10-12 17:55:19 -0400285 results.extend(_CheckChangeHasEol(
286 input_api, output_api, source_file_filter=sources))
287 with _WarningsAsErrors(output_api):
288 results.extend(input_api.canned_checks.CheckChangeHasNoCR(
289 input_api, output_api, source_file_filter=sources))
290 results.extend(input_api.canned_checks.CheckChangeHasNoStrayWhitespace(
291 input_api, output_api, source_file_filter=sources))
Ben Wagnercf42e982018-02-09 17:41:20 -0500292 results.extend(_JsonChecks(input_api, output_api))
rmistry01cbf6c2015-03-12 07:48:40 -0700293 results.extend(_IfDefChecks(input_api, output_api))
borenetc7c91802015-03-25 04:47:02 -0700294 results.extend(_CopyrightChecks(input_api, output_api,
295 source_file_filter=sources))
Eric Boren6dc00212019-07-24 15:15:43 -0400296 results.extend(_CheckDEPSValid(input_api, output_api))
Mike Kleinbb413432019-07-26 11:55:40 -0500297 results.extend(_CheckIncludesFormatted(input_api, output_api))
Mike Klein96f64012020-04-03 10:59:37 -0500298 results.extend(_CheckGNFormatted(input_api, output_api))
Ravi Mistry6eca5792020-12-16 11:42:29 -0500299 results.extend(_CheckGitConflictMarkers(input_api, output_api))
Kevin Lubick2cd80672021-07-01 11:03:36 -0400300 results.extend(_RegenerateAllExamplesCPP(input_api, output_api))
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000301 return results
302
rmistry@google.com8e3ff8c2013-01-17 12:55:34 +0000303
304def CheckChangeOnUpload(input_api, output_api):
Ravi Mistry4c0ffe72020-03-02 13:19:02 -0500305 """Presubmit checks for the change on upload."""
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000306 results = []
307 results.extend(_CommonChecks(input_api, output_api))
borenet1ed2ae42016-07-26 11:52:17 -0700308 # Run on upload, not commit, since the presubmit bot apparently doesn't have
borenet60b0a2d2016-10-04 12:45:41 -0700309 # coverage or Go installed.
borenet2dbbfa52016-10-14 06:32:09 -0700310 results.extend(_InfraTests(input_api, output_api))
Ravi Mistry57735162019-07-25 13:45:15 -0400311 results.extend(_CheckReleaseNotesForPublicAPI(input_api, output_api))
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000312 return results
rmistry@google.com8e3ff8c2013-01-17 12:55:34 +0000313
314
rmistryb398ecc2016-08-29 08:13:29 -0700315class CodeReview(object):
316 """Abstracts which codereview tool is used for the specified issue."""
317
318 def __init__(self, input_api):
319 self._issue = input_api.change.issue
320 self._gerrit = input_api.gerrit
rmistryb398ecc2016-08-29 08:13:29 -0700321
322 def GetOwnerEmail(self):
Aaron Gablea49909a2017-10-09 12:50:52 -0700323 return self._gerrit.GetChangeOwner(self._issue)
rmistryb398ecc2016-08-29 08:13:29 -0700324
325 def GetSubject(self):
Aaron Gablea49909a2017-10-09 12:50:52 -0700326 return self._gerrit.GetChangeInfo(self._issue)['subject']
rmistryb398ecc2016-08-29 08:13:29 -0700327
328 def GetDescription(self):
Aaron Gablea49909a2017-10-09 12:50:52 -0700329 return self._gerrit.GetChangeDescription(self._issue)
rmistryb398ecc2016-08-29 08:13:29 -0700330
Ravi Mistry39eabb62016-10-05 08:41:12 -0400331 def GetReviewers(self):
Aaron Gablea49909a2017-10-09 12:50:52 -0700332 code_review_label = (
333 self._gerrit.GetChangeInfo(self._issue)['labels']['Code-Review'])
334 return [r['email'] for r in code_review_label.get('all', [])]
Ravi Mistry39eabb62016-10-05 08:41:12 -0400335
rmistryb398ecc2016-08-29 08:13:29 -0700336 def GetApprovers(self):
337 approvers = []
Aaron Gablea49909a2017-10-09 12:50:52 -0700338 code_review_label = (
339 self._gerrit.GetChangeInfo(self._issue)['labels']['Code-Review'])
340 for m in code_review_label.get('all', []):
341 if m.get("value") == 1:
342 approvers.append(m["email"])
rmistryb398ecc2016-08-29 08:13:29 -0700343 return approvers
344
345
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +0000346def _CheckOwnerIsInAuthorsFile(input_api, output_api):
347 results = []
rmistryb398ecc2016-08-29 08:13:29 -0700348 if input_api.change.issue:
349 cr = CodeReview(input_api)
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +0000350
rmistryb398ecc2016-08-29 08:13:29 -0700351 owner_email = cr.GetOwnerEmail()
Eric Borendd988292018-01-02 13:29:21 -0500352
353 # Service accounts don't need to be in AUTHORS.
Eric Boren1eec99c2018-04-26 13:09:48 -0400354 for suffix in SERVICE_ACCOUNT_SUFFIX:
355 if owner_email.endswith(suffix):
356 return results
Eric Borendd988292018-01-02 13:29:21 -0500357
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +0000358 try:
359 authors_content = ''
360 for line in open(AUTHORS_FILE_NAME):
361 if not line.startswith('#'):
362 authors_content += line
363 email_fnmatches = re.findall('<(.*)>', authors_content)
364 for email_fnmatch in email_fnmatches:
365 if fnmatch.fnmatch(owner_email, email_fnmatch):
366 # Found a match, the user is in the AUTHORS file break out of the loop
367 break
368 else:
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +0000369 results.append(
370 output_api.PresubmitError(
371 'The email %s is not in Skia\'s AUTHORS file.\n'
372 'Issue owner, this CL must include an addition to the Skia AUTHORS '
rmistry9806d4d2015-10-01 08:10:54 -0700373 'file.'
rmistry83fab472014-07-18 05:25:56 -0700374 % owner_email))
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +0000375 except IOError:
376 # Do not fail if authors file cannot be found.
377 traceback.print_exc()
378 input_api.logging.error('AUTHORS file not found!')
379
380 return results
381
382
Ravi Mistry57735162019-07-25 13:45:15 -0400383def _CheckReleaseNotesForPublicAPI(input_api, output_api):
384 """Checks to see if release notes file is updated with public API changes."""
385 results = []
386 public_api_changed = False
387 release_file_changed = False
388 for affected_file in input_api.AffectedFiles():
389 affected_file_path = affected_file.LocalPath()
390 file_path, file_ext = os.path.splitext(affected_file_path)
391 # We only care about files that end in .h and are under the top-level
392 # include dir, but not include/private.
393 if (file_ext == '.h' and
394 file_path.split(os.path.sep)[0] == 'include' and
395 'private' not in file_path):
396 public_api_changed = True
397 elif affected_file_path == RELEASE_NOTES_FILE_NAME:
398 release_file_changed = True
399
400 if public_api_changed and not release_file_changed:
401 results.append(output_api.PresubmitPromptWarning(
402 'If this change affects a client API, please add a summary line '
403 'to the %s file.' % RELEASE_NOTES_FILE_NAME))
404 return results
405
406
407
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000408def _CheckLGTMsForPublicAPI(input_api, output_api):
409 """Check LGTMs for public API changes.
410
411 For public API files make sure there is an LGTM from the list of owners in
412 PUBLIC_API_OWNERS.
413 """
414 results = []
415 requires_owner_check = False
rmistry9407ece2014-08-26 14:00:54 -0700416 for affected_file in input_api.AffectedFiles():
417 affected_file_path = affected_file.LocalPath()
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000418 file_path, file_ext = os.path.splitext(affected_file_path)
rmistry9407ece2014-08-26 14:00:54 -0700419 # We only care about files that end in .h and are under the top-level
mtkleinbda12672015-07-28 08:54:12 -0700420 # include dir, but not include/private.
421 if (file_ext == '.h' and
422 'include' == file_path.split(os.path.sep)[0] and
423 'private' not in file_path):
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000424 requires_owner_check = True
425
426 if not requires_owner_check:
427 return results
428
429 lgtm_from_owner = False
rmistryb398ecc2016-08-29 08:13:29 -0700430 if input_api.change.issue:
431 cr = CodeReview(input_api)
432
433 if re.match(REVERT_CL_SUBJECT_PREFIX, cr.GetSubject(), re.I):
commit-bot@chromium.orgcfdc5962014-01-31 17:33:04 +0000434 # It is a revert CL, ignore the public api owners check.
435 return results
rmistryf2d83ca2014-08-26 10:30:29 -0700436
Ravi Mistry39eabb62016-10-05 08:41:12 -0400437 if input_api.gerrit:
438 for reviewer in cr.GetReviewers():
439 if reviewer in PUBLIC_API_OWNERS:
440 # If an owner is specified as an reviewer in Gerrit then ignore the
441 # public api owners check.
rmistryf2d83ca2014-08-26 10:30:29 -0700442 return results
Ravi Mistry39eabb62016-10-05 08:41:12 -0400443 else:
444 match = re.search(r'^TBR=(.*)$', cr.GetDescription(), re.M)
445 if match:
446 tbr_section = match.group(1).strip().split(' ')[0]
447 tbr_entries = tbr_section.split(',')
448 for owner in PUBLIC_API_OWNERS:
449 if owner in tbr_entries or owner.split('@')[0] in tbr_entries:
450 # If an owner is specified in the TBR= line then ignore the public
451 # api owners check.
452 return results
rmistryf2d83ca2014-08-26 10:30:29 -0700453
rmistryb398ecc2016-08-29 08:13:29 -0700454 if cr.GetOwnerEmail() in PUBLIC_API_OWNERS:
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000455 # An owner created the CL that is an automatic LGTM.
456 lgtm_from_owner = True
457
rmistryb398ecc2016-08-29 08:13:29 -0700458 for approver in cr.GetApprovers():
459 if approver in PUBLIC_API_OWNERS:
460 # Found an lgtm in a message from an owner.
461 lgtm_from_owner = True
462 break
commit-bot@chromium.orgcfdc5962014-01-31 17:33:04 +0000463
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000464 if not lgtm_from_owner:
465 results.append(
466 output_api.PresubmitError(
mtkleinbda12672015-07-28 08:54:12 -0700467 "If this CL adds to or changes Skia's public API, you need an LGTM "
468 "from any of %s. If this CL only removes from or doesn't change "
Ravi Mistrydbb84c22016-10-05 12:47:44 -0400469 "Skia's public API, please add a short note to the CL saying so. "
Aaron Gablea49909a2017-10-09 12:50:52 -0700470 "Add one of the owners as a reviewer to your CL as well as to the "
471 "TBR= line. If you don't know if this CL affects Skia's public "
472 "API, treat it like it does." % str(PUBLIC_API_OWNERS)))
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000473 return results
474
475
Edward Lemur2b7876c2020-01-17 18:48:13 -0500476def PostUploadHook(gerrit, change, output_api):
rmistryd223fb22015-02-26 10:16:13 -0800477 """git cl upload will call this hook after the issue is created/modified.
478
479 This hook does the following:
480 * Adds a link to preview docs changes if there are any docs changes in the CL.
Ravi Mistry355feab2017-05-23 14:24:08 -0400481 * Adds 'No-Try: true' if the CL contains only docs changes.
rmistryd223fb22015-02-26 10:16:13 -0800482 """
Edward Lemur2b7876c2020-01-17 18:48:13 -0500483 if not change.issue:
484 return []
485
486 # Skip PostUploadHooks for all auto-commit service account bots. New
487 # patchsets (caused due to PostUploadHooks) invalidates the CQ+2 vote from
488 # the "--use-commit-queue" flag to "git cl upload".
489 for suffix in SERVICE_ACCOUNT_SUFFIX:
490 if change.author_email.endswith(suffix):
491 return []
rmistryd223fb22015-02-26 10:16:13 -0800492
493 results = []
Ravi Mistry27095f22021-04-22 12:51:49 +0000494 at_least_one_docs_change = False
rmistryd223fb22015-02-26 10:16:13 -0800495 all_docs_changes = True
496 for affected_file in change.AffectedFiles():
497 affected_file_path = affected_file.LocalPath()
498 file_path, _ = os.path.splitext(affected_file_path)
Ravi Mistry27095f22021-04-22 12:51:49 +0000499 if 'site' == file_path.split(os.path.sep)[0]:
500 at_least_one_docs_change = True
rmistryd223fb22015-02-26 10:16:13 -0800501 else:
502 all_docs_changes = False
Ravi Mistry27095f22021-04-22 12:51:49 +0000503 if at_least_one_docs_change and not all_docs_changes:
504 break
rmistryd223fb22015-02-26 10:16:13 -0800505
Edward Lemur2b7876c2020-01-17 18:48:13 -0500506 footers = change.GitFootersFromDescription()
507 description_changed = False
Ravi Mistryb5e2acc2017-12-07 11:10:11 -0500508
Edward Lemur2b7876c2020-01-17 18:48:13 -0500509 # If the change includes only doc changes then add No-Try: true in the
510 # CL's description if it does not exist yet.
511 if all_docs_changes and 'true' not in footers.get('No-Try', []):
512 description_changed = True
Edward Lemurc631b7c2020-02-04 15:30:18 -0500513 change.AddDescriptionFooter('No-Try', 'true')
Edward Lemur2b7876c2020-01-17 18:48:13 -0500514 results.append(
515 output_api.PresubmitNotifyResult(
516 'This change has only doc changes. Automatically added '
517 '\'No-Try: true\' to the CL\'s description'))
rmistryd223fb22015-02-26 10:16:13 -0800518
Edward Lemur2b7876c2020-01-17 18:48:13 -0500519 # If the description has changed update it.
520 if description_changed:
521 gerrit.UpdateDescription(
522 change.FullDescriptionText(), change.issue)
rmistryd223fb22015-02-26 10:16:13 -0800523
Edward Lemur2b7876c2020-01-17 18:48:13 -0500524 return results
rmistryd223fb22015-02-26 10:16:13 -0800525
526
rmistry@google.com8e3ff8c2013-01-17 12:55:34 +0000527def CheckChangeOnCommit(input_api, output_api):
Ravi Mistry4c0ffe72020-03-02 13:19:02 -0500528 """Presubmit checks for the change on commit."""
rmistry@google.com8e3ff8c2013-01-17 12:55:34 +0000529 results = []
rmistry@google.com6be0b4c2013-01-17 14:50:59 +0000530 results.extend(_CommonChecks(input_api, output_api))
rmistry@google.comfb4a68d2013-08-12 14:51:20 +0000531 results.extend(_CheckLGTMsForPublicAPI(input_api, output_api))
commit-bot@chromium.org745e08c2014-02-03 14:18:32 +0000532 results.extend(_CheckOwnerIsInAuthorsFile(input_api, output_api))
Ravi Mistrya70cb8a2017-09-12 13:52:05 -0400533 # Checks for the presence of 'DO NOT''SUBMIT' in CL description and in
534 # content of files.
535 results.extend(
536 input_api.canned_checks.CheckDoNotSubmit(input_api, output_api))
rmistry@google.com8e3ff8c2013-01-17 12:55:34 +0000537 return results