"""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_map.py WORKTREE CRATE_DIR MAPPING.tsv [--dry-run] MAPPING.tsv: one module per line, tab separated: the module path from the crate root (`governor/governor_methods`, the names of the `mod` declarations) or the file path below the crate directory (`src/governor/governor_methods.rs`), the new module name (one identifier), and the new doc lines of the file (`//!` text, lines separated by ` || `; replaced only while the file still has the generated header). Modules are renamed in the listed order; list a child before its parent when both change. Compile the crate afterwards: a path that the rewrite missed shows up as an error. Offline refactoring aid; not part of the product. """ import pathlib import re import subprocess import sys import textwrap sys.path.insert(0, str(pathlib.Path(__file__).parent)) from rust_modtree_lowlevel import Crate # noqa: E402 GENERATED = re.compile( r"Split out of|Moved out of|Groups the submodules|Methods of `|Defines `|Implements `|Functions: `|Items of the parent" ) MOD_LINE = re.compile(r"^(?:pub(?:\([^)]*\))? )?mod ([A-Za-z_][A-Za-z0-9_]*);$") def write(path, text): with open(path, "w", encoding="utf-8", newline=chr(10)) as handle: handle.write(text) def sort_mod_blocks(text): """Sort each run of consecutive plain `mod x;` lines (no attributes between them) by name, as rustfmt does.""" lines, out, i = text.split(chr(10)), [], 0 while i < len(lines): j = i while j < len(lines) and MOD_LINE.match(lines[j]): j += 1 if j - i > 1: out += sorted(lines[i:j], key=lambda ln: MOD_LINE.match(ln).group(1)) i = j else: out.append(lines[i]) i += 1 return chr(10).join(out) 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 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(chr(10)) end = 0 while end < len(lines) and lines[end].startswith("//!"): end += 1 if end and not GENERATED.search(chr(10).join(lines[:end])): return text # a person wrote it: keep wrapped = [part for ln in doc_lines for part in textwrap.wrap(ln, 116)] return chr(10).join(["//! " + ln for ln in wrapped] + lines[end:]) def rewrite_references(files, old, new): """Rewrite the paths that name module `old` in `files`: `old::x`, `a::old`, `mod old`, `use old`, names in `use` lists, and `#[path = "dir/old/child.rs"]` strings below the renamed directory.""" word = r"(?{new}/", out) if not fn_clash: out = use_stmt.sub(lambda m: bare.sub(new, m.group(0)) if in_list.search(m.group(0)) else m.group(0), out) if out != text: write(f, out) changed.append(f) return changed def rename_one(wt, crate_dir, rel, new, doc_lines, dry): tree = Crate(crate_dir) mod = tree.root if rel.endswith(".rs"): # a file path below the crate directory instead of a module path mod = tree.by_file.get((crate_dir / rel).resolve()) if mod is None: raise SystemExit(f"file `{rel}` is not in the module tree") else: for seg in rel.split("/"): if seg not in mod.children: raise SystemExit(f"module `{seg}` of `{rel}` not found") mod = mod.children[seg] old, f, parent_mod = mod.name, mod.file, mod.parent parent = parent_mod.file parent_text = parent.read_text(encoding="utf-8") decl = re.search(rf"(?m)^[ \t]*(?:pub(?:\([^)]*\))?\s+)?mod\s+{old}\s*;", parent_text) if not decl: raise SystemExit(f"no `mod {old};` in {parent}") new_file = f if f.name == "mod.rs" else f.with_name(new + ".rs") owned = f.parent / f.stem if f.name != "mod.rs" else f.parent print(f" {f.relative_to(wt).as_posix()} -> {new_file.relative_to(wt).as_posix()}") if dry: return [] if f.name != "mod.rs": git_mv(wt, f, new_file) if owned.is_dir(): git_mv(wt, owned, owned.with_name(new)) if f.name == "mod.rs": new_file = owned.with_name(new) / "mod.rs" # the declaration, and a `#[path = "..."]` attribute among the attributes just above it head = parent_text[: decl.start()] tail = parent_text[decl.start() :] window_start = max(0, len(head) - 700) window = head[window_start:] path_attr = None for m in re.finditer(r'#\[path\s*=\s*"([^"]+)"\]', window): path_attr = m if path_attr and (parent.parent / path_attr.group(1)).resolve() == f.resolve(): new_path = re.sub(rf"{re.escape(f.name)}$", new_file.name, path_attr.group(1)) window = window[: path_attr.start(1)] + new_path + window[path_attr.end(1) :] head = head[:window_start] + window tail = re.sub(rf"mod\s+{old}\s*;", f"mod {new};", tail, count=1) write(parent, sort_mod_blocks(head + tail)) if doc_lines: write(new_file, new_doc(new_file.read_text(encoding="utf-8"), doc_lines)) files = [p for p in crate_dir.rglob("*.rs") if "target" not in p.parts] declared = sum(len(re.findall(rf"(?