Debian Codegraph @

tools/linter.py

raw
1 import os
2 import subprocess
3 import sys
4 from argparse import ArgumentParser
5
6 CWD = os.path.abspath(os.path.dirname(__file__))
7
8
9 class DiffLinter:
10 def __init__(self) -> None:
11 self.repository_root = os.path.realpath(os.path.join(CWD, ".."))
12
13 def run_ruff(self, fix: bool) -> tuple[int, str]:
14 """
15 Original Author: Josh Wilson (@person142)
16 Source:
17 https://github.com/scipy/scipy/blob/main/tools/lint_diff.py
18 Unlike pycodestyle, ruff by itself is not capable of limiting
19 its output to the given diff.
20 """
21 print("Running Ruff Check...")
22 command = ["ruff", "check"]
23 if fix:
24 command.append("--fix")
25
26 res = subprocess.run(
27 command,
28 stdout=subprocess.PIPE,
29 cwd=self.repository_root,
30 encoding="utf-8",
31 )
32 return res.returncode, res.stdout
33
34 def run_cython_lint(self) -> tuple[int, str]:
35 print("Running cython-lint...")
36 command = ["cython-lint", "--no-pycodestyle", "numpy"]
37
38 res = subprocess.run(
39 command,
40 stdout=subprocess.PIPE,
41 cwd=self.repository_root,
42 encoding="utf-8",
43 )
44 return res.returncode, res.stdout
45
46 def run_lint(self, fix: bool) -> None:
47
48 # Ruff Linter
49 retcode, ruff_errors = self.run_ruff(fix)
50 ruff_errors and print(ruff_errors)
51
52 if retcode:
53 sys.exit(retcode)
54
55 # C API Borrowed-ref Linter
56 retcode, c_API_errors = self.run_check_c_api()
57 c_API_errors and print(c_API_errors)
58
59 if retcode:
60 sys.exit(retcode)
61
62 # Cython Linter
63 retcode, cython_errors = self.run_cython_lint()
64 cython_errors and print(cython_errors)
65
66 sys.exit(retcode)
67
68 def run_check_c_api(self) -> tuple[int, str]:
69 """Run C-API borrowed-ref checker"""
70 print("Running C API borrow-reference linter...")
71 borrowed_ref_script = os.path.join(
72 self.repository_root, "tools", "ci", "check_c_api_usage.py"
73 )
74 borrowed_res = subprocess.run(
75 [sys.executable, borrowed_ref_script],
76 cwd=self.repository_root,
77 stdout=subprocess.PIPE,
78 stderr=subprocess.STDOUT,
79 text=True,
80 check=False,
81 )
82
83 # Exit with non-zero if C API Check fails
84 return borrowed_res.returncode, borrowed_res.stdout
85
86
87 if __name__ == "__main__":
88 parser = ArgumentParser()
89 args = parser.parse_args()
90
91 DiffLinter().run_lint(fix=False)