Files
hermes-agent/scripts/install_root_lint.py
alt-glitch 658f942e3d fix(paths): the lint counts import-time sys.path edits in classes, match cases and inverted guards
Class bodies and match cases run at import, and the import branch of
an 'if __name__ != "__main__"' guard is the body, not the else. Removals
(remove, pop, clear, del) change the search path too.
2026-11-07 01:17:21 -05:00

176 lines
8.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""Ratchet lint for hand-written install-root paths in production code.
* **root_from_file**: a ``__file__`` path expression that climbs to the install root
(``Path(__file__).resolve().parents[1]`` in ``hermes_cli/x.py``, ``os.path.dirname(__file__)`` in a
root module). The climb counts ``.parent``, ``.parents[n]``, ``os.path.dirname`` and
``os.path.join(..., os.pardir)``; it reaches the root when it climbs as many levels as the file is
deep. ``hermes_cli._startup_fast.project_root_str()`` owns that answer.
* **module_sys_path**: a ``sys.path`` edit that runs when the module is imported (module level, outside
functions and the ``if __name__ == "__main__"`` block).
Production code is pyproject's ``packages.find`` packages and the root ``*.py`` modules. Not caught: a
climb through a variable (``_pkg = Path(__file__).parent`` then ``_pkg.parent``).
Existing sites never fail anything. ``scripts/install_root_lint_baseline.json`` counts them per kind
and file; the lint fails only when a file's count rises above it. Run ``--update`` after removing a
site, or to record an intended one.
"""
from __future__ import annotations
import argparse
import ast
import json
import sys
import tomllib
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BASELINE = ROOT / "scripts" / "install_root_lint_baseline.json"
KINDS = ("root_from_file", "module_sys_path")
FIX_HINT = ("Call hermes_cli._startup_fast.project_root_str() for the install root, and leave sys.path to"
" the entry point. If the site is intended, run `python scripts/install_root_lint.py --update`"
" and say why in the PR.")
_SKIP_PARTS = {"tests", "__pycache__", "node_modules"}
_SAME_LEVEL = {"abspath", "realpath", "normpath", "resolve", "absolute", "Path", "PurePath", "str", "fspath"}
def production_files(root: Path = ROOT) -> list[Path]:
"""Repo-relative paths of the shipped packages' and root modules' Python files."""
find = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8-sig"))
tops = {name.split(".")[0] for name in find["tool"]["setuptools"]["packages"]["find"]["include"]}
files = [p for top in tops for p in (root / top).rglob("*.py")]
files += [p for p in root.glob("*.py") if p.stem not in {"setup", "conftest"}]
rels = {p.relative_to(root) for p in files}
return sorted(rel for rel in rels if not _SKIP_PARTS.intersection(rel.parts[:-1]))
def _name(node: ast.AST) -> str:
"""The last dotted component a call names (``os.path.dirname`` -> ``dirname``)."""
return node.attr if isinstance(node, ast.Attribute) else node.id if isinstance(node, ast.Name) else ""
def _is_pardir(node: ast.AST) -> bool:
return _name(node) == "pardir" or (isinstance(node, ast.Constant) and node.value == "..")
def climb(node: ast.AST) -> int | None:
"""Directory levels above the file that ``node`` names, or None when it is not ``__file__`` math."""
if isinstance(node, ast.Name):
return 0 if node.id == "__file__" else None
if isinstance(node, ast.Attribute) and node.attr == "parent":
base = climb(node.value)
return None if base is None else base + 1
if (isinstance(node, ast.Subscript) and isinstance(node.value, ast.Attribute) and node.value.attr == "parents"
and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, int)):
base = climb(node.value.value)
return None if base is None else base + node.slice.value + 1
if not isinstance(node, ast.Call):
return None
name = _name(node.func)
if name in {"resolve", "absolute"} and isinstance(node.func, ast.Attribute) and not node.args:
return climb(node.func.value)
if not node.args or isinstance(node.args[0], ast.Starred):
return None
base = climb(node.args[0])
if base is None:
return None
if name in _SAME_LEVEL and len(node.args) == 1:
return base
if name == "dirname" and len(node.args) == 1:
return base + 1
if name == "join" and all(_is_pardir(arg) for arg in node.args[1:]):
return base + len(node.args) - 1
return None
def _script_only_branches(test: ast.expr) -> tuple[str, str] | None:
"""For ``__name__ == "__main__"`` / ``!=``: which If branch runs only as a script, and which at import."""
if (isinstance(test, ast.Compare) and len(test.ops) == 1 and len(test.comparators) == 1
and {ast.unparse(test.left), ast.unparse(test.comparators[0])} == {"__name__", "'__main__'"}):
if isinstance(test.ops[0], ast.Eq):
return "body", "orelse"
if isinstance(test.ops[0], ast.NotEq):
return "orelse", "body"
return None
def _module_level(body: list[ast.stmt]):
"""Statements that run at import: into if/try/with/loops/match and class bodies, not into defs or a
script-only ``__main__`` branch."""
for stmt in body:
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
if isinstance(stmt, ast.If) and (branches := _script_only_branches(stmt.test)) is not None:
yield from _module_level(getattr(stmt, branches[1]))
continue
yield stmt
for field in ("body", "orelse", "finalbody", "handlers"):
yield from _module_level(getattr(stmt, field, []))
for case in getattr(stmt, "cases", []):
yield from _module_level(case.body)
_SYS_PATH_METHODS = {f"sys.path.{m}" for m in ("insert", "append", "extend", "remove", "pop", "clear")}
def _edits_sys_path(stmt: ast.stmt) -> bool:
"""A ``sys.path`` list method call, ``del`` of it or a slice, or an assignment to it or a slice."""
if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
return ast.unparse(stmt.value.func) in _SYS_PATH_METHODS
if isinstance(stmt, ast.Delete):
targets = stmt.targets
else:
targets = stmt.targets if isinstance(stmt, ast.Assign) else [getattr(stmt, "target", None)]
return any(target is not None and ast.unparse(target).split("[")[0] == "sys.path" for target in targets)
def collect(root: Path = ROOT) -> dict[str, list[str]]:
"""Per kind, ``["<rel>:<line>", ...]``."""
found: dict[str, set[tuple[str, int]]] = {kind: set() for kind in KINDS}
for rel in production_files(root):
tree = ast.parse((root / rel).read_text(encoding="utf-8-sig"))
for node in ast.walk(tree):
if isinstance(node, ast.expr) and (levels := climb(node)) is not None and levels >= len(rel.parts):
found["root_from_file"].add((rel.as_posix(), node.lineno))
for stmt in _module_level(tree.body):
if _edits_sys_path(stmt):
found["module_sys_path"].add((rel.as_posix(), stmt.lineno))
return {kind: [f"{rel}:{line}" for rel, line in sorted(sites)] for kind, sites in found.items()}
def tally(found: dict[str, list[str]]) -> dict[str, dict[str, int]]:
return {kind: dict(sorted(Counter(site.rsplit(":", 1)[0] for site in found[kind]).items())) for kind in KINDS}
def read_baseline(path: Path = BASELINE) -> dict[str, dict[str, int]]:
return json.loads(path.read_text(encoding="utf-8-sig"))
def regressions(current: dict[str, dict[str, int]], baseline: dict[str, dict[str, int]]) -> list[str]:
return [f"{kind}: {rel} ({n}, baseline {baseline.get(kind, {}).get(rel, 0)})" for kind in KINDS
for rel, n in current[kind].items() if n > baseline.get(kind, {}).get(rel, 0)]
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0])
parser.add_argument("--update", action="store_true", help="rewrite the baseline with the current sites")
args = parser.parse_args(argv)
found = collect()
current = tally(found)
if args.update:
BASELINE.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
print(f"wrote {BASELINE.relative_to(ROOT)}")
return 0
if rises := regressions(current, read_baseline()):
print("new install-root sites:\n " + "\n ".join(rises) + f"\n{FIX_HINT}", file=sys.stderr)
return 1
print(", ".join(f"{kind}: {sum(current[kind].values())}" for kind in KINDS))
return 0
if __name__ == "__main__":
raise SystemExit(main())