|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import pathlib |
| 4 | +import tomllib |
| 5 | + |
| 6 | +REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent |
| 7 | +ROOT_SKIP_DIRS = { |
| 8 | + ".git", |
| 9 | + ".venv", |
| 10 | + ".uv_cache", |
| 11 | + ".uv-cache", |
| 12 | + ".uv_tools", |
| 13 | + ".uv-tools", |
| 14 | + ".cache", |
| 15 | + "node_modules", |
| 16 | + ".next", |
| 17 | +} |
| 18 | +RECURSIVE_SKIP_DIRS = {"__pycache__", ".pytest_cache"} |
| 19 | + |
| 20 | + |
| 21 | +def load_config() -> tuple[int, set[str]]: |
| 22 | + pyproject = REPO_ROOT / "pyproject.toml" |
| 23 | + with open(pyproject, "rb") as f: |
| 24 | + data = tomllib.load(f) |
| 25 | + cfg = data.get("tool", {}).get("file_length", {}) |
| 26 | + max_lines = cfg.get("max_lines", 500) |
| 27 | + exclude = set(cfg.get("exclude", [])) |
| 28 | + return max_lines, exclude |
| 29 | + |
| 30 | + |
| 31 | +def main() -> int: |
| 32 | + max_lines, exclude = load_config() |
| 33 | + violations: list[tuple[pathlib.Path, int]] = [] |
| 34 | + |
| 35 | + for path in REPO_ROOT.rglob("*.py"): |
| 36 | + rel = path.relative_to(REPO_ROOT) |
| 37 | + parts = rel.parts |
| 38 | + if parts[0] in ROOT_SKIP_DIRS: |
| 39 | + continue |
| 40 | + if any(part in RECURSIVE_SKIP_DIRS for part in parts[:-1]): |
| 41 | + continue |
| 42 | + if rel.as_posix() in exclude: |
| 43 | + continue |
| 44 | + line_count = len(path.read_text(encoding="utf-8", errors="ignore").splitlines()) |
| 45 | + if line_count > max_lines: |
| 46 | + violations.append((rel, line_count)) |
| 47 | + |
| 48 | + if violations: |
| 49 | + print(f"File length check failed: {len(violations)} file(s) exceed {max_lines} lines") |
| 50 | + for rel_path, count in sorted(violations): |
| 51 | + print(f" {rel_path}: {count} lines") |
| 52 | + print( |
| 53 | + "Refactor large files into smaller modules, " |
| 54 | + "or add to [tool.file_length] exclude in pyproject.toml." |
| 55 | + ) |
| 56 | + return 1 |
| 57 | + |
| 58 | + print(f"File length check passed (all files <= {max_lines} lines).") |
| 59 | + return 0 |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + raise SystemExit(main()) |
0 commit comments