"""Rename Rust modules to what they hold, with `git mv`, and update the `mod` declaration, the `#[path]` attribute, the paths that name the module and the doc comment of the file (STRA-338 debt (c), names). Usage: python scripts/dev/rename_module.py WORKTREE CRATE_DIR MAPPING.tsv [--dry-run] MAPPING.tsv: one module per line, tab separated: `old module path below src/` (for example `governor/governor_methods`), the new module name (one identifier), and the new doc lines of the file (`//!` text, lines separated by ` || `). Modules are renamed in the listed order; list a child before its parent when both change. Offline refactoring aid; not part of the product. """ import pathlib import re import subprocess import sys IDENT = r"[A-Za-z_][A-Za-z0-9_]*" GENERATED = re.compile(r"Split out of|Moved out of|Groups the submodules|Methods of `|Defines `|Implements `|Functions: `|Items of the parent") def git_mv(wt, src, dst): dst.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["git", "mv", str(src.relative_to(wt)), str(dst.relative_to(wt))], cwd=wt, check=True) def module_files(src_dir, rel): """(file, owned dir or None) of the module `rel` (`a/b` -> a/b.rs or a/b/mod.rs).""" base = src_dir / rel if (base.with_suffix(".rs")).is_file(): f = base.with_suffix(".rs") return f, (base if base.is_dir() else None) if (base / "mod.rs").is_file(): return base / "mod.rs", base raise SystemExit(f"module not found: {rel}") def parent_file(src_dir, rel): parts = rel.split("/") if len(parts) == 1: for name in ("lib.rs", "main.rs"): if (src_dir / name).is_file(): return src_dir / name parent = "/".join(parts[:-1]) f, _ = module_files(src_dir, parent) return f def new_doc(text, doc_lines): """The file text with its leading `//!` block replaced by `doc_lines`, when that block is the generated one.""" lines = text.split("\n") end = 0 while end < len(lines) and lines[end].startswith("//!"): end += 1 block = "\n".join(lines[:end]) if end and not GENERATED.search(block): return text # a person wrote it: keep body = "\n".join(lines[end:]) return "\n".join("//! " + ln for ln in doc_lines) + "\n" + body def rewrite_references(files, old, new): changed = [] ref = [ (re.compile(rf"\b{old}::"), f"{new}::"), (re.compile(rf"::{old}\b(?!\s*\()"), f"::{new}"), (re.compile(rf"\bmod\s+{old}\b"), f"mod {new}"), (re.compile(rf"\buse\s+{old}\b"), f"use {new}"), ] use_stmt = re.compile(r"(?ms)^\s*(?:pub(?:\([^)]*\))?\s+)?use\s[^;]*;") for f in files: text = f.read_text(encoding="utf-8") out = text for rx, repl in ref: out = rx.sub(repl, out) def in_use(m): return re.sub(rf"(?#\[path\s*=\s*\"(?P[^\"]+)\"\]\s*\n\s*)?(?Ppub(?:\([^)]*\))?\s+)?mod\s+{old}\s*;", parent_text ) if not decl: raise SystemExit(f"no `mod {old};` in {parent}") target_dir = f.parent new_file = f.with_name(new + ".rs") if f.name != "mod.rs" else f print(f" {f.relative_to(wt).as_posix()} -> {new_file.relative_to(wt).as_posix()}") if decl.group("path"): path = decl.group("path") new_path = re.sub(rf"{re.escape(old)}(\.rs)$", rf"{new}\1", path) if path.endswith(old + ".rs") else path new_file = (parent.parent / new_path).resolve() if path.endswith(old + ".rs") else new_file f_actual = (parent.parent / path).resolve() if f_actual != f.resolve(): raise SystemExit(f"{path} does not name {f}") if dry: return [] if f.name != "mod.rs": git_mv(wt, f, new_file) if owned is not None and owned.is_dir(): git_mv(wt, owned, owned.with_name(new)) else: git_mv(wt, owned, owned.with_name(new)) new_file = owned.with_name(new) / "mod.rs" text = parent_text repl = decl.group(0) repl = re.sub(rf"\bmod\s+{old}\b", f"mod {new}", repl) if decl.group("path"): repl = repl.replace(decl.group("path"), new_path) parent.write_text(text.replace(decl.group(0), repl, 1), encoding="utf-8", newline="\n") body = new_file.read_text(encoding="utf-8") if doc_lines: new_file.write_text(new_doc(body, doc_lines), encoding="utf-8", newline="\n") files = [p for p in crate_dir.rglob("*.rs") if "target" not in p.parts] return rewrite_references(files, old, new) def main(): wt, crate_dir, mapping = (pathlib.Path(a).resolve() for a in sys.argv[1:4]) dry = "--dry-run" in sys.argv for line in mapping.read_text(encoding="utf-8").splitlines(): if not line.strip() or line.startswith("#"): continue rel, new, *doc = line.split("\t") doc_lines = [d.strip() for d in doc[0].split(" || ")] if doc and doc[0].strip() else [] rename_one(wt, crate_dir, rel, new, doc_lines, dry) if __name__ == "__main__": main()