Files
hermes-agent/scripts/move/renames.py
alt-glitch 5e53407e2c fix(move): a path joined through a folder variable to a moved file is flagged
When a file leaves a folder that stays, the folder's name no longer counts
as moved, so the only trace of the old place in a join is the file's own
name. rewrite_imports.py flagged that name only when the join started at a
repository-root expression: tools_dir = ROOT / "tools" followed by
tools_dir / "blueprints.py" kept its old path with no flag.

A path join that ends in the name of a file that left a folder that stays
is now flagged whatever expression holds the folder. For a whole-package
move that set of files is empty, so its output is unchanged.
2026-11-16 18:09:00 +05:30

200 lines
9.4 KiB
Python

"""Module renames recorded by a move commit: the paths ``git mv`` changed, as dotted module names."""
from __future__ import annotations
import ast
import functools
import re
import subprocess
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
def current_name(name: str, renames: dict[str, str]) -> str | None:
"""The new name for ``name`` by its longest dotted prefix that is a key of ``renames``."""
parts = name.split(".")
for size in range(len(parts), 0, -1):
old = ".".join(parts[:size])
if old in renames:
return renames[old] + name[len(old):]
return None
def emptied_folders(tree: Iterable[str], paths: Iterable[tuple[str, str]]) -> frozenset[str]:
"""Folders the move took away: those above a moved file whose every tracked file moved.
``tree`` is every tracked path before the move. A folder that keeps one file stayed, however many left it.
"""
moved = {old for old, _ in paths}
kept = {str(parent) for path in tree if path not in moved for parent in PurePosixPath(path).parents}
above = {str(parent) for old in moved for parent in PurePosixPath(old).parents}
return frozenset(above - kept - {"."})
@dataclass(frozen=True)
class MovedPaths:
"""What a move took away, as path text: the files it renamed and the folders it emptied."""
paths: tuple[tuple[str, str], ...]
emptied: frozenset[str]
@functools.cached_property
def path_pattern(self) -> re.Pattern | None:
"""Path-shaped text that starts with the top-level name of a moved path; ``find_path`` checks it."""
tops = sorted({PurePosixPath(old).parts[0] for old, _ in self.paths}, key=len, reverse=True)
return re.compile(r"(?<![\w/.-])((?:" + "|".join(map(re.escape, tops)) + r")(?:/[\w.-]+)*/?)") if tops else None
@functools.cached_property
def old_tree(self) -> frozenset[str]:
"""Every old file path this move renamed and every folder it emptied."""
return frozenset(old for old, _ in self.paths) | self.emptied
def find_path(self, text: str) -> tuple[str, str] | None:
"""(old, new) for the first moved file or folder ``text`` names: a top-level file, a folder followed by a file
or folder that moved with it (``tools/registry.py``, ``tools/environments/``; never ``tools/list``), or the
whole string being a moved folder (``"tools/"``)."""
if self.path_pattern is None:
return None
if text.endswith("/") and text[:-1] in self.old_tree and "/" not in text[:-1]:
return text, self.new_path.get(text, "")
for match in self.path_pattern.finditer(text):
parts = match.group(1).rstrip("/").split("/")
for size in range(len(parts), 0, -1):
old = "/".join(parts[:size])
if old in self.old_tree and (size > 1 or old.endswith(".py")):
folder = not old.endswith(".py")
return old + "/" * folder, self.new_path.get(old + "/" * folder, "")
return None
@functools.cached_property
def new_path(self) -> dict[str, str]:
return dict(self.old_paths())
@functools.cached_property
def folders(self) -> frozenset[str]:
"""The name of the outermost file or folder each moved path lost: ``tools`` for a package that moved whole,
``model_tools.py`` for a root file, ``blueprints.py`` for a file that left a folder that stays."""
out = set()
for old, _ in self.paths:
parts = PurePosixPath(old).parts
out.add(next(parts[size - 1] for size in range(1, len(parts) + 1)
if "/".join(parts[:size]) in self.old_tree))
return frozenset(out)
@functools.cached_property
def departed_files(self) -> frozenset[str]:
"""Names of the files that left a folder that stays. The folder's own name names nothing that moved, so a
path join that ends in one of these is the only trace of the old place, whatever holds the folder."""
return frozenset(PurePosixPath(old).name for old, _ in self.paths
if PurePosixPath(old).parent != PurePosixPath(".")
and str(PurePosixPath(old).parent) not in self.emptied)
def old_paths(self) -> list[tuple[str, str]]:
"""Old -> new path text a by-path literal can carry: each moved file and each moved directory."""
pairs = {old: new for old, new in self.paths if old.endswith(".py")}
for old, new in self.paths:
old_dir, new_dir = str(PurePosixPath(old).parent), str(PurePosixPath(new).parent)
if old_dir in self.emptied and old_dir != new_dir:
pairs[old_dir + "/"] = new_dir + "/"
return sorted(pairs.items(), key=lambda item: -len(item[0]))
def renamed_paths(repo: Path, commit: str) -> list[tuple[str, str]]:
"""Old -> new paths of every file ``commit`` renamed, ``__init__.py`` files paired by their directory.
Git pairs renames by content, so two empty or identical ``__init__.py`` files can be paired across
packages, and git never pairs empty files at all. Each one is paired through the move of its
directory's other files instead; git's own pair is kept only when that directory has no other file.
"""
status = git(repo, "diff", "-M", "--name-status", f"{commit}^", commit)
moved, inits, deleted, added = [], [], [], set()
for line in status.splitlines():
kind, *paths = line.split("\t")
if kind.startswith("R") and PurePosixPath(paths[0]).name == "__init__.py":
inits.append((paths[0], paths[1]))
deleted.append(paths[0])
added.add(paths[1])
elif kind.startswith("R"):
moved.append((paths[0], paths[1]))
elif kind == "D":
deleted.append(paths[0])
elif kind == "A":
added.add(paths[0])
directories = {}
for old, new in moved:
old_dir, new_dir = PurePosixPath(old).parent, PurePosixPath(new).parent
while str(old_dir) not in (".", str(new_dir)) and old_dir.name == new_dir.name:
directories.setdefault(str(old_dir), str(new_dir))
old_dir, new_dir = old_dir.parent, new_dir.parent
git_pairs = dict(inits)
for old in deleted:
if PurePosixPath(old).name != "__init__.py":
continue
old_dir = str(PurePosixPath(old).parent)
new = f"{directories[old_dir]}/__init__.py" if old_dir in directories else git_pairs.get(old)
if new in added:
moved.append((old, new))
return moved
def moved_modules(repo: Path, commit: str) -> dict[str, tuple[str, str]]:
"""Old dotted name -> (new dotted name, new path) of every ``.py`` file ``commit`` renamed."""
old_packages = _packages(repo, f"{commit}^")
new_packages = _packages(repo, commit)
modules = {}
for old_path, new_path in renamed_paths(repo, commit):
if old_path.endswith(".py") and new_path.endswith(".py"):
old, new = _module_name(old_path, old_packages), _module_name(new_path, new_packages)
if old != new:
modules[old] = (new, new_path)
return modules
def module_renames(repo: Path, commit: str) -> dict[str, str]:
"""Old -> new dotted module names for the ``.py`` files ``commit`` renamed.
A moved package maps once by its prefix; its modules that kept their place under it add no entry.
"""
renames = {old: new for old, (new, _) in moved_modules(repo, commit).items()}
for old in sorted(renames, key=len, reverse=True):
others = {key: value for key, value in renames.items() if key != old}
if current_name(old, others) == renames[old]:
del renames[old]
return renames
def config_keys(root: Path) -> frozenset[str]:
"""Every dotted key path of ``DEFAULT_CONFIG`` (``agent``, ``agent.max_turns``, ...), read by AST."""
keys: set[str] = set()
for path in git(root, "ls-files", "*hermes_cli/config_defaults.py").split():
body = ast.parse((root / path).read_text(encoding="utf-8-sig")).body
pending = [("", node.value) for node in body if isinstance(node, ast.Assign)
and any(getattr(target, "id", None) == "DEFAULT_CONFIG" for target in node.targets)]
while pending:
prefix, value = pending.pop()
for key, item in zip(getattr(value, "keys", ()), getattr(value, "values", ())):
if isinstance(key, ast.Constant) and isinstance(key.value, str):
keys.add(prefix + key.value)
pending.append((f"{prefix}{key.value}.", item))
return frozenset(keys)
def git(repo: Path, *args: str) -> str:
return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True,
text=True, timeout=120).stdout
def _packages(repo: Path, commit: str) -> set[str]:
files = git(repo, "ls-tree", "-r", "--name-only", commit).splitlines()
return {str(PurePosixPath(f).parent) for f in files if PurePosixPath(f).name == "__init__.py"}
def _module_name(path: str, packages: set[str]) -> str:
"""Dotted name of a ``.py`` path; the import root is the nearest parent directory without ``__init__.py``."""
parts = list(PurePosixPath(path).with_suffix("").parts)
if parts[-1] == "__init__":
parts.pop()
root = len(parts) - 1
while root > 0 and "/".join(parts[:root]) in packages:
root -= 1
return ".".join(parts[root:])