-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcheck_no_line_number_snippets.py
73 lines (63 loc) · 2.08 KB
/
check_no_line_number_snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Purpose: To ensure that no docs snippets use the file and line number convention,
only the named snippets convention.
"""
import pathlib
import re
import shutil
import subprocess
import sys
ITEMS_IGNORED_FROM_LINE_NUMBER_SNIPPET_CHECKER = {
"docs/prepare_to_build_docs.sh",
}
EXCLUDED_FILENAMES_PATTERN = re.compile(r"node_modules", re.IGNORECASE)
def check_dependencies(*deps: str) -> None:
for dep in deps:
if not shutil.which(dep):
raise Exception(f"Must have `{dep}` installed in PATH to run {__file__}") # noqa: TRY002, TRY003
def run_grep(target_dir: pathlib.Path) -> list[str]:
try:
res = subprocess.run( # noqa: PLW1510
[
"grep",
"--recursive",
"--files-with-matches",
"--ignore-case",
"--word-regexp",
"--regexp",
r"file=",
str(target_dir),
],
text=True,
capture_output=True,
)
except subprocess.CalledProcessError as e:
raise RuntimeError( # noqa: TRY003
f"Command {e.cmd} returned with error (code {e.returncode}): {e.output}"
) from e
return res.stdout.splitlines()
def main() -> None:
check_dependencies("grep")
project_root = pathlib.Path(__file__).parent.parent.parent
docs_dir = project_root / "docs"
assert docs_dir.exists()
grep_output = run_grep(docs_dir)
grep_output = list(
filter(
lambda filename: EXCLUDED_FILENAMES_PATTERN.match(filename),
grep_output,
)
)
excluded_documents = {
project_root / file_path for file_path in ITEMS_IGNORED_FROM_LINE_NUMBER_SNIPPET_CHECKER
}
new_violations = set(grep_output).difference(excluded_documents)
if new_violations:
print(
f"[ERROR] Found {len(new_violations)} snippets using file and line number syntax. Please use named snippet syntax:" # noqa: E501
)
for line in new_violations:
print(line)
sys.exit(1)
if __name__ == "__main__":
main()