|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import ast |
| 4 | +import pathlib |
| 5 | +import sys |
| 6 | +from typing import Iterable |
| 7 | + |
| 8 | +ALLOWED_NAME = "DEVICE" |
| 9 | + |
| 10 | + |
| 11 | +class DeviceKwargVisitor(ast.NodeVisitor): |
| 12 | + def __init__(self, filename: str) -> None: |
| 13 | + self.filename = filename |
| 14 | + self.errors: list[tuple[int, int, str]] = [] |
| 15 | + |
| 16 | + def visit_Call(self, node: ast.Call) -> None: |
| 17 | + for kw in node.keywords or (): |
| 18 | + if kw.arg != "device": |
| 19 | + continue |
| 20 | + |
| 21 | + # Only disallow string literals, e.g., device="cuda" or device='cpu' |
| 22 | + if isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str): |
| 23 | + self.errors.append( |
| 24 | + ( |
| 25 | + getattr(kw, "lineno", node.lineno), |
| 26 | + getattr(kw, "col_offset", node.col_offset), |
| 27 | + "device must not be a string literal like 'cuda'; use DEVICE", |
| 28 | + ) |
| 29 | + ) |
| 30 | + |
| 31 | + # Continue walking children |
| 32 | + self.generic_visit(node) |
| 33 | + |
| 34 | + |
| 35 | +def iter_python_files(paths: Iterable[str]) -> Iterable[pathlib.Path]: |
| 36 | + for p in paths: |
| 37 | + path = pathlib.Path(p) |
| 38 | + if path.is_dir(): |
| 39 | + yield from path.rglob("*.py") |
| 40 | + elif path.suffix == ".py" and path.exists(): |
| 41 | + yield path |
| 42 | + |
| 43 | + |
| 44 | +def should_check(path: pathlib.Path) -> bool: |
| 45 | + # Only check files under test/ or examples/ |
| 46 | + try: |
| 47 | + parts = path.resolve().parts |
| 48 | + except FileNotFoundError: |
| 49 | + parts = path.parts |
| 50 | + # find directory names in the path |
| 51 | + return "test" in parts or "examples" in parts |
| 52 | + |
| 53 | + |
| 54 | +def check_file(path: pathlib.Path) -> list[tuple[int, int, str]]: |
| 55 | + try: |
| 56 | + source = path.read_text(encoding="utf-8") |
| 57 | + except UnicodeDecodeError: |
| 58 | + return [] |
| 59 | + |
| 60 | + try: |
| 61 | + tree = ast.parse(source, filename=str(path)) |
| 62 | + except SyntaxError: |
| 63 | + # let other hooks catch syntax errors |
| 64 | + return [] |
| 65 | + |
| 66 | + visitor = DeviceKwargVisitor(str(path)) |
| 67 | + visitor.visit(tree) |
| 68 | + |
| 69 | + # Allow inline opt-out using marker on the same line: @ignore-device-lint |
| 70 | + lines = source.splitlines() |
| 71 | + filtered_errors: list[tuple[int, int, str]] = [] |
| 72 | + for lineno, col, msg in visitor.errors: |
| 73 | + if 1 <= lineno <= len(lines): |
| 74 | + if "@ignore-device-lint" in lines[lineno - 1]: |
| 75 | + continue |
| 76 | + filtered_errors.append((lineno, col, msg)) |
| 77 | + return filtered_errors |
| 78 | + |
| 79 | + |
| 80 | +def main(argv: list[str]) -> int: |
| 81 | + if len(argv) == 0: |
| 82 | + # pre-commit will pass file list; if not, scan the default dirs |
| 83 | + candidates = list(iter_python_files(["examples", "test"])) |
| 84 | + else: |
| 85 | + candidates = [pathlib.Path(a) for a in argv] |
| 86 | + |
| 87 | + errors_found = 0 |
| 88 | + for path in candidates: |
| 89 | + if not should_check(path): |
| 90 | + continue |
| 91 | + for lineno, col, msg in check_file(path): |
| 92 | + print(f"{path}:{lineno}:{col}: {msg}") |
| 93 | + errors_found += 1 |
| 94 | + |
| 95 | + return 1 if errors_found else 0 |
| 96 | + |
| 97 | + |
| 98 | +if __name__ == "__main__": |
| 99 | + raise SystemExit(main(sys.argv[1:])) |
0 commit comments