Files
leleka/scripts/dev/rename_module_map.py
T

167 lines
7.6 KiB
Python

"""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"(?<![A-Za-z0-9_])"
ref = [
(re.compile(rf"{word}{old}::(?!<)"), f"{new}::"),
(re.compile(rf"::{old}(?![A-Za-z0-9_:])(?!\s*\()"), f"::{new}"),
(re.compile(rf"{word}mod\s+{old}(?![A-Za-z0-9_])"), f"mod {new}"),
(re.compile(rf"{word}use\s+{old}(?![A-Za-z0-9_])"), f"use {new}"),
]
use_stmt = re.compile(r"(?ms)^\s*(?:pub(?:\([^)]*\))?\s+)?use\s[^;]*;")
# a function or type of the same name as the module: names inside `use` lists are not safe to rewrite blindly
clash = re.compile(rf"{word}(?:fn|struct|enum|trait|const|static|type)\s+{old}(?![A-Za-z0-9_])")
fn_clash = any(clash.search(f.read_text(encoding="utf-8")) for f in files)
in_list = re.compile(rf"[{{,\s]{old}(?![A-Za-z0-9_])")
bare = re.compile(rf"(?<![A-Za-z0-9_:]){old}(?![A-Za-z0-9_:(])")
changed = []
if fn_clash:
ref = [ref[0], ref[2], ref[3]]
print(f" `{old}` is also a function or type name: only `{old}::` paths and `mod`/`use` heads are rewritten; fix the rest by hand")
for f in files:
text = f.read_text(encoding="utf-8")
out = text
for rx, repl in ref:
out = rx.sub(repl, out)
out = re.sub(rf'(#\[path\s*=\s*"(?:[^"]*/)?){old}/', rf"\g<1>{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"(?<![A-Za-z0-9_])mod\s+{old}\s*;", p.read_text(encoding="utf-8"))) for p in files)
if declared:
# the name is also used by other modules: rewrite only the parent and the files of the renamed module itself
inside = new_file.parent / new if new_file.name != "mod.rs" else new_file.parent
files = [parent, new_file] + (list(inside.rglob("*.rs")) if inside.is_dir() else [])
print(f" `{old}` is still declared elsewhere: rewriting {len(files)} files only")
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()