#!/usr/bin/env python3 """Check local function-annotation conventions that Ruff does not cover.""" from __future__ import annotations import argparse import ast from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path from utils.paths import CODE_ROOT DEFAULT_EXCLUDED_DIRECTORIES = frozenset({".venv", "__pycache__"}) @dataclass(frozen=True) class Finding: """Describe one source-level convention violation.""" path: Path line: int message: str def render(self) -> str: """Render the finding in a compiler-friendly format.""" return f"{self.path}:{self.line}: {self.message}" def _function_findings( path: Path, node: ast.FunctionDef | ast.AsyncFunctionDef, ) -> Iterable[Finding]: arguments = [ *node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs, ] for argument in arguments: if argument.arg in {"self", "cls"}: continue if argument.annotation is None: yield Finding( path, argument.lineno, f"{node.name}() argument {argument.arg!r} lacks an annotation", ) for argument in (node.args.vararg, node.args.kwarg): if argument is not None and argument.annotation is None: yield Finding( path, argument.lineno, f"{node.name}() argument {argument.arg!r} lacks an annotation", ) if node.returns is None: yield Finding( path, node.lineno, f"{node.name}() lacks a return annotation", ) def check_path(path: Path) -> list[Finding]: """Return convention violations found in one Python source file.""" try: tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) except (OSError, SyntaxError) as error: line = error.lineno if isinstance(error, SyntaxError) else 1 return [Finding(path, line or 1, f"cannot parse source: {error}")] findings: list[Finding] = [] for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): findings.extend(_function_findings(path, node)) return findings def _source_paths(values: Sequence[Path]) -> list[Path]: if values: return sorted( path for path in values if path.suffix == ".py" and path.is_file() ) return sorted( path for path in CODE_ROOT.rglob("*.py") if DEFAULT_EXCLUDED_DIRECTORIES.isdisjoint( path.relative_to(CODE_ROOT).parts ) ) def build_parser() -> argparse.ArgumentParser: """Build the command-line parser.""" parser = argparse.ArgumentParser(description=__doc__) _ = parser.add_argument("paths", nargs="*", type=Path) return parser def main(argv: Sequence[str] | None = None) -> int: """Check selected files and return a nonzero status for violations.""" args = build_parser().parse_args(argv) findings = [ finding for path in _source_paths(args.paths) for finding in check_path(path) ] for finding in findings: print(finding.render()) if findings: print(f"Found {len(findings)} code-convention violation(s).") return 1 print("Code signature conventions pass.") return 0 if __name__ == "__main__": raise SystemExit(main())