The ratchet read a move as one old file becoming one new file. When several modules are folded into one, each with its own MOVES key, two things read as new code: - A line that names the new module was spelled back as the first key only, so an import that had named one of the other old modules no longer matched its base line. Every old name of the file is now spelled as the first one, on both sides. - An old module that leaves a generated file at its path was dropped from the comparison as generated, so the functions that moved out of it had no base unit to match. Such a file now reads as deleted. A fold of tools/ modules otherwise fails PLC0415 once per function-level import it only renamed.
220 lines
8.5 KiB
Python
220 lines
8.5 KiB
Python
"""Git plumbing: which files changed between two trees, and their contents on either side.
|
|
|
|
A tree is a revision (``"abc123"``) or ``None`` for the working tree. Both sides are read
|
|
through the same functions so base and head are measured identically.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import subprocess
|
|
from dataclasses import dataclass
|
|
from pathlib import Path, PurePosixPath
|
|
|
|
from hermes_agent.compat.paths import PathMoves, moves_from_source
|
|
|
|
|
|
def git(repo: Path, *args: str, check: bool = True) -> str:
|
|
proc = subprocess.run(
|
|
["git", *args],
|
|
cwd=repo,
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
stdin=subprocess.DEVNULL,
|
|
timeout=120,
|
|
check=False,
|
|
)
|
|
if check and proc.returncode != 0:
|
|
raise RuntimeError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
|
|
return proc.stdout
|
|
|
|
|
|
def repo_root(start: Path) -> Path:
|
|
return Path(git(start, "rev-parse", "--show-toplevel").strip())
|
|
|
|
|
|
def resolve_rev(repo: Path, rev: str) -> str:
|
|
return git(repo, "rev-parse", "--verify", f"{rev}^{{commit}}").strip()
|
|
|
|
|
|
def resolve_tree(repo: Path, rev: str) -> str:
|
|
"""A head may be any tree-ish: a commit, or the index's tree from ``git write-tree``."""
|
|
return git(repo, "rev-parse", "--verify", f"{rev}^{{tree}}").strip()
|
|
|
|
|
|
def commit_or_none(repo: Path, rev: str) -> str | None:
|
|
"""``rev`` as a commit sha, or None when it does not name a commit (a tree, a missing ref)."""
|
|
out = git(repo, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}", check=False)
|
|
return out.strip() or None
|
|
|
|
|
|
def default_base(repo: Path, tip: str = "HEAD") -> str:
|
|
"""Merge-base of ``tip`` with origin/main (local runs); CI passes ``--base`` explicitly."""
|
|
for ref in ("origin/main", "main"):
|
|
out = git(repo, "merge-base", tip, ref, check=False).strip()
|
|
if out:
|
|
return out
|
|
raise RuntimeError("no merge-base with origin/main or main; pass --base")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Change:
|
|
status: str # A, M, D, R
|
|
old: str | None
|
|
new: str | None
|
|
|
|
|
|
def _parse_name_status(out: str) -> list[Change]:
|
|
fields = out.split("\0")
|
|
changes: list[Change] = []
|
|
i = 0
|
|
while i < len(fields) and fields[i]:
|
|
code = fields[i][0]
|
|
if code in "RC":
|
|
old, new = fields[i + 1], fields[i + 2]
|
|
changes.append(Change("R" if code == "R" else "A", old if code == "R" else None, new))
|
|
i += 3
|
|
continue
|
|
path = fields[i + 1]
|
|
if code == "D":
|
|
changes.append(Change("D", path, None))
|
|
elif code == "A":
|
|
changes.append(Change("A", None, path))
|
|
else:
|
|
changes.append(Change("M", path, path))
|
|
i += 2
|
|
return changes
|
|
|
|
|
|
MOVES_FILE = "hermes_agent/compat/moves.py"
|
|
GENERATED_BLOCK = ("# BEGIN shims (generated by scripts/move/generate_shims.py; do not edit)\n", "# END shims\n")
|
|
|
|
|
|
def generated_files(repo: Path, tree: str | None) -> set[str]:
|
|
"""Paths ``scripts/move/generate_shims.py`` writes, as the ``.gitattributes`` of ``tree`` lists them.
|
|
|
|
They are generated old-path files (shims and byte copies of moved files), not code anyone wrote
|
|
in this change, so they are not judged.
|
|
"""
|
|
text = read_file(repo, tree, ".gitattributes") or ""
|
|
block = text.partition(GENERATED_BLOCK[0])[2].partition(GENERATED_BLOCK[1])[0]
|
|
return {line.split()[0].removeprefix("/") for line in block.splitlines() if line.strip()}
|
|
|
|
|
|
def tree_moves(repo: Path, tree: str | None) -> dict[str, str]:
|
|
"""The ``MOVES`` table as ``tree`` holds it (old module name -> current name)."""
|
|
return moves_from_source(read_file(repo, tree, MOVES_FILE))
|
|
|
|
|
|
def _module(path: str) -> str:
|
|
return path.removesuffix(".py").removesuffix("/__init__").replace("/", ".")
|
|
|
|
|
|
def module_moves(repo: Path, tree: str | None, changes: list[Change]) -> dict[str, str]:
|
|
"""Old module name -> current name: every Python file ``changes`` renames, then ``tree``'s ``MOVES``.
|
|
|
|
Most moved modules get no ``MOVES`` key, and a line that only names one by its new name is still the
|
|
base's line. A root-level module is left out: its bare name is also an ordinary word in code.
|
|
"""
|
|
renames = {_module(c.old): _module(c.new) for c in changes
|
|
if c.status == "R" and c.old and c.new and c.old.endswith(".py") and "/" in c.new.removesuffix("/__init__.py")}
|
|
return renames | tree_moves(repo, tree)
|
|
|
|
|
|
def _pair_moves(changes: list[Change], original, base_files: set[str]) -> list[Change]:
|
|
"""Pair each new file with the base file the head's ``MOVES`` says it was.
|
|
|
|
A move leaves a generated file at the old path, so git sees an add plus a modify and never pairs
|
|
them. A file that existed on the base keeps its own path; the file left behind reads as new.
|
|
"""
|
|
pairs = {c.new: original(c.new) for c in changes
|
|
if c.new is not None and c.status != "M" and original(c.new) != c.new
|
|
and original(c.new) in base_files and c.old != original(c.new)}
|
|
if not pairs:
|
|
return changes
|
|
claimed = set(pairs.values())
|
|
paired: list[Change] = []
|
|
for c in changes:
|
|
if c.new in pairs:
|
|
paired.append(Change("R", pairs[c.new], c.new))
|
|
if c.old is not None and c.old not in claimed:
|
|
paired.append(Change("D", c.old, None))
|
|
elif c.old in claimed:
|
|
if c.new is not None:
|
|
paired.append(Change("A", None, c.new))
|
|
else:
|
|
paired.append(c)
|
|
return paired
|
|
|
|
|
|
def changed_files(repo: Path, base: str, head: str | None, *diff_args: str) -> list[Change]:
|
|
args = ["diff", "--name-status", "-M", *diff_args, "-z", "--no-color", base]
|
|
if head is not None:
|
|
args.append(head)
|
|
changes = _parse_name_status(git(repo, *args))
|
|
if head is None:
|
|
untracked = git(repo, "ls-files", "--others", "--exclude-standard", "-z")
|
|
changes.extend(Change("A", None, p) for p in untracked.split("\0") if p)
|
|
moves = tree_moves(repo, head)
|
|
if moves:
|
|
changes = _pair_moves(changes, PathMoves(moves).original,
|
|
set(tracked_files(repo, base)) - generated_files(repo, base))
|
|
generated, was_generated = generated_files(repo, head), generated_files(repo, base)
|
|
# A generated file is not judged. Where it replaced a real file, that file's code left the path:
|
|
# it reads as deleted, so the units that moved out of it keep their caps and violations.
|
|
return [Change("D", c.old, None) if c.new in generated else c for c in changes
|
|
if c.new not in generated or (c.status == "M" and c.old not in was_generated)]
|
|
|
|
|
|
def read_file(repo: Path, tree: str | None, path: str) -> str | None:
|
|
if tree is None:
|
|
try:
|
|
return (repo / path).read_text(encoding="utf-8-sig", errors="replace")
|
|
except (FileNotFoundError, IsADirectoryError):
|
|
return None
|
|
proc = subprocess.run(
|
|
["git", "show", f"{tree}:{path}"],
|
|
cwd=repo,
|
|
capture_output=True,
|
|
stdin=subprocess.DEVNULL,
|
|
timeout=60,
|
|
check=False,
|
|
)
|
|
if proc.returncode != 0:
|
|
return None
|
|
# Same decoding as the working-tree read: a BOM must not make the two sides disagree.
|
|
return proc.stdout.decode("utf-8-sig", errors="replace")
|
|
|
|
|
|
def tracked_files(repo: Path, tree: str | None) -> list[str]:
|
|
if tree is None:
|
|
return [p for p in git(repo, "ls-files", "-z").split("\0") if p]
|
|
return [p for p in git(repo, "ls-tree", "-r", "--name-only", "-z", tree).split("\0") if p]
|
|
|
|
|
|
def first_party_names(repo: Path, tree: str | None) -> frozenset[str]:
|
|
"""Top-level import names a tree ships: ``NAME/__init__.py`` or ``NAME.py`` at its root."""
|
|
names = set()
|
|
for path in tracked_files(repo, tree):
|
|
parts = PurePosixPath(path).parts
|
|
if len(parts) == 1 and path.endswith(".py"):
|
|
names.add(path[:-3])
|
|
elif len(parts) == 2 and parts[1] == "__init__.py":
|
|
names.add(parts[0])
|
|
return frozenset(names)
|
|
|
|
|
|
def known_env_names(repo: Path, tree: str | None) -> set[str]:
|
|
"""Every HERMES_* literal in non-test Python of a tree (the HX002 allow set)."""
|
|
args = ["grep", "-h", "-o", "-I", "-E", r"HERMES_[A-Z0-9_]+"]
|
|
if tree is not None:
|
|
args.append(tree)
|
|
args += ["--", "*.py", ":!tests/**", ":!**/tests/**"]
|
|
out = git(repo, *args, check=False)
|
|
names = set()
|
|
for line in out.splitlines():
|
|
# `git grep <tree>` prefixes "<tree>:" even with -h on some versions.
|
|
names.add(line.rsplit(":", 1)[-1])
|
|
return names
|