Debian Codegraph @

testing/web-platform/tests/tools/lint/lint.py

raw
1 import abc
2 import argparse
3 import ast
4 import json
5 import logging
6 import multiprocessing
7 import os
8 import re
9 import subprocess
10 import sys
11 import tempfile
12 from collections import defaultdict
13 from typing import (Any, Callable, Dict, IO, Iterable, List, Optional, Sequence, Set, Text, Tuple,
14 Type, TypeVar)
15
16 from urllib.parse import urlsplit, urljoin, parse_qs
17
18 try:
19 from xml.etree import cElementTree as ElementTree
20 except ImportError:
21 from xml.etree import ElementTree as ElementTree # type: ignore
22
23 from . import fnmatch
24 from . import rules
25 from .. import localpaths
26 from ..ci.tc.github_checks_output import get_gh_checks_outputter, GitHubChecksOutputter
27 from ..gitignore.gitignore import PathFilter
28 from ..wpt import testfiles
29 from ..manifest.mputil import max_parallelism
30 from ..manifest.vcs import walk
31
32 from ..manifest.sourcefile import SourceFile, js_meta_re, python_meta_re, space_chars, get_any_variants
33
34 from ..metadata.yaml.load import load_data_to_dict
35 from ..metadata.meta.schema import META_YML_FILENAME, MetaFile
36 from ..metadata.webfeatures.schema import WEB_FEATURES_YML_FILENAME, WebFeaturesFile
37
38 # The Ignorelist is a two level dictionary. The top level is indexed by
39 # error names (e.g. 'TRAILING WHITESPACE'). Each of those then has a map of
40 # file patterns (e.g. 'foo/*') to a set of specific line numbers for the
41 # exception. The line numbers are optional; if missing the entire file
42 # ignores the error.
43 Ignorelist = Dict[str, Dict[str, Set[Optional[int]]]]
44
45 # Define an arbitrary typevar
46 T = TypeVar("T")
47
48
49 logger: Optional[logging.Logger] = None
50
51
52 def setup_logging(prefix: bool = False) -> None:
53 global logger
54 if logger is None:
55 logger = logging.getLogger(os.path.basename(os.path.splitext(__file__)[0]))
56 handler: logging.Handler = logging.StreamHandler(sys.stdout)
57 # Only add a handler if the parent logger is missing a handler
58 parent = logger.parent
59 assert isinstance(parent, logging.Logger)
60 if parent and len(parent.handlers) == 0:
61 handler = logging.StreamHandler(sys.stdout)
62 logger.addHandler(handler)
63 if prefix:
64 format = logging.BASIC_FORMAT
65 else:
66 format = "%(message)s"
67 formatter = logging.Formatter(format)
68 for handler in logger.handlers:
69 handler.setFormatter(formatter)
70 logger.setLevel(logging.DEBUG)
71
72
73 setup_logging()
74
75
76 ERROR_MSG = """You must fix all errors; for details on how to fix them, see
77 https://web-platform-tests.org/writing-tests/lint-tool.html
78
79 However, instead of fixing a particular error, it's sometimes
80 OK to add a line to the lint.ignore file in the root of the
81 web-platform-tests directory to make the lint tool ignore it.
82
83 For example, to make the lint tool ignore all '%s'
84 errors in the %s file,
85 you could add the following line to the lint.ignore file.
86
87 %s: %s"""
88
89
90 def all_filesystem_paths(repo_root: Text, subdir: Optional[Text] = None) -> Iterable[Text]:
91 path_filter = PathFilter(repo_root.encode("utf8"),
92 extras=[b".git/"])
93 if subdir:
94 expanded_path = subdir.encode("utf8")
95 subdir_str = expanded_path
96 else:
97 expanded_path = repo_root.encode("utf8")
98 for dirpath, dirnames, filenames in path_filter(walk(expanded_path)):
99 for filename, _ in filenames:
100 path = os.path.join(dirpath, filename)
101 if subdir:
102 path = os.path.join(subdir_str, path)
103 assert not os.path.isabs(path), path
104 yield path.decode("utf8")
105
106
107 def _all_files_equal(paths: Iterable[Text]) -> bool:
108 """
109 Checks all the paths are files that are byte-for-byte identical
110
111 :param paths: the list of paths to compare
112 :returns: True if they are all identical
113 """
114 paths = list(paths)
115 if len(paths) < 2:
116 return True
117
118 first = paths.pop()
119 size = os.path.getsize(first)
120 if any(os.path.getsize(path) != size for path in paths):
121 return False
122
123 # Chunk this to avoid eating up memory and file descriptors
124 bufsize = 4096*4 # 16KB, a "reasonable" number of disk sectors
125 groupsize = 8 # Hypothesised to be large enough in the common case that everything fits in one group
126 with open(first, "rb") as first_f:
127 for start in range(0, len(paths), groupsize):
128 path_group = paths[start:start+groupsize]
129 first_f.seek(0)
130 try:
131 files = [open(x, "rb") for x in path_group]
132 for _ in range(0, size, bufsize):
133 a = first_f.read(bufsize)
134 for f in files:
135 b = f.read(bufsize)
136 if a != b:
137 return False
138 finally:
139 for f in files:
140 f.close()
141
142 return True
143
144
145 def check_path_length(repo_root: Text, path: Text) -> List[rules.Error]:
146 if len(path) + 1 > 150:
147 return [rules.PathLength.error(path, (path, len(path) + 1))]
148 return []
149
150
151 def check_file_type(repo_root: Text, path: Text) -> List[rules.Error]:
152 if os.path.islink(path):
153 return [rules.FileType.error(path, (path, "symlink"))]
154 return []
155
156
157 def check_worker_collision(repo_root: Text, path: Text) -> List[rules.Error]:
158 endings = [(".any.html", ".any.js"),
159 (".any.worker.html", ".any.js"),
160 (".worker.html", ".worker.js")]
161 for path_ending, generated in endings:
162 if path.endswith(path_ending):
163 return [rules.WorkerCollision.error(path, (path_ending, generated))]
164 return []
165
166
167 def check_gitignore_file(repo_root: Text, path: Text) -> List[rules.Error]:
168 if not path.endswith(".gitignore"):
169 return []
170
171 path_parts = path.split(os.path.sep)
172 if len(path_parts) == 1:
173 return []
174
175 if path_parts[-1] != ".gitignore":
176 return []
177
178 if (path_parts[0] in ["tools", "docs"] or
179 path_parts[:2] == ["resources", "webidl2"]):
180 return []
181
182 return [rules.GitIgnoreFile.error(path)]
183
184
185 def check_mojom_js(repo_root: Text, path: Text) -> List[rules.Error]:
186 if path.endswith(".mojom.js"):
187 return [rules.MojomJSFile.error(path)]
188 return []
189
190
191 def check_ahem_copy(repo_root: Text, path: Text) -> List[rules.Error]:
192 lpath = path.lower()
193 if "ahem" in lpath and lpath.endswith(".ttf"):
194 return [rules.AhemCopy.error(path)]
195 return []
196
197
198 def check_tentative_directories(repo_root: Text, path: Text) -> List[rules.Error]:
199 path_parts = path.split(os.path.sep)
200 for directory in path_parts[:-1]:
201 if "tentative" in directory and directory != "tentative":
202 return [rules.TentativeDirectoryName.error(path)]
203 return []
204
205
206 def check_git_ignore(repo_root: Text, paths: List[Text]) -> List[rules.Error]:
207 errors = []
208
209 with tempfile.TemporaryFile('w+', newline='') as f:
210 for path in paths:
211 f.write('%s\n' % os.path.join(repo_root, path))
212 f.seek(0)
213 try:
214 matches = subprocess.check_output(
215 ["git", "check-ignore", "--verbose", "--no-index", "--stdin"], stdin=f)
216 for match in matches.strip().split(b'\n'):
217 match_filter, path_bytes = match.split()
218 _, _, filter_string = match_filter.split(b':')
219 # If the matching filter reported by check-ignore is a special-case exception,
220 # that's fine. Otherwise, it requires a new special-case exception.
221 if filter_string[0:1] != b'!':
222 path = path_bytes.decode("utf8")
223 errors.append(rules.IgnoredPath.error(path, (path,)))
224 except subprocess.CalledProcessError:
225 # Nonzero return code means that no match exists.
226 pass
227 return errors
228
229
230 drafts_csswg_re = re.compile(r"https?\:\/\/drafts\.csswg\.org\/([^/?#]+)")
231 w3c_tr_re = re.compile(r"https?\:\/\/www\.w3c?\.org\/TR\/([^/?#]+)")
232 w3c_dev_re = re.compile(r"https?\:\/\/dev\.w3c?\.org\/[^/?#]+\/([^/?#]+)")
233
234
235 def check_unique_testharness_basenames(repo_root: Text, paths: List[Text]) -> List[rules.Error]:
236 """
237 Checks that all testharness files have unique basename paths.
238
239 The 'basename path' refers to the entire path excluding the extension. For
240 example, 'foo/bar/baz.html' and 'foo/bar/baz.xhtml' have the same basename
241 path, but 'foo/bar/baz.html' and 'foo/qux/baz.html' do not.
242
243 Testharness files with identical basenames have caused issues in downstream
244 infrastructure (see https://github.com/web-platform-tests/wpt/issues/7570),
245 and may cause confusion in general.
246
247 :param repo_root: the repository root
248 :param paths: list of all paths
249 :returns: a list of errors found in ``paths``
250 """
251
252 errors = []
253 file_dict = defaultdict(list)
254 for path in paths:
255 source_file = SourceFile(repo_root, path, "/")
256 if "testharness" not in source_file.possible_types:
257 continue
258 file_name, file_extension = os.path.splitext(path)
259 file_dict[file_name].append(file_extension)
260 for k, v in file_dict.items():
261 if len(v) == 1:
262 continue
263 context = (', '.join(v),)
264 for extension in v:
265 errors.append(rules.DuplicateBasenamePath.error(k + extension, context))
266 return errors
267
268
269 def check_unique_case_insensitive_paths(repo_root: Text, paths: List[Text]) -> List[rules.Error]:
270 seen: Dict[Text, Text] = {}
271 errors = []
272 for path in paths:
273 lower_path = path.lower()
274 if lower_path in seen:
275 context = (seen[lower_path],)
276 errors.append(rules.DuplicatePathCaseInsensitive.error(path, context))
277 else:
278 seen[lower_path] = path
279 return errors
280
281
282 def parse_ignorelist(f: IO[Text]) -> Tuple[Ignorelist, Set[Text]]:
283 """
284 Parse the ignorelist file given by `f`, and return the parsed structure.
285
286 :returns: a tuple of an Ignorelist and a set of files that are completely
287 skipped by the linter (i.e. have a '*' entry).
288 """
289
290 data: Ignorelist = defaultdict(lambda:defaultdict(set))
291 skipped_files: Set[Text] = set()
292
293 for line in f:
294 line = line.strip()
295 if not line or line.startswith("#"):
296 continue
297 parts = [item.strip() for item in line.split(":")]
298
299 if len(parts) == 2:
300 error_types_s, file_match = parts
301 line_number: Optional[int] = None
302 else:
303 error_types_s, file_match, line_number_s = parts
304 line_number = int(line_number_s)
305
306 error_types = {item.strip() for item in error_types_s.split(",")}
307 file_match = os.path.normcase(file_match)
308
309 if "*" in error_types:
310 skipped_files.add(file_match)
311 else:
312 for error_type in error_types:
313 data[error_type][file_match].add(line_number)
314
315 return data, skipped_files
316
317
318 def filter_ignorelist_errors(data: Ignorelist, errors: Sequence[rules.Error]) -> List[rules.Error]:
319 """
320 Filter out those errors that are ignored in `data`.
321 """
322
323 if not errors:
324 return []
325
326 skipped = [False for item in range(len(errors))]
327
328 for i, (error_type, msg, path, line) in enumerate(errors):
329 normpath = os.path.normcase(path)
330 # Allow skipping all lint errors except the IGNORED PATH lint,
331 # which explains how to fix it correctly and shouldn't be skipped.
332 if error_type in data and error_type != "IGNORED PATH":
333 wl_files = data[error_type]
334 for file_match, allowed_lines in wl_files.items():
335 if None in allowed_lines or line in allowed_lines:
336 if fnmatch.fnmatchcase(normpath, file_match):
337 skipped[i] = True
338
339 return [item for i, item in enumerate(errors) if not skipped[i]]
340
341
342 regexps = [item() for item in # type: ignore
343 [rules.TrailingWhitespaceRegexp,
344 rules.TabsRegexp,
345 rules.CRRegexp,
346 rules.SetTimeoutRegexp,
347 rules.W3CTestOrgRegexp,
348 rules.WebPlatformTestRegexp,
349 rules.Webidl2Regexp,
350 rules.ConsoleRegexp,
351 rules.GenerateTestsRegexp,
352 rules.PrintRegexp,
353 rules.LayoutTestsRegexp,
354 rules.MissingDepsRegexp,
355 rules.SpecialPowersRegexp,
356 rules.AssertThrowsRegexp,
357 rules.PromiseRejectsRegexp,
358 rules.AssertPreconditionRegexp,
359 rules.HTMLInvalidSyntaxRegexp]]
360
361
362 def check_regexp_line(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
363 errors: List[rules.Error] = []
364
365 applicable_regexps = [regexp for regexp in regexps if regexp.applies(path)]
366
367 for i, line in enumerate(f):
368 for regexp in applicable_regexps:
369 if regexp.search(line):
370 errors.append((regexp.name, regexp.description, path, i+1))
371
372 return errors
373
374
375 def check_parsed(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
376 source_file = SourceFile(repo_root, path, "/", contents=f.read())
377
378 errors: List[rules.Error] = []
379
380 if path.startswith("css/"):
381 if (source_file.type != "support" and
382 not source_file.name_is_reference and
383 not source_file.name_is_tentative and
384 not source_file.name_is_crashtest and
385 not source_file.spec_links):
386 return [rules.MissingLink.error(path)]
387
388 if source_file.name_is_non_test:
389 return []
390
391 if source_file.markup_type is None:
392 return []
393
394 if source_file.root is None:
395 return [rules.ParseFailed.error(path)]
396
397 test_type = source_file.type
398
399 if test_type == "manual" and not source_file.name_is_manual:
400 errors.append(rules.ContentManual.error(path))
401
402 if test_type == "visual" and not source_file.name_is_visual:
403 errors.append(rules.ContentVisual.error(path))
404
405 about_blank_parts = urlsplit("about:blank")
406 for reftest_node in source_file.reftest_nodes:
407 href = reftest_node.attrib.get("href", "").strip(space_chars)
408 parts = urlsplit(href)
409
410 if parts == about_blank_parts:
411 continue
412
413 if (parts.scheme or parts.netloc):
414 errors.append(rules.AbsoluteUrlRef.error(path, (href,)))
415 continue
416
417 ref_url = urljoin(source_file.url, href)
418 ref_parts = urlsplit(ref_url)
419
420 if source_file.url == ref_url:
421 errors.append(rules.SameFileRef.error(path))
422 continue
423
424 assert ref_parts.path != ""
425
426 reference_file = os.path.join(repo_root, ref_parts.path[1:])
427 reference_rel = reftest_node.attrib.get("rel", "")
428
429 if not os.path.isfile(reference_file):
430 errors.append(rules.NonexistentRef.error(path,
431 (reference_rel, href)))
432
433 if source_file.reftest_nodes:
434 if test_type not in ("print-reftest", "reftest"):
435 errors.append(rules.ReferenceInOtherType.error(path, (test_type,)))
436
437 if len(source_file.timeout_nodes) > 1:
438 errors.append(rules.MultipleTimeout.error(path))
439
440 for timeout_node in source_file.timeout_nodes:
441 timeout_value = timeout_node.attrib.get("content", "").lower()
442 if timeout_value != "long":
443 errors.append(rules.InvalidTimeout.error(path, (timeout_value,)))
444
445 if source_file.content_is_ref_node or source_file.content_is_testharness:
446 for element in source_file.variant_nodes:
447 if "content" not in element.attrib:
448 errors.append(rules.VariantMissing.error(path))
449 else:
450 variant = element.attrib["content"]
451 if is_variant_malformed(variant):
452 value = f"{path} `<meta name=variant>` 'content' attribute"
453 errors.append(rules.MalformedVariant.error(path, (value,)))
454
455 required_elements: List[Text] = []
456
457 testharnessreport_nodes: List[ElementTree.Element] = []
458 if source_file.testharness_nodes:
459 if test_type not in ("testharness", "manual"):
460 errors.append(rules.TestharnessInOtherType.error(path, (test_type,)))
461 if len(source_file.testharness_nodes) > 1:
462 errors.append(rules.MultipleTestharness.error(path))
463
464 testharnessreport_nodes = source_file.root.findall(".//{http://www.w3.org/1999/xhtml}script[@src='/resources/testharnessreport.js']")
465 if not testharnessreport_nodes:
466 errors.append(rules.MissingTestharnessReport.error(path))
467 else:
468 if len(testharnessreport_nodes) > 1:
469 errors.append(rules.MultipleTestharnessReport.error(path))
470
471 required_elements.extend(key for key, value in {"testharness": True,
472 "testharnessreport": len(testharnessreport_nodes) > 0,
473 "timeout": len(source_file.timeout_nodes) > 0}.items()
474 if value)
475
476 testdriver_vendor_nodes: List[ElementTree.Element] = []
477 if source_file.testdriver_nodes:
478 if test_type not in {"testharness", "reftest", "print-reftest", "crashtest", "support"}:
479 errors.append(rules.TestdriverInUnsupportedType.error(path, (test_type,)))
480
481 if len(source_file.testdriver_nodes) > 1:
482 errors.append(rules.MultipleTestdriver.error(path))
483
484 testdriver_vendor_nodes = source_file.root.findall(".//{http://www.w3.org/1999/xhtml}script[@src='/resources/testdriver-vendor.js']")
485 if not testdriver_vendor_nodes:
486 errors.append(rules.MissingTestdriverVendor.error(path))
487 else:
488 if len(testdriver_vendor_nodes) > 1:
489 errors.append(rules.MultipleTestdriverVendor.error(path))
490
491 required_elements.append("testdriver")
492 if len(testdriver_vendor_nodes) > 0:
493 required_elements.append("testdriver-vendor")
494
495 if required_elements:
496 seen_elements = defaultdict(bool)
497
498 for elem in source_file.root.iter():
499 if source_file.timeout_nodes and elem == source_file.timeout_nodes[0]:
500 seen_elements["timeout"] = True
501 if seen_elements["testharness"]:
502 errors.append(rules.LateTimeout.error(path))
503
504 elif source_file.testharness_nodes and elem == source_file.testharness_nodes[0]:
505 seen_elements["testharness"] = True
506
507 elif testharnessreport_nodes and elem == testharnessreport_nodes[0]:
508 seen_elements["testharnessreport"] = True
509 if not seen_elements["testharness"]:
510 errors.append(rules.EarlyTestharnessReport.error(path))
511
512 elif source_file.testdriver_nodes and elem == source_file.testdriver_nodes[0]:
513 seen_elements["testdriver"] = True
514
515 elif testdriver_vendor_nodes and elem == testdriver_vendor_nodes[0]:
516 seen_elements["testdriver-vendor"] = True
517 if not seen_elements["testdriver"]:
518 errors.append(rules.EarlyTestdriverVendor.error(path))
519
520 if all(seen_elements[name] for name in required_elements):
521 break
522
523 for element in source_file.root.findall(".//{http://www.w3.org/1999/xhtml}script[@src]"):
524 src = element.attrib["src"]
525
526 def is_path_correct(script: Text, src: Text) -> bool:
527 """
528 If the `src` relevant to the `script`, check that the `src` is the
529 correct path for `script`.
530 :param script: the script name to check the `src` for.
531 :param src: the included path.
532 :return: if the `src` irrelevant to the `script`, or if the `src`
533 path is the correct path.
534 """
535 if script == src:
536 # The src does not provide the full path.
537 return False
538
539 if "/%s" % script not in src:
540 # The src is not relevant to the script.
541 return True
542
543 return ("%s" % src).startswith("/resources/%s" % script)
544
545 def is_query_string_correct(script: Text, src: Text,
546 allowed_query_string_params: Dict[str, List[str]]) -> bool:
547 """
548 Checks if the query string in a script tag's `src` is valid.
549
550 Specifically, it verifies that the query string parameters and their
551 values are among those allowed for the given script. It handles vendor
552 prefixes (parameters or values containing a colon) by allowing them
553 unconditionally.
554
555 :param script: the name of the script (e.g., "testharness.js"). Used
556 to verify is the given `src` is related to the
557 script.
558 :param src: the full `src` attribute value from the script tag.
559 :param allowed_query_string_params: A dictionary where keys are
560 allowed parameter names and
561 values are lists of allowed
562 values for each parameter.
563 :return: if the query string is empty or contains only allowed
564 params.
565 """
566 if not ("%s" % src).startswith("/resources/%s?" % script):
567 # The src is not related to the script.
568 return True
569
570 try:
571 query_string = urlsplit(urljoin(source_file.url, src)).query
572 query_string_params = parse_qs(query_string,
573 keep_blank_values=True)
574 except ValueError:
575 # Parsing error means that the query string is incorrect.
576 return False
577
578 for param_name in query_string_params:
579 if param_name not in allowed_query_string_params:
580 return False
581
582 for param_value in query_string_params[param_name]:
583 if ':' in param_value:
584 # Allow for vendor-specific values in query parameters.
585 continue
586 if param_value not in allowed_query_string_params[
587 param_name]:
588 return False
589 return True
590
591 if (not is_path_correct("testharness.js", src) or
592 not is_query_string_correct("testharness.js", src, {})):
593 errors.append(rules.TestharnessPath.error(path))
594
595 if (not is_path_correct("testharnessreport.js", src) or
596 not is_query_string_correct("testharnessreport.js", src, {})):
597 errors.append(rules.TestharnessReportPath.error(path))
598
599 if not is_path_correct("testdriver.js", src):
600 errors.append(rules.TestdriverPath.error(path))
601 if not is_query_string_correct("testdriver.js", src,
602 {'feature': ['bidi']}):
603 errors.append(rules.TestdriverUnsupportedQueryParameter.error(path))
604
605 if (not is_path_correct("testdriver-vendor.js", src) or
606 not is_query_string_correct("testdriver-vendor.js", src, {})):
607 errors.append(rules.TestdriverVendorPath.error(path))
608
609 script_path = None
610 try:
611 script_path = urlsplit(urljoin(source_file.url, src)).path
612 except ValueError:
613 # This happens if the contents of src isn't something that looks like a URL to Python
614 pass
615 if (script_path == "/common/reftest-wait.js" and
616 "reftest-wait" not in source_file.root.attrib.get("class", "").split()):
617 errors.append(rules.MissingReftestWait.error(path))
618
619 return errors
620
621
622 def is_variant_malformed(variant: str) -> bool:
623 return (variant == "" or variant[0] not in ("?", "#") or
624 len(variant) == 1 or (variant[0] == "?" and variant[1] == "#"))
625
626
627 class ASTCheck(metaclass=abc.ABCMeta):
628 @abc.abstractproperty
629 def rule(self) -> Type[rules.Rule]:
630 pass
631
632 @abc.abstractmethod
633 def check(self, root: ast.AST) -> List[int]:
634 pass
635
636 class OpenModeCheck(ASTCheck):
637 rule = rules.OpenNoMode
638
639 def check(self, root: ast.AST) -> List[int]:
640 errors = []
641 for node in ast.walk(root):
642 if isinstance(node, ast.Call):
643 if hasattr(node.func, "id") and node.func.id in ("open", "file"):
644 if (len(node.args) < 2 and
645 all(item.arg != "mode" for item in node.keywords)):
646 errors.append(node.lineno)
647 return errors
648
649 ast_checkers = [item() for item in [OpenModeCheck]]
650
651 def check_python_ast(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
652 if not path.endswith(".py"):
653 return []
654
655 try:
656 root = ast.parse(f.read())
657 except SyntaxError as e:
658 return [rules.ParseFailed.error(path, line_no=e.lineno)]
659
660 errors = []
661 for checker in ast_checkers:
662 for lineno in checker.check(root):
663 errors.append(checker.rule.error(path, line_no=lineno))
664 return errors
665
666
667 broken_js_metadata = re.compile(br"//\s*META:")
668 broken_python_metadata = re.compile(br"#\s*META:")
669
670
671 def check_global_metadata(value: bytes) -> Iterable[Tuple[Type[rules.Rule], Tuple[Any, ...]]]:
672 global_values = {item.strip().decode("utf8") for item in value.split(b",") if item.strip()}
673
674 # TODO: this could check for duplicates and such
675 for global_value in global_values:
676 if not get_any_variants(global_value):
677 yield (rules.UnknownGlobalMetadata, ())
678
679
680 def check_script_metadata(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
681 if path.endswith((".window.js", ".worker.js", ".any.js")):
682 meta_re = js_meta_re
683 broken_metadata = broken_js_metadata
684 elif path.endswith(".py"):
685 meta_re = python_meta_re
686 broken_metadata = broken_python_metadata
687 else:
688 return []
689
690 done = False
691 errors = []
692 for line_no, line in enumerate(f, 1):
693 assert isinstance(line, bytes), line
694
695 m = meta_re.match(line)
696 if m:
697 key, value = m.groups()
698 if key == b"global":
699 for rule_class, context in check_global_metadata(value):
700 errors.append(rule_class.error(path, context, line_no))
701 elif key == b"timeout":
702 if value != b"long":
703 errors.append(rules.UnknownTimeoutMetadata.error(path,
704 line_no=line_no))
705 elif key == b"variant":
706 if is_variant_malformed(value.decode()):
707 value = f"{path} `META: variant=...` value"
708 errors.append(rules.MalformedVariant.error(path, (value,), line_no))
709 elif key == b"script":
710 if value == b"/resources/testharness.js":
711 errors.append(rules.MultipleTestharness.error(path, line_no=line_no))
712 elif value == b"/resources/testharnessreport.js":
713 errors.append(rules.MultipleTestharnessReport.error(path, line_no=line_no))
714 elif key not in (b"title", b"quic"):
715 errors.append(rules.UnknownMetadata.error(path, line_no=line_no))
716 else:
717 done = True
718
719 if done:
720 if meta_re.match(line):
721 errors.append(rules.StrayMetadata.error(path, line_no=line_no))
722 elif meta_re.search(line):
723 errors.append(rules.IndentedMetadata.error(path, line_no=line_no))
724 elif broken_metadata.search(line):
725 errors.append(rules.BrokenMetadata.error(path, line_no=line_no))
726
727 return errors
728
729
730 ahem_font_re = re.compile(br"font.*:.*ahem", flags=re.IGNORECASE)
731 # Ahem can appear either in the global location or in the support
732 # directory for legacy Mozilla imports
733 ahem_stylesheet_re = re.compile(br"\/fonts\/ahem\.css|support\/ahem.css",
734 flags=re.IGNORECASE)
735
736
737 def check_ahem_system_font(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
738 if not path.endswith((".html", ".htm", ".xht", ".xhtml")):
739 return []
740 contents = f.read()
741 errors = []
742 if ahem_font_re.search(contents) and not ahem_stylesheet_re.search(contents):
743 errors.append(rules.AhemSystemFont.error(path))
744 return errors
745
746
747 def check_meta_file(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
748 if os.path.basename(path) != META_YML_FILENAME:
749 return []
750 try:
751 MetaFile(load_data_to_dict(f))
752 except Exception:
753 return [rules.InvalidMetaFile.error(path)]
754 return []
755
756
757 def check_web_features_file(repo_root: Text, path: Text, f: IO[bytes]) -> List[rules.Error]:
758 if os.path.basename(path) != WEB_FEATURES_YML_FILENAME:
759 return []
760 try:
761 web_features_file: WebFeaturesFile = WebFeaturesFile(load_data_to_dict(f))
762 except Exception:
763 return [rules.InvalidWebFeaturesFile.error(path)]
764 errors = []
765 base_dir = os.path.join(repo_root, os.path.dirname(path))
766 files_in_directory = [
767 f for f in os.listdir(base_dir) if os.path.isfile(os.path.join(base_dir, f))]
768 for feature in web_features_file.features:
769 if isinstance(feature.files, list):
770 for file in feature.files:
771 if not file.match_files(files_in_directory):
772 errors.append(rules.MissingTestInWebFeaturesFile.error(path, (file)))
773
774 return errors
775
776
777 def check_path(repo_root: Text, path: Text) -> List[rules.Error]:
778 """
779 Runs lints that check the file path.
780
781 :param repo_root: the repository root
782 :param path: the path of the file within the repository
783 :returns: a list of errors found in ``path``
784 """
785
786 errors = []
787 for path_fn in path_lints:
788 errors.extend(path_fn(repo_root, path))
789 return errors
790
791
792 def check_all_paths(repo_root: Text, paths: List[Text]) -> List[rules.Error]:
793 """
794 Runs lints that check all paths globally.
795
796 :param repo_root: the repository root
797 :param paths: a list of all the paths within the repository
798 :returns: a list of errors found in ``f``
799 """
800
801 errors = []
802 for paths_fn in all_paths_lints():
803 errors.extend(paths_fn(repo_root, paths))
804 return errors
805
806
807 def check_file_contents(repo_root: Text, path: Text, f: Optional[IO[bytes]] = None) -> List[rules.Error]:
808 """
809 Runs lints that check the file contents.
810
811 :param repo_root: the repository root
812 :param path: the path of the file within the repository
813 :param f: a file-like object with the file contents
814 :returns: a list of errors found in ``f``
815 """
816 if f is None:
817 f = open(os.path.join(repo_root, path), 'rb')
818 with f:
819 errors = []
820 for file_fn in file_lints:
821 errors.extend(file_fn(repo_root, path, f))
822 f.seek(0)
823 return errors
824
825
826 def check_file_contents_apply(args: Tuple[Text, Text]) -> List[rules.Error]:
827 return check_file_contents(*args)
828
829
830 def output_errors_text(log: Callable[[Any], None], errors: List[rules.Error]) -> None:
831 for error_type, description, path, line_number in errors:
832 pos_string = path
833 if line_number:
834 pos_string += ":%s" % line_number
835 log(f"{pos_string}: {description} ({error_type})")
836
837
838 def output_errors_markdown(log: Callable[[Any], None], errors: List[rules.Error]) -> None:
839 if not errors:
840 return
841 heading = """Got lint errors:
842
843 | Error Type | Position | Message |
844 |------------|----------|---------|"""
845 for line in heading.split("\n"):
846 log(line)
847 for error_type, description, path, line_number in errors:
848 pos_string = path
849 if line_number:
850 pos_string += ":%s" % line_number
851 log(f"{error_type} | {pos_string} | {description} |")
852
853
854 def output_errors_json(log: Callable[[Any], None], errors: List[rules.Error]) -> None:
855 for error_type, error, path, line_number in errors:
856 # We use 'print' rather than the log function to ensure that the output
857 # is valid JSON (e.g. with no logger preamble).
858 print(json.dumps({"path": path, "lineno": line_number,
859 "rule": error_type, "message": error}))
860
861
862 def output_errors_github_checks(outputter: GitHubChecksOutputter, errors: List[rules.Error], first_reported: bool) -> None:
863 """Output errors to the GitHub Checks output markdown format.
864
865 :param outputter: the GitHub Checks outputter
866 :param errors: a list of error tuples (error type, message, path, line number)
867 :param first_reported: True if these are the first reported errors
868 """
869 if first_reported:
870 outputter.output(
871 "\nChanges in this PR contain lint errors, listed below. These "
872 "errors must either be fixed or added to the list of ignored "
873 "errors; see [the documentation]("
874 "https://web-platform-tests.org/writing-tests/lint-tool.html). "
875 "For help, please tag `@web-platform-tests/wpt-core-team` in a "
876 "comment.\n")
877 outputter.output("```")
878 output_errors_text(outputter.output, errors)
879
880
881 def output_error_count(error_count: Dict[Text, int]) -> None:
882 if not error_count:
883 return
884
885 assert logger is not None
886 by_type = " ".join("%s: %d" % item for item in error_count.items())
887 count = sum(error_count.values())
888 logger.info("")
889 if count == 1:
890 logger.info(f"There was 1 error ({by_type})")
891 else:
892 logger.info("There were %d errors (%s)" % (count, by_type))
893
894
895 def changed_files(wpt_root: Text) -> List[Text]:
896 revish = testfiles.get_revish(revish=None)
897 changed, _ = testfiles.files_changed(revish, None, include_uncommitted=True, include_new=True)
898 return [os.path.relpath(item, wpt_root) for item in changed]
899
900
901 def lint_paths(kwargs: Dict[Text, Any], wpt_root: Text) -> List[Text]:
902 if kwargs.get("paths"):
903 paths = []
904 for path in kwargs.get("paths", []):
905 if os.path.isdir(path):
906 path_dir = list(all_filesystem_paths(wpt_root, path))
907 paths.extend(path_dir)
908 elif os.path.isfile(path):
909 paths.append(os.path.relpath(os.path.abspath(path), wpt_root))
910 elif kwargs["all"]:
911 paths = list(all_filesystem_paths(wpt_root))
912 elif kwargs["paths_file"]:
913 paths = []
914 with open(kwargs["paths_file"], 'r', newline='') as f:
915 for line in f.readlines():
916 path = line.strip()
917 if os.path.isdir(path):
918 path_dir = list(all_filesystem_paths(wpt_root, path))
919 paths.extend(path_dir)
920 elif os.path.isfile(path):
921 paths.append(os.path.relpath(os.path.abspath(path), wpt_root))
922 else:
923 changed_paths = changed_files(wpt_root)
924 force_all = False
925 for path in changed_paths:
926 path = path.replace(os.path.sep, "/")
927 if path == "lint.ignore" or path.startswith("tools/lint/"):
928 force_all = True
929 break
930 paths = (list(changed_paths) if not force_all
931 else list(all_filesystem_paths(wpt_root)))
932
933 return paths
934
935
936 def create_parser() -> argparse.ArgumentParser:
937 parser = argparse.ArgumentParser()
938 parser.add_argument("paths", nargs="*",
939 help="List of paths to lint")
940 parser.add_argument("--json", action="store_true",
941 help="Output machine-readable JSON format")
942 parser.add_argument("--markdown", action="store_true",
943 help="Output markdown")
944 parser.add_argument("--repo-root", type=str,
945 help="The WPT directory. Use this "
946 "option if the lint script exists outside the repository")
947 parser.add_argument("--ignore-glob", type=str, action="append",
948 help="Additional file glob to ignore (repeat to add more). "
949 "Globs are matched against paths relative to REPO_ROOT "
950 "using fnmatch, except that path separators are normalized.")
951 parser.add_argument("--all", action="store_true", help="If no paths are passed, try to lint the whole "
952 "working directory, not just files that changed")
953 parser.add_argument("--github-checks-text-file", type=str,
954 help="Path to GitHub checks output file for Taskcluster runs")
955 parser.add_argument("-j", "--jobs", type=int, default=0,
956 help="Level to parallelism to use (defaults to 0, which detects the number of CPUs)")
957 parser.add_argument("--paths-file", help="File containing a list of files to lint, one per line")
958 return parser
959
960
961 def main(venv: Any = None, **kwargs: Any) -> int:
962
963 assert logger is not None
964 if kwargs.get("json") and kwargs.get("markdown"):
965 logger.critical("Cannot specify --json and --markdown")
966 sys.exit(2)
967
968 repo_root = kwargs.get('repo_root') or localpaths.repo_root
969 output_format = {(True, False): "json",
970 (False, True): "markdown",
971 (False, False): "normal"}[(kwargs.get("json", False),
972 kwargs.get("markdown", False))]
973
974 if output_format == "markdown":
975 setup_logging(True)
976
977 paths = lint_paths(kwargs, repo_root)
978
979 ignore_glob = kwargs.get("ignore_glob", [])
980
981 github_checks_outputter = get_gh_checks_outputter(kwargs["github_checks_text_file"])
982
983 jobs = kwargs.get("jobs", 0)
984
985 return lint(repo_root, paths, output_format, ignore_glob, github_checks_outputter, jobs)
986
987
988 # best experimental guess at a decent cut-off for using the parallel path
989 MIN_FILES_FOR_PARALLEL = 80
990
991
992 def lint(repo_root: Text,
993 paths: List[Text],
994 output_format: Text,
995 ignore_glob: Optional[List[Text]] = None,
996 github_checks_outputter: Optional[GitHubChecksOutputter] = None,
997 jobs: int = 0) -> int:
998 error_count: Dict[Text, int] = defaultdict(int)
999 last = None
1000
1001 if jobs == 0:
1002 jobs = max_parallelism()
1003
1004 with open(os.path.join(repo_root, "lint.ignore")) as f:
1005 ignorelist, skipped_files = parse_ignorelist(f)
1006
1007 if ignore_glob:
1008 skipped_files |= set(ignore_glob)
1009
1010 output_errors = {"json": output_errors_json,
1011 "markdown": output_errors_markdown,
1012 "normal": output_errors_text}[output_format]
1013
1014 def process_errors(errors: List[rules.Error]) -> Optional[Tuple[Text, Text]]:
1015 """
1016 Filters and prints the errors, and updates the ``error_count`` object.
1017
1018 :param errors: a list of error tuples (error type, message, path, line number)
1019 :returns: ``None`` if there were no errors, or
1020 a tuple of the error type and the path otherwise
1021 """
1022
1023 errors = filter_ignorelist_errors(ignorelist, errors)
1024 if not errors:
1025 return None
1026
1027 assert logger is not None
1028 output_errors(logger.error, errors)
1029
1030 if github_checks_outputter:
1031 first_output = len(error_count) == 0
1032 output_errors_github_checks(github_checks_outputter, errors, first_output)
1033
1034 for error_type, error, path, line in errors:
1035 error_count[error_type] += 1
1036
1037 return (errors[-1][0], path)
1038
1039 to_check_content = []
1040 skip = set()
1041
1042 for path in paths:
1043 abs_path = os.path.join(repo_root, path)
1044 if not os.path.exists(abs_path):
1045 skip.add(path)
1046 continue
1047
1048 if any(fnmatch.fnmatch(path, file_match) for file_match in skipped_files):
1049 skip.add(path)
1050 continue
1051
1052 errors = check_path(repo_root, path)
1053 last = process_errors(errors) or last
1054
1055 if not os.path.isdir(abs_path):
1056 to_check_content.append((repo_root, path))
1057
1058 paths = [p for p in paths if p not in skip]
1059
1060 if jobs > 1 and len(to_check_content) >= MIN_FILES_FOR_PARALLEL:
1061 pool = multiprocessing.Pool(jobs)
1062 # submit this job first, as it's the longest running
1063 all_paths_result = pool.apply_async(check_all_paths, (repo_root, paths))
1064 # each item tends to be quick, so pass things in large chunks to avoid too much IPC overhead
1065 errors_it = pool.imap_unordered(check_file_contents_apply, to_check_content, chunksize=40)
1066 pool.close()
1067 for errors in errors_it:
1068 last = process_errors(errors) or last
1069
1070 errors = all_paths_result.get()
1071 pool.join()
1072 last = process_errors(errors) or last
1073 else:
1074 for item in to_check_content:
1075 errors = check_file_contents(*item)
1076 last = process_errors(errors) or last
1077
1078 errors = check_all_paths(repo_root, paths)
1079 last = process_errors(errors) or last
1080
1081 if output_format in ("normal", "markdown"):
1082 output_error_count(error_count)
1083 if error_count:
1084 assert last is not None
1085 assert logger is not None
1086 for line in (ERROR_MSG % (last[0], last[1], last[0], last[1])).split("\n"):
1087 logger.info(line)
1088
1089 if error_count and github_checks_outputter:
1090 github_checks_outputter.output("```")
1091
1092 return sum(error_count.values())
1093
1094
1095 path_lints = [check_file_type, check_path_length, check_worker_collision, check_ahem_copy,
1096 check_mojom_js, check_tentative_directories, check_gitignore_file]
1097 file_lints = [check_regexp_line, check_parsed, check_python_ast, check_script_metadata,
1098 check_ahem_system_font, check_meta_file, check_web_features_file]
1099
1100
1101 def all_paths_lints() -> Any:
1102 paths = [check_unique_testharness_basenames,
1103 check_unique_case_insensitive_paths]
1104 # Don't break users of the lint that don't have git installed.
1105 try:
1106 subprocess.check_output(["git", "--version"])
1107 paths += [check_git_ignore]
1108 except (subprocess.CalledProcessError, FileNotFoundError):
1109 print('No git present; skipping .gitignore lint.')
1110 return paths
1111
1112
1113 if __name__ == "__main__":
1114 args = create_parser().parse_args()
1115 error_count = main(**vars(args))
1116 if error_count > 0:
1117 sys.exit(1)