| 1 |
#!/usr/bin/env python3 |
| 2 |
# 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 |
|
| 9 |
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts |
| 10 |
for more details about the presubmit API built into gcl. |
| 11 |
""" |
| 12 |
|
| 13 |
import difflib |
| 14 |
import os |
| 15 |
import re |
| 16 |
import subprocess |
| 17 |
import sys |
| 18 |
|
| 19 |
|
| 20 |
RELEASE_NOTES_DIR = 'relnotes' |
| 21 |
RELEASE_NOTES_FILE_NAME = 'RELEASE_NOTES.md' |
| 22 |
RELEASE_NOTES_README = '//relnotes/README.md' |
| 23 |
|
| 24 |
GOLD_TRYBOT_URL = 'https://gold.skia.org/search?issue=' |
| 25 |
|
| 26 |
SERVICE_ACCOUNT_SUFFIX = [ |
| 27 |
'@%s.iam.gserviceaccount.com' % project for project in [ |
| 28 |
'skia-buildbots.google.com', 'skia-swarming-bots', 'skia-public', |
| 29 |
'skia-corp.google.com', 'chops-service-accounts']] |
| 30 |
|
| 31 |
USE_PYTHON3 = True |
| 32 |
|
| 33 |
def np(path): |
| 34 |
"""normalize path |
| 35 |
This takes in a os-dependent path and returns it using forward slashes only. |
| 36 |
""" |
| 37 |
return os.path.normpath(path).replace(os.sep, '/') |
| 38 |
|
| 39 |
def _CheckChangeHasEol(input_api, output_api, source_file_filter=None): |
| 40 |
"""Checks that files end with at least one \n (LF).""" |
| 41 |
eof_files = [] |
| 42 |
for f in input_api.AffectedSourceFiles(source_file_filter): |
| 43 |
contents = input_api.ReadFile(f, 'rb') |
| 44 |
# Check that the file ends in at least one newline character. |
| 45 |
if len(contents) > 1 and contents[-1:] != '\n': |
| 46 |
eof_files.append(f.LocalPath()) |
| 47 |
|
| 48 |
if eof_files: |
| 49 |
return [output_api.PresubmitPromptWarning( |
| 50 |
'These files should end in a newline character:', |
| 51 |
items=eof_files)] |
| 52 |
return [] |
| 53 |
|
| 54 |
|
| 55 |
def _JsonChecks(input_api, output_api): |
| 56 |
"""Run checks on any modified json files.""" |
| 57 |
failing_files = [] |
| 58 |
for affected_file in input_api.AffectedFiles(None): |
| 59 |
affected_file_path = affected_file.LocalPath() |
| 60 |
is_json = affected_file_path.endswith('.json') |
| 61 |
is_metadata = (np(affected_file_path).startswith('site/') and |
| 62 |
np(affected_file_path).endswith('/METADATA')) |
| 63 |
if is_json or is_metadata: |
| 64 |
try: |
| 65 |
input_api.json.load(open(affected_file_path, 'r')) |
| 66 |
except ValueError as ve: |
| 67 |
failing_files.append(f'{affected_file_path}\t\t{ve}') |
| 68 |
|
| 69 |
results = [] |
| 70 |
if failing_files: |
| 71 |
results.append( |
| 72 |
output_api.PresubmitError( |
| 73 |
'The following files contain invalid json:\n%s\n' % |
| 74 |
'\n'.join(failing_files))) |
| 75 |
return results |
| 76 |
|
| 77 |
|
| 78 |
def _IfDefChecks(input_api, output_api): |
| 79 |
"""Ensures if/ifdef are not before includes. See skbug/3362 for details.""" |
| 80 |
comment_block_start_pattern = re.compile('^\s*\/\*.*$') |
| 81 |
comment_block_middle_pattern = re.compile('^\s+\*.*') |
| 82 |
comment_block_end_pattern = re.compile('^\s+\*\/.*$') |
| 83 |
single_line_comment_pattern = re.compile('^\s*//.*$') |
| 84 |
def is_comment(line): |
| 85 |
return (comment_block_start_pattern.match(line) or |
| 86 |
comment_block_middle_pattern.match(line) or |
| 87 |
comment_block_end_pattern.match(line) or |
| 88 |
single_line_comment_pattern.match(line)) |
| 89 |
|
| 90 |
empty_line_pattern = re.compile('^\s*$') |
| 91 |
def is_empty_line(line): |
| 92 |
return empty_line_pattern.match(line) |
| 93 |
|
| 94 |
failing_files = [] |
| 95 |
for affected_file in input_api.AffectedSourceFiles(None): |
| 96 |
affected_file_path = affected_file.LocalPath() |
| 97 |
if affected_file_path.endswith('.cpp') or affected_file_path.endswith('.h'): |
| 98 |
f = open(affected_file_path) |
| 99 |
for line in f: |
| 100 |
if is_comment(line) or is_empty_line(line): |
| 101 |
continue |
| 102 |
# The below will be the first real line after comments and newlines. |
| 103 |
if line.startswith('#if 0 '): |
| 104 |
pass |
| 105 |
elif line.startswith('#if ') or line.startswith('#ifdef '): |
| 106 |
failing_files.append(affected_file_path) |
| 107 |
break |
| 108 |
|
| 109 |
results = [] |
| 110 |
if failing_files: |
| 111 |
results.append( |
| 112 |
output_api.PresubmitError( |
| 113 |
'The following files have #if or #ifdef before includes:\n%s\n\n' |
| 114 |
'See skbug.com/40034487 for why this should be fixed.' % |
| 115 |
'\n'.join(failing_files))) |
| 116 |
return results |
| 117 |
|
| 118 |
|
| 119 |
def _CopyrightChecks(input_api, output_api, source_file_filter=None): |
| 120 |
results = [] |
| 121 |
year_pattern = r'\d{4}' |
| 122 |
year_range_pattern = r'%s(-%s)?' % (year_pattern, year_pattern) |
| 123 |
years_pattern = r'%s(,%s)*,?' % (year_range_pattern, year_range_pattern) |
| 124 |
copyright_pattern = ( |
| 125 |
r'Copyright (\([cC]\) )?%s \w+' % years_pattern) |
| 126 |
|
| 127 |
for affected_file in input_api.AffectedSourceFiles(source_file_filter): |
| 128 |
norm_path = np(affected_file.LocalPath()) |
| 129 |
if ('third_party/' in norm_path or |
| 130 |
'tests/sksl/' in norm_path or |
| 131 |
'bazel/rbe/' in norm_path or |
| 132 |
'bazel/external/' in norm_path or |
| 133 |
'bazel/exporter/interfaces/mocks/' in norm_path or |
| 134 |
norm_path.endswith('gen.go')): |
| 135 |
continue |
| 136 |
contents = input_api.ReadFile(affected_file, 'rb') |
| 137 |
if not re.search(copyright_pattern, contents): |
| 138 |
results.append(output_api.PresubmitError( |
| 139 |
'%s is missing a correct copyright header.' % affected_file)) |
| 140 |
return results |
| 141 |
|
| 142 |
|
| 143 |
def _InfraTests(input_api, output_api): |
| 144 |
"""Run the infra tests.""" |
| 145 |
results = [] |
| 146 |
if not any(f.LocalPath().startswith('infra') |
| 147 |
for f in input_api.AffectedFiles()): |
| 148 |
return results |
| 149 |
|
| 150 |
cmd = ['python3', os.path.join('infra', 'bots', 'infra_tests.py')] |
| 151 |
try: |
| 152 |
subprocess.check_output(cmd) |
| 153 |
except subprocess.CalledProcessError as e: |
| 154 |
results.append(output_api.PresubmitError( |
| 155 |
'`%s` failed:\n%s' % (' '.join(cmd), e.output))) |
| 156 |
return results |
| 157 |
|
| 158 |
|
| 159 |
def _CheckGNFormatted(input_api, output_api): |
| 160 |
"""Make sure any .gn files we're changing have been formatted.""" |
| 161 |
files = [] |
| 162 |
for f in input_api.AffectedFiles(include_deletes=False): |
| 163 |
if (f.LocalPath().endswith('.gn') or |
| 164 |
f.LocalPath().endswith('.gni')): |
| 165 |
files.append(f) |
| 166 |
if not files: |
| 167 |
return [] |
| 168 |
|
| 169 |
cmd = ['python3', os.path.join('bin', 'fetch-gn')] |
| 170 |
try: |
| 171 |
subprocess.check_output(cmd) |
| 172 |
except subprocess.CalledProcessError as e: |
| 173 |
return [output_api.PresubmitError( |
| 174 |
'`%s` failed:\n%s' % (' '.join(cmd), e.output))] |
| 175 |
|
| 176 |
results = [] |
| 177 |
for f in files: |
| 178 |
gn = 'gn.exe' if 'win32' in sys.platform else 'gn' |
| 179 |
gn = os.path.join(input_api.PresubmitLocalPath(), 'bin', gn) |
| 180 |
cmd = [gn, 'format', '--dry-run', f.LocalPath()] |
| 181 |
try: |
| 182 |
subprocess.check_output(cmd) |
| 183 |
except subprocess.CalledProcessError: |
| 184 |
fix = 'bin/gn format ' + f.LocalPath() |
| 185 |
results.append(output_api.PresubmitError( |
| 186 |
'`%s` failed, try\n\t%s' % (' '.join(cmd), fix))) |
| 187 |
return results |
| 188 |
|
| 189 |
|
| 190 |
def _CheckGitConflictMarkers(input_api, output_api): |
| 191 |
pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$') |
| 192 |
results = [] |
| 193 |
for f in input_api.AffectedFiles(): |
| 194 |
for line_num, line in f.ChangedContents(): |
| 195 |
if f.LocalPath().endswith('.md'): |
| 196 |
# First-level headers in markdown look a lot like version control |
| 197 |
# conflict markers. http://daringfireball.net/projects/markdown/basics |
| 198 |
continue |
| 199 |
if pattern.match(line): |
| 200 |
results.append( |
| 201 |
output_api.PresubmitError( |
| 202 |
'Git conflict markers found in %s:%d %s' % ( |
| 203 |
f.LocalPath(), line_num, line))) |
| 204 |
return results |
| 205 |
|
| 206 |
|
| 207 |
def _CheckIncludesFormatted(input_api, output_api): |
| 208 |
"""Make sure #includes in files we're changing have been formatted.""" |
| 209 |
files = [str(f) for f in input_api.AffectedFiles() if f.Action() != 'D'] |
| 210 |
cmd = ['python3', |
| 211 |
'tools/rewrite_includes.py', |
| 212 |
'--dry-run'] + files |
| 213 |
if 0 != subprocess.call(cmd): |
| 214 |
return [output_api.PresubmitError('`%s` failed' % ' '.join(cmd))] |
| 215 |
return [] |
| 216 |
|
| 217 |
|
| 218 |
class _WarningsAsErrors(): |
| 219 |
def __init__(self, output_api): |
| 220 |
self.output_api = output_api |
| 221 |
self.old_warning = None |
| 222 |
def __enter__(self): |
| 223 |
self.old_warning = self.output_api.PresubmitPromptWarning |
| 224 |
self.output_api.PresubmitPromptWarning = self.output_api.PresubmitError |
| 225 |
return self.output_api |
| 226 |
def __exit__(self, ex_type, ex_value, ex_traceback): |
| 227 |
self.output_api.PresubmitPromptWarning = self.old_warning |
| 228 |
|
| 229 |
|
| 230 |
def _RegenerateAllExamplesCPP(input_api, output_api): |
| 231 |
"""Regenerates all_examples.cpp if an example was added or deleted.""" |
| 232 |
if not any(np(f.LocalPath()).startswith('docs/examples/') |
| 233 |
for f in input_api.AffectedFiles()): |
| 234 |
return [] |
| 235 |
command_str = os.path.join('tools', 'fiddle', 'make_all_examples_cpp.py') |
| 236 |
cmd = ['python3', command_str, '--print-diff'] |
| 237 |
proc = subprocess.run(cmd, capture_output=True) |
| 238 |
if proc.returncode != 0: |
| 239 |
return [output_api.PresubmitError('`%s` failed' % ' '.join(cmd))] |
| 240 |
|
| 241 |
results = [] |
| 242 |
diff_output = proc.stdout.decode('utf-8').strip() |
| 243 |
if diff_output: |
| 244 |
results += [output_api.PresubmitError( |
| 245 |
'Diffs found after running "%s":\n\n%s\n' |
| 246 |
'Please commit or discard the above changes.' % ( |
| 247 |
command_str, |
| 248 |
diff_output, |
| 249 |
) |
| 250 |
)] |
| 251 |
return results |
| 252 |
|
| 253 |
|
| 254 |
def _CheckIncludeForOutsideDeps(input_api, output_api): |
| 255 |
"""The include directory should consist of only public APIs. |
| 256 |
|
| 257 |
This check makes sure we don't have anything in the include directory |
| 258 |
depend on outside folders. If we had include/core/SkDonut.h depend on |
| 259 |
src/core/SkPastry.h, then clients would have transitive access to the |
| 260 |
private SkPastry class and any symbols in there, even if they don't |
| 261 |
directly include src/core/SkPastry.h (which can be detected/blocked |
| 262 |
with build systems like GN or Bazel). By keeping include/ self-contained, |
| 263 |
we keep a tighter grip on our public API and make Skia easier to distribute |
| 264 |
(one can ship a .a/.so and a single directory of .h files). |
| 265 |
""" |
| 266 |
banned_includes = [ |
| 267 |
input_api.re.compile(r'#\s*include\s+("src/.*)'), |
| 268 |
input_api.re.compile(r'#\s*include\s+("tools/.*)'), |
| 269 |
] |
| 270 |
file_filter = lambda x: (np(x.LocalPath()).startswith('include/')) |
| 271 |
errors = [] |
| 272 |
for affected_file in input_api.AffectedSourceFiles(file_filter): |
| 273 |
affected_filepath = affected_file.LocalPath() |
| 274 |
for (line_num, line) in affected_file.ChangedContents(): |
| 275 |
for re in banned_includes: |
| 276 |
match = re.search(line) |
| 277 |
if match: |
| 278 |
errors.append(('%s:%s: include/* should only depend on other things in include/*. ' + |
| 279 |
'Please remove #include of %s, perhaps making it a forward-declare.') % ( |
| 280 |
affected_filepath, line_num, match.group(1))) |
| 281 |
|
| 282 |
if errors: |
| 283 |
return [output_api.PresubmitError('\n'.join(errors))] |
| 284 |
return [] |
| 285 |
|
| 286 |
|
| 287 |
def _CheckExamplesForPrivateAPIs(input_api, output_api): |
| 288 |
"""We only want our checked-in examples (aka fiddles) to show public API.""" |
| 289 |
banned_includes = [ |
| 290 |
input_api.re.compile(r'#\s*include\s+("src/.*)'), |
| 291 |
input_api.re.compile(r'#\s*include\s+("include/private/.*)'), |
| 292 |
] |
| 293 |
file_filter = lambda x: (np(x.LocalPath()).startswith('docs/examples/')) |
| 294 |
errors = [] |
| 295 |
for affected_file in input_api.AffectedSourceFiles(file_filter): |
| 296 |
affected_filepath = affected_file.LocalPath() |
| 297 |
for (line_num, line) in affected_file.ChangedContents(): |
| 298 |
for re in banned_includes: |
| 299 |
match = re.search(line) |
| 300 |
if match: |
| 301 |
errors.append('%s:%s: Fiddles should not use private/internal API like %s.' % ( |
| 302 |
affected_filepath, line_num, match.group(1))) |
| 303 |
|
| 304 |
if errors: |
| 305 |
return [output_api.PresubmitError('\n'.join(errors))] |
| 306 |
return [] |
| 307 |
|
| 308 |
|
| 309 |
def _CheckGeneratedBazelBUILDFiles(input_api, output_api): |
| 310 |
if 'win32' in sys.platform: |
| 311 |
# TODO(skbug.com/40043154): Remove when Bazel builds work on Windows. |
| 312 |
# Note: `make` is not installed on Windows by default. |
| 313 |
return [] |
| 314 |
if 'darwin' in sys.platform: |
| 315 |
# This takes too long on Mac with default settings. Probably due to sandboxing. |
| 316 |
return [] |
| 317 |
files = [] |
| 318 |
for affected_file in input_api.AffectedFiles(include_deletes=True): |
| 319 |
affected_file_path = affected_file.LocalPath() |
| 320 |
if (affected_file_path.endswith('.go') or |
| 321 |
affected_file_path.endswith('BUILD.bazel')): |
| 322 |
files.append(affected_file) |
| 323 |
if not files: |
| 324 |
return [] |
| 325 |
return _RunCommandAndCheckDiff( |
| 326 |
output_api, ['make', '-C', 'bazel', 'generate_go'], files |
| 327 |
) |
| 328 |
|
| 329 |
|
| 330 |
def _CheckBazelBUILDFiles(input_api, output_api): |
| 331 |
"""Makes sure our BUILD.bazel files are compatible with G3.""" |
| 332 |
results = [] |
| 333 |
for affected_file in input_api.AffectedFiles(include_deletes=False): |
| 334 |
affected_file_path = affected_file.LocalPath() |
| 335 |
is_bazel = affected_file_path.endswith('BUILD.bazel') |
| 336 |
# This list lines up with the one in autoroller_lib.py (see G3). |
| 337 |
excluded_paths = ["infra/", "bazel/rbe/", "bazel/external/", "bazel/common_config_settings/", |
| 338 |
"modules/canvaskit/go/", "experimental/", "bazel/platform", "third_party/", |
| 339 |
"tests/", "resources/", "bazel/deps_parser/", "bazel/exporter_tool/", |
| 340 |
"tools/ganesh/gl/interface/", "bazel/utils/", "include/config/", |
| 341 |
"bench/", "example/external_client/"] |
| 342 |
is_excluded = any(affected_file_path.startswith(os.path.normpath(n)) for n in excluded_paths) |
| 343 |
if is_bazel and not is_excluded: |
| 344 |
with open(affected_file_path, 'r') as file: |
| 345 |
contents = file.read() |
| 346 |
if 'licenses(["notice"])' not in contents: |
| 347 |
results.append(output_api.PresubmitError( |
| 348 |
('%s needs to have\nlicenses(["notice"])\nimmediately after ' + |
| 349 |
'the load() calls to comply with G3 policies.') % affected_file_path |
| 350 |
)) |
| 351 |
if 'cc_library(' in contents and '"skia_cc_library"' not in contents: |
| 352 |
results.append(output_api.PresubmitError( |
| 353 |
('%s needs to load skia_cc_library from skia_rules.bzl instead of using the ' + |
| 354 |
'native one. This allows us to build differently for G3.\n' + |
| 355 |
'Add "skia_cc_library" to load("//bazel:skia_rules.bzl", ...)') |
| 356 |
% affected_file_path |
| 357 |
)) |
| 358 |
if 'default_applicable_licenses' not in contents: |
| 359 |
# See https://opensource.google/documentation/reference/thirdparty/new_license_rules |
| 360 |
results.append(output_api.PresubmitError( |
| 361 |
('%s needs to have\npackage(default_applicable_licenses = ["//:license"])\n'+ |
| 362 |
'to comply with G3 policies') % affected_file_path |
| 363 |
)) |
| 364 |
return results |
| 365 |
|
| 366 |
|
| 367 |
def _RunCommandAndCheckDiff(output_api, command, files_to_check): |
| 368 |
"""Run an arbitrary command. Fail if it produces any diffs on the given files.""" |
| 369 |
prev_contents = {} |
| 370 |
for file in files_to_check: |
| 371 |
# NewContents just reads the file. |
| 372 |
prev_contents[file] = file.NewContents() |
| 373 |
|
| 374 |
command_str = ' '.join(command) |
| 375 |
results = [] |
| 376 |
|
| 377 |
try: |
| 378 |
subprocess.check_output( |
| 379 |
command, |
| 380 |
stderr=subprocess.STDOUT, encoding='utf-8') |
| 381 |
except subprocess.CalledProcessError as e: |
| 382 |
results += [output_api.PresubmitError( |
| 383 |
'Command "%s" returned non-zero exit code %d. Output: \n\n%s' % ( |
| 384 |
command_str, |
| 385 |
e.returncode, |
| 386 |
e.output, |
| 387 |
) |
| 388 |
)] |
| 389 |
|
| 390 |
# Compare the new content to the previous content. |
| 391 |
diffs = [] |
| 392 |
for file, prev_content in prev_contents.items(): |
| 393 |
new_content = file.NewContents(flush_cache=True) |
| 394 |
if new_content != prev_content: |
| 395 |
path = file.LocalPath() |
| 396 |
diff = difflib.unified_diff(prev_content, new_content, path, path, lineterm='') |
| 397 |
diffs.append('\n'.join(diff)) |
| 398 |
|
| 399 |
if diffs: |
| 400 |
results += [output_api.PresubmitError( |
| 401 |
'Diffs found after running "%s":\n\n%s\n\n' |
| 402 |
'Please commit or discard the above changes.' % ( |
| 403 |
command_str, |
| 404 |
'\n'.join(diffs), |
| 405 |
) |
| 406 |
)] |
| 407 |
|
| 408 |
return results |
| 409 |
|
| 410 |
|
| 411 |
def _CheckGNIGenerated(input_api, output_api): |
| 412 |
"""Ensures that the generated *.gni files are current. |
| 413 |
|
| 414 |
The Bazel project files are authoritative and some *.gni files are |
| 415 |
generated from them using the exporter_tool. This check ensures they |
| 416 |
are still current. |
| 417 |
""" |
| 418 |
if 'win32' in sys.platform: |
| 419 |
# TODO(skbug.com/40043154): Remove when Bazel builds work on Windows. |
| 420 |
# Note: `make` is not installed on Windows by default. |
| 421 |
return [ |
| 422 |
output_api.PresubmitNotifyResult( |
| 423 |
'Skipping Bazel=>GNI export check on Windows (unsupported platform).' |
| 424 |
) |
| 425 |
] |
| 426 |
if 'darwin' in sys.platform: |
| 427 |
# This takes too long on Mac with default settings. Probably due to sandboxing. |
| 428 |
return [] |
| 429 |
files = [] |
| 430 |
for affected_file in input_api.AffectedFiles(include_deletes=True): |
| 431 |
affected_file_path = affected_file.LocalPath() |
| 432 |
if affected_file_path.endswith('BUILD.bazel') or affected_file_path.endswith('.gni'): |
| 433 |
files.append(affected_file) |
| 434 |
# Generate GNI files and verify no changes. |
| 435 |
if not files: |
| 436 |
# No Bazel build files changed. |
| 437 |
return [] |
| 438 |
return _RunCommandAndCheckDiff( |
| 439 |
output_api, ['make', '-C', 'bazel', 'generate_gni'], files |
| 440 |
) |
| 441 |
|
| 442 |
|
| 443 |
def _CheckBuildifier(input_api, output_api): |
| 444 |
"""Runs Buildifier and fails on linting errors, or if it produces any diffs. |
| 445 |
|
| 446 |
This check only runs if the affected files include any WORKSPACE, BUILD, |
| 447 |
BUILD.bazel or *.bzl files. |
| 448 |
""" |
| 449 |
files = [] |
| 450 |
# Please keep the below exclude patterns in sync with those in the //:buildifier rule definition. |
| 451 |
for affected_file in input_api.AffectedFiles(include_deletes=False): |
| 452 |
affected_file_path = affected_file.LocalPath() |
| 453 |
norm_path = np(affected_file.LocalPath()) |
| 454 |
if norm_path.endswith('BUILD.bazel') or norm_path.endswith('.bzl'): |
| 455 |
if not norm_path.endswith('public.bzl') and \ |
| 456 |
not "bazel/rbe/gce_linux/" in norm_path and \ |
| 457 |
not norm_path.startswith("third_party/externals/") and \ |
| 458 |
not "node_modules/" in norm_path: # Skip generated files. |
| 459 |
files.append(affected_file) |
| 460 |
if not files: |
| 461 |
return [] |
| 462 |
try: |
| 463 |
subprocess.check_output( |
| 464 |
['buildifier', '--version'], |
| 465 |
stderr=subprocess.STDOUT) |
| 466 |
except: |
| 467 |
return [output_api.PresubmitNotifyResult( |
| 468 |
'Skipping buildifier check because it is not on PATH. \n' + |
| 469 |
'You can download it from https://github.com/bazelbuild/buildtools/releases')] |
| 470 |
|
| 471 |
return _RunCommandAndCheckDiff( |
| 472 |
# Please keep the below arguments in sync with those in the //:buildifier rule definition. |
| 473 |
output_api, [ |
| 474 |
'buildifier', |
| 475 |
'--mode=fix', |
| 476 |
'--lint=fix', |
| 477 |
'--warnings', |
| 478 |
','.join([ |
| 479 |
'-native-android', |
| 480 |
'-native-cc', |
| 481 |
'-native-py', |
| 482 |
]) |
| 483 |
] + [f.LocalPath() for f in files], files) |
| 484 |
|
| 485 |
|
| 486 |
def _CheckBannedAPIs(input_api, output_api): |
| 487 |
"""Check source code for functions, packages, and symbols that should not be used.""" |
| 488 |
|
| 489 |
# A list of tuples of a regex to match an API and a suggested replacement for |
| 490 |
# that API. There is an optional third parameter for files which *can* use this |
| 491 |
# API without warning. |
| 492 |
banned_replacements = [ |
| 493 |
(r'std::stof\(', 'std::strtof(), which does not throw'), |
| 494 |
(r'std::stod\(', 'std::strtod(), which does not throw'), |
| 495 |
(r'std::stold\(', 'std::strtold(), which does not throw'), |
| 496 |
# go/cstyle#Disallowed_Stdlib |
| 497 |
(r'std::barrier', ''), |
| 498 |
(r'std::condition_variable', ''), |
| 499 |
(r'std::counting_semaphore', ''), |
| 500 |
(r'std::future', ''), |
| 501 |
(r'std::jthread', ''), |
| 502 |
(r'std::latch', ''), |
| 503 |
(r'std::mutex', 'SkMutex'), |
| 504 |
(r'std::shared_mutex', 'SkSharedMutex'), |
| 505 |
(r'std::stop_token', ''), |
| 506 |
(r'std::thread', '', ['^tests/', 'SkExecutor']), |
| 507 |
|
| 508 |
# We used to have separate symbols for this, but coalesced them to make the |
| 509 |
# Bazel build easier. |
| 510 |
(r'GR_TEST_UTILS', 'GPU_TEST_UTILS'), |
| 511 |
(r'GRAPHITE_TEST_UTILS', 'GPU_TEST_UTILS'), |
| 512 |
|
| 513 |
# This form of multi line string can unintentionally cause Skia to ship with |
| 514 |
# extraneous spaces and newlines in its SkSL (or generated) code, which slightly |
| 515 |
# increases code size and parse time. Instead, use normal quotes and C++'s |
| 516 |
# auto-concatenation |
| 517 |
# "this string" |
| 518 |
# "and this" |
| 519 |
# "string will be joined without extra spaces" |
| 520 |
(r'R"\(', 'implied string concatenation', |
| 521 |
['^bench/', |
| 522 |
'^docs/', |
| 523 |
'^gm/', |
| 524 |
'^modules/skottie/tests/', |
| 525 |
'^src/sksl/lex/Main.cpp', |
| 526 |
'^tests/', |
| 527 |
'^tools/'] |
| 528 |
), |
| 529 |
|
| 530 |
# Our Bazel rules have special copies of our cc_library rules with GPU_TEST_UTILS |
| 531 |
# set. If GPU_TEST_UTILS is used outside of those files in Skia proper, the build |
| 532 |
# will break/crash in mysterious ways (because files may get compiled in multiple |
| 533 |
# conflicting ways as a result of the define being inconsistently set). |
| 534 |
(r'GPU_TEST_UTILS', 'use only in GPU code and tests', |
| 535 |
['^include/core/SkTypes.h', |
| 536 |
'^include/gpu/', |
| 537 |
'^include/private/gpu/', |
| 538 |
'^src/gpu/ganesh', |
| 539 |
'^src/gpu/graphite', |
| 540 |
'^tests/', |
| 541 |
'^tools/'] |
| 542 |
), |
| 543 |
] |
| 544 |
|
| 545 |
# These defines are either there or not, and using them with just an #if is a |
| 546 |
# subtle, frustrating bug. |
| 547 |
existence_defines = ['SK_GANESH', 'SK_GRAPHITE', 'SK_GL', 'SK_VULKAN', 'SK_DAWN', 'SK_METAL', |
| 548 |
'SK_DIRECT3D', 'SK_DEBUG', 'GPU_TEST_UTILS'] |
| 549 |
for d in existence_defines: |
| 550 |
banned_replacements.append(('#if {}'.format(d), |
| 551 |
'#if defined({})'.format(d))) |
| 552 |
compiled_replacements = [] |
| 553 |
for rep in banned_replacements: |
| 554 |
exceptions = [] |
| 555 |
if len(rep) == 3: |
| 556 |
(re, replacement, exceptions) = rep |
| 557 |
else: |
| 558 |
(re, replacement) = rep |
| 559 |
|
| 560 |
compiled_re = input_api.re.compile(re) |
| 561 |
compiled_exceptions = [input_api.re.compile(exc) for exc in exceptions] |
| 562 |
compiled_replacements.append( |
| 563 |
(compiled_re, replacement, compiled_exceptions)) |
| 564 |
|
| 565 |
errors = [] |
| 566 |
file_filter = lambda x: (x.LocalPath().endswith('.h') or |
| 567 |
x.LocalPath().endswith('.cpp') or |
| 568 |
x.LocalPath().endswith('.cc') or |
| 569 |
x.LocalPath().endswith('.m') or |
| 570 |
x.LocalPath().endswith('.mm')) |
| 571 |
for affected_file in input_api.AffectedSourceFiles(file_filter): |
| 572 |
affected_filepath = affected_file.LocalPath() |
| 573 |
for (line_num, line) in affected_file.ChangedContents(): |
| 574 |
for (re, replacement, exceptions) in compiled_replacements: |
| 575 |
match = re.search(line) |
| 576 |
if match: |
| 577 |
for exc in exceptions: |
| 578 |
if exc.search(affected_filepath): |
| 579 |
break |
| 580 |
else: |
| 581 |
errors.append('%s:%s: Instead of %s, please use %s.' % ( |
| 582 |
affected_filepath, line_num, match.group(), replacement)) |
| 583 |
|
| 584 |
if errors: |
| 585 |
return [output_api.PresubmitError('\n'.join(errors))] |
| 586 |
|
| 587 |
return [] |
| 588 |
|
| 589 |
|
| 590 |
def _CheckDEPS(input_api, output_api): |
| 591 |
"""If DEPS was modified, run the deps_parser to update bazel/deps.json""" |
| 592 |
files = [] |
| 593 |
for affected_file in input_api.AffectedFiles(include_deletes=False): |
| 594 |
affected_file_path = affected_file.LocalPath() |
| 595 |
if affected_file_path.endswith('DEPS') or affected_file_path.endswith('deps.json'): |
| 596 |
files.append(affected_file) |
| 597 |
if not files: |
| 598 |
return [] |
| 599 |
try: |
| 600 |
subprocess.check_output( |
| 601 |
['bazelisk', '--version'], |
| 602 |
stderr=subprocess.STDOUT) |
| 603 |
except: |
| 604 |
return [output_api.PresubmitNotifyResult( |
| 605 |
'Skipping DEPS check because bazelisk is not on PATH. \n' + |
| 606 |
'You can download it from https://github.com/bazelbuild/bazelisk/releases/tag/v1.14.0')] |
| 607 |
|
| 608 |
return _RunCommandAndCheckDiff( |
| 609 |
output_api, ['bazelisk', 'run', '//bazel/deps_parser'], files |
| 610 |
) |
| 611 |
|
| 612 |
|
| 613 |
def _CommonChecks(input_api, output_api): |
| 614 |
"""Presubmit checks common to upload and commit.""" |
| 615 |
results = [] |
| 616 |
sources = lambda x: (x.LocalPath().endswith('.h') or |
| 617 |
x.LocalPath().endswith('.py') or |
| 618 |
x.LocalPath().endswith('.sh') or |
| 619 |
x.LocalPath().endswith('.m') or |
| 620 |
x.LocalPath().endswith('.mm') or |
| 621 |
x.LocalPath().endswith('.go') or |
| 622 |
x.LocalPath().endswith('.c') or |
| 623 |
x.LocalPath().endswith('.cc') or |
| 624 |
x.LocalPath().endswith('.cpp')) |
| 625 |
results.extend(_CheckChangeHasEol( |
| 626 |
input_api, output_api, source_file_filter=sources)) |
| 627 |
with _WarningsAsErrors(output_api): |
| 628 |
results.extend(input_api.canned_checks.CheckChangeHasNoCR( |
| 629 |
input_api, output_api, source_file_filter=sources)) |
| 630 |
results.extend(input_api.canned_checks.CheckChangeHasNoStrayWhitespace( |
| 631 |
input_api, output_api, source_file_filter=sources)) |
| 632 |
results.extend(_JsonChecks(input_api, output_api)) |
| 633 |
results.extend(_IfDefChecks(input_api, output_api)) |
| 634 |
results.extend(_CopyrightChecks(input_api, output_api, |
| 635 |
source_file_filter=sources)) |
| 636 |
results.extend(_CheckIncludesFormatted(input_api, output_api)) |
| 637 |
results.extend(_CheckGNFormatted(input_api, output_api)) |
| 638 |
results.extend(_CheckGitConflictMarkers(input_api, output_api)) |
| 639 |
results.extend(_RegenerateAllExamplesCPP(input_api, output_api)) |
| 640 |
results.extend(_CheckExamplesForPrivateAPIs(input_api, output_api)) |
| 641 |
results.extend(_CheckIncludeForOutsideDeps(input_api, output_api)) |
| 642 |
results.extend(_CheckBazelBUILDFiles(input_api, output_api)) |
| 643 |
results.extend(_CheckBannedAPIs(input_api, output_api)) |
| 644 |
return results |
| 645 |
|
| 646 |
|
| 647 |
def CheckChangeOnUpload(input_api, output_api): |
| 648 |
"""Presubmit checks for the change on upload.""" |
| 649 |
results = [] |
| 650 |
results.extend(_CommonChecks(input_api, output_api)) |
| 651 |
# Run on upload, not commit, since the presubmit bot apparently doesn't have |
| 652 |
# coverage or Go installed. |
| 653 |
results.extend(_InfraTests(input_api, output_api)) |
| 654 |
results.extend(_CheckTopReleaseNotesChanged(input_api, output_api)) |
| 655 |
results.extend(_CheckReleaseNotesForPublicAPI(input_api, output_api)) |
| 656 |
# Buildifier might not be on the CI machines. |
| 657 |
results.extend(_CheckBuildifier(input_api, output_api)) |
| 658 |
# We don't want this to block the CQ (for now). |
| 659 |
results.extend(_CheckDEPS(input_api, output_api)) |
| 660 |
# Bazelisk is not yet included in the Presubmit job. |
| 661 |
results.extend(_CheckGeneratedBazelBUILDFiles(input_api, output_api)) |
| 662 |
results.extend(_CheckGNIGenerated(input_api, output_api)) |
| 663 |
return results |
| 664 |
|
| 665 |
|
| 666 |
class CodeReview(object): |
| 667 |
"""Abstracts which codereview tool is used for the specified issue.""" |
| 668 |
|
| 669 |
def __init__(self, input_api): |
| 670 |
self._issue = input_api.change.issue |
| 671 |
self._gerrit = input_api.gerrit |
| 672 |
|
| 673 |
def GetOwnerEmail(self): |
| 674 |
return self._gerrit.GetChangeOwner(self._issue) |
| 675 |
|
| 676 |
def GetSubject(self): |
| 677 |
return self._gerrit.GetChangeInfo(self._issue)['subject'] |
| 678 |
|
| 679 |
def GetDescription(self): |
| 680 |
return self._gerrit.GetChangeDescription(self._issue) |
| 681 |
|
| 682 |
def GetReviewers(self): |
| 683 |
code_review_label = ( |
| 684 |
self._gerrit.GetChangeInfo(self._issue)['labels']['Code-Review']) |
| 685 |
return [r['email'] for r in code_review_label.get('all', [])] |
| 686 |
|
| 687 |
def GetApprovers(self): |
| 688 |
approvers = [] |
| 689 |
code_review_label = ( |
| 690 |
self._gerrit.GetChangeInfo(self._issue)['labels']['Code-Review']) |
| 691 |
for m in code_review_label.get('all', []): |
| 692 |
if m.get("value") == 1: |
| 693 |
approvers.append(m["email"]) |
| 694 |
return approvers |
| 695 |
|
| 696 |
|
| 697 |
def _CheckReleaseNotesForPublicAPI(input_api, output_api): |
| 698 |
"""Checks to see if a release notes file is added or edited with public API changes.""" |
| 699 |
results = [] |
| 700 |
public_api_changed = False |
| 701 |
release_file_changed = False |
| 702 |
for affected_file in input_api.AffectedFiles(): |
| 703 |
affected_file_path = affected_file.LocalPath() |
| 704 |
file_path, file_ext = os.path.splitext(affected_file_path) |
| 705 |
# We only care about files that end in .h and are under the top-level |
| 706 |
# include dir, but not include/private. |
| 707 |
if (file_ext == '.h' and |
| 708 |
file_path.split(os.path.sep)[0] == 'include' and |
| 709 |
'private' not in file_path): |
| 710 |
public_api_changed = True |
| 711 |
elif os.path.dirname(file_path) == RELEASE_NOTES_DIR: |
| 712 |
release_file_changed = True |
| 713 |
|
| 714 |
if public_api_changed and not release_file_changed: |
| 715 |
results.append(output_api.PresubmitPromptWarning( |
| 716 |
'If this change affects a client API, please add a new summary ' |
| 717 |
'file in the %s directory. More information can be found in ' |
| 718 |
'%s.' % (RELEASE_NOTES_DIR, RELEASE_NOTES_README))) |
| 719 |
return results |
| 720 |
|
| 721 |
|
| 722 |
def _CheckTopReleaseNotesChanged(input_api, output_api): |
| 723 |
"""Warns if the top level release notes file was changed. |
| 724 |
|
| 725 |
The top level file is now auto-edited, and new release notes should |
| 726 |
be added to the RELEASE_NOTES_DIR directory""" |
| 727 |
results = [] |
| 728 |
top_relnotes_changed = False |
| 729 |
release_file_changed = False |
| 730 |
for affected_file in input_api.AffectedFiles(): |
| 731 |
affected_file_path = affected_file.LocalPath() |
| 732 |
file_path, file_ext = os.path.splitext(affected_file_path) |
| 733 |
if affected_file_path == RELEASE_NOTES_FILE_NAME: |
| 734 |
top_relnotes_changed = True |
| 735 |
elif os.path.dirname(file_path) == RELEASE_NOTES_DIR: |
| 736 |
release_file_changed = True |
| 737 |
# When relnotes_util is run it will modify RELEASE_NOTES_FILE_NAME |
| 738 |
# and delete the individual note files in RELEASE_NOTES_DIR. |
| 739 |
# So, if both paths are modified do not emit a warning. |
| 740 |
if top_relnotes_changed and not release_file_changed: |
| 741 |
results.append(output_api.PresubmitPromptWarning( |
| 742 |
'Do not edit %s directly. %s is automatically edited during the ' |
| 743 |
'release process. Release notes should be added as new files in ' |
| 744 |
'the %s directory. More information can be found in %s.' % (RELEASE_NOTES_FILE_NAME, |
| 745 |
RELEASE_NOTES_FILE_NAME, |
| 746 |
RELEASE_NOTES_DIR, |
| 747 |
RELEASE_NOTES_README))) |
| 748 |
return results |
| 749 |
|
| 750 |
|
| 751 |
def PostUploadHook(gerrit, change, output_api): |
| 752 |
"""git cl upload will call this hook after the issue is created/modified. |
| 753 |
|
| 754 |
This hook does the following: |
| 755 |
* Adds a link to preview docs changes if there are any docs changes in the CL. |
| 756 |
* Adds 'No-Try: true' if the CL contains only docs changes. |
| 757 |
""" |
| 758 |
if not change.issue: |
| 759 |
return [] |
| 760 |
|
| 761 |
# Skip PostUploadHooks for all auto-commit service account bots. New |
| 762 |
# patchsets (caused due to PostUploadHooks) invalidates the CQ+2 vote from |
| 763 |
# the "--use-commit-queue" flag to "git cl upload". |
| 764 |
for suffix in SERVICE_ACCOUNT_SUFFIX: |
| 765 |
if change.author_email.endswith(suffix): |
| 766 |
return [] |
| 767 |
|
| 768 |
results = [] |
| 769 |
at_least_one_docs_change = False |
| 770 |
all_docs_changes = True |
| 771 |
for affected_file in change.AffectedFiles(): |
| 772 |
affected_file_path = affected_file.LocalPath() |
| 773 |
file_path, _ = os.path.splitext(affected_file_path) |
| 774 |
if 'site' == file_path.split(os.path.sep)[0]: |
| 775 |
at_least_one_docs_change = True |
| 776 |
else: |
| 777 |
all_docs_changes = False |
| 778 |
if at_least_one_docs_change and not all_docs_changes: |
| 779 |
break |
| 780 |
|
| 781 |
footers = change.GitFootersFromDescription() |
| 782 |
description_changed = False |
| 783 |
|
| 784 |
# If the change includes only doc changes then add No-Try: true in the |
| 785 |
# CL's description if it does not exist yet. |
| 786 |
if all_docs_changes and 'true' not in footers.get('No-Try', []): |
| 787 |
description_changed = True |
| 788 |
change.AddDescriptionFooter('No-Try', 'true') |
| 789 |
results.append( |
| 790 |
output_api.PresubmitNotifyResult( |
| 791 |
'This change has only doc changes. Automatically added ' |
| 792 |
'\'No-Try: true\' to the CL\'s description')) |
| 793 |
|
| 794 |
# If the description has changed update it. |
| 795 |
if description_changed: |
| 796 |
gerrit.UpdateDescription( |
| 797 |
change.FullDescriptionText(), change.issue) |
| 798 |
|
| 799 |
return results |
| 800 |
|
| 801 |
|
| 802 |
def CheckChangeOnCommit(input_api, output_api): |
| 803 |
"""Presubmit checks for the change on commit.""" |
| 804 |
results = [] |
| 805 |
results.extend(_CommonChecks(input_api, output_api)) |
| 806 |
# Checks for the presence of 'DO NOT''SUBMIT' in CL description and in |
| 807 |
# content of files. |
| 808 |
results.extend( |
| 809 |
input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) |
| 810 |
return results |