Files
leleka/scripts/dev/rename_module.py
T

106 lines
4.9 KiB
Python

"""Rename a Rust module file to what it contains (STRA-338 debt (c), names), keeping history and every path in order.
Usage: python scripts/dev/rename_module.py CRATE_DIR OLD_FILE NEW_NAME [--apply]
CRATE_DIR the crate directory (holds src/)
OLD_FILE the module file to rename, as a path (`src/a/b/old_name.rs`) relative to CRATE_DIR or absolute
NEW_NAME the new module name (no `.rs`)
Without --apply the plan is printed. With --apply the tool
* `git mv`s the file (and the directory `old_name/` that holds its children, when one exists),
* rewrites the `mod old_name;` declaration of the parent (and the file name of its `#[path = "..."]`),
* replaces the identifier `old_name` by `NEW_NAME` in the parent file and every `.rs` file below the parent's directory (all of the crate
with --crate-wide; every whole-word use of the name with --any-ident) that names it as a path segment
(`old_name::x`, `::old_name`, `use ..{old_name, ..}`, `mod old_name`), and the old file name inside `#[path]` strings.
It never touches a file outside CRATE_DIR; docs that quote the old name are listed so they can be updated by hand.
Offline refactoring aid, not part of the product. Compile afterwards (`cargo check --workspace --all-targets`).
"""
import os
import pathlib
import re
import subprocess
import sys
sys.path.insert(0, str(pathlib.Path(__file__).parent))
from rust_modtree import Crate # noqa: E402
def git(root, *args):
subprocess.run(["git", "-C", str(root), *args], check=True)
def main():
crate_dir = pathlib.Path(sys.argv[1]).resolve()
old_file = pathlib.Path(sys.argv[2])
old_file = (old_file if old_file.is_absolute() else crate_dir / old_file).resolve()
new_name = sys.argv[3]
apply = "--apply" in sys.argv
old_name = old_file.stem
crate = Crate(crate_dir)
mod = crate.by_file.get(old_file)
if mod is None or mod.parent is None:
sys.exit(f"{old_file} is not a module file of {crate_dir}")
if old_file.name in ("mod.rs", "lib.rs", "main.rs"):
sys.exit("a mod.rs / lib.rs / main.rs file is named by its directory")
new_file = old_file.with_name(new_name + ".rs")
old_dir, new_dir = old_file.with_suffix(""), new_file.with_suffix("")
if new_file.exists():
sys.exit(f"{new_file} exists")
name = re.escape(old_name)
# only the uses of the name as a module: `old::x`, `mod old`, `super::old;` (not a function, method or field `old`)
ident = re.compile(
rf"(?<![A-Za-z0-9_.]){name}(?=::)|(?<=mod ){name}(?![A-Za-z0-9_])|(?<=super::){name}(?![A-Za-z0-9_(])"
)
if "--any-ident" in sys.argv: # the name is unique enough: every whole-word use (also inside `use a::{b, name}`)
ident = re.compile(rf"(?<![A-Za-z0-9_]){name}(?![A-Za-z0-9_])")
path_name = re.compile(rf'(#\[path\s*=\s*"[^"]*?){re.escape(old_name)}(\.rs")')
path_dir = re.compile(rf'(#\[path\s*=\s*"[^"]*?){re.escape(old_name)}(/[^"]*")')
print(f"{old_file.relative_to(crate_dir)} -> {new_file.name} (module `{old_name}` of {mod.parent.file.name})")
touched = []
parent_file = mod.parent.file
scope_dir = parent_file.parent if parent_file.name in ("mod.rs", "lib.rs", "main.rs") else parent_file.with_suffix("")
scope = [parent_file] + (sorted(scope_dir.rglob("*.rs")) if scope_dir.is_dir() else [])
if "--crate-wide" in sys.argv:
scope = sorted(crate_dir.rglob("*.rs"))
for file in dict.fromkeys(scope):
if "target" in file.parts:
continue
text = file.read_text(encoding="utf-8")
if old_name not in text:
continue
new_text = path_name.sub(rf"\g<1>{new_name}\g<2>", text)
new_text = path_dir.sub(rf"\g<1>{new_name}\g<2>", new_text)
new_text = ident.sub(new_name, new_text)
if new_text != text:
touched.append((file, text, new_text))
for file, text, new_text in touched:
hits = len(ident.findall(text)) + len(path_name.findall(text)) + len(path_dir.findall(text))
print(f" rewrite {file.relative_to(crate_dir)}: {hits} occurrence(s)")
if not apply:
return
root = subprocess.run(
["git", "-C", str(crate_dir), "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True
).stdout.strip()
git(root, "mv", str(old_file), str(new_file))
if old_dir.is_dir():
git(root, "mv", str(old_dir), str(new_dir))
for file, text, new_text in touched:
if file == old_file:
file = new_file
elif old_dir in file.parents:
file = new_dir / file.relative_to(old_dir)
with open(file, "w", encoding="utf-8", newline="\n") as handle:
handle.write(new_text)
docs = subprocess.run(
["git", "-C", root, "grep", "-l", "-F", old_name + ".rs", "--", "docs", "scripts", "*.md", "*.json"],
capture_output=True, text=True,
).stdout.split()
if docs:
print("files that still quote the old file name:", *docs, sep="\n ")
if __name__ == "__main__":
main()