"""Replace `#[path = "x.rs"] mod name;` by the directory layout (`parent/name.rs`) with `git mv` (STRA-338 stage 10). Usage: python scripts/dev/path_to_layout.py CRATE_DIR [--apply | --fix-includes] The module paths do not change, only where the files live. Walking the module tree from the crate roots, a module whose declaration carries a `#[path]` (except a `tests.rs` file and a `../` path that leaves the module's directory) gets the location its parent's directory gives it: `/.rs`, and the children that were resolved next to the old file move into the directory named after the new one. Then * the `#[path]` of every normalised declaration is dropped, the others are rewritten relative to the moved parent; * `include_str!`, `include_bytes!` and `include!` paths of a moved file are rewritten to reach the same file. A file loaded through `#[path]` (like a crate root or `mod.rs`) resolves its own `mod x;` next to itself; a file at its default place resolves them in a directory named after it. The tool tracks both for the old and the new tree. Without --apply the plan is printed. A target that already exists is reported and left. After --apply, run --fix-includes: it rewrites the `include_str!` of source files that other files read and that moved (read from `git diff -M`). Offline refactoring aid, not part of the product. """ import os import pathlib import re import subprocess import sys ROOTS = ("lib.rs", "main.rs", "mod.rs") PATH_ATTR = re.compile(r'^(\s*)#\[path\s*=\s*"([^"]+)"\]\s*$') MOD_DECL = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;\s*$") INCLUDE = re.compile(r'(include_str!|include_bytes!|include!)\(\s*"([^"]+)"\s*\)') def is_root(path): return path.name in ROOTS or path.parent.name == "bin" and path.parent.parent.name == "src" def directory(path, flat): """Where the `mod x;` declarations of a file are resolved.""" return path.parent if flat else path.parent / path.stem def declarations(path): """[(mod name, line index of the mod line, line index of its #[path] line or None, path string or None)].""" rows = path.read_text(encoding="utf-8").split("\n") found, path_line, path_value = [], None, None for index, row in enumerate(rows): attr = PATH_ATTR.match(row) if attr: path_line, path_value = index, attr.group(2) continue decl = MOD_DECL.match(row) if decl: found.append((decl.group(1), index, path_line, path_value)) path_line = path_value = None elif not row.strip().startswith("#[") and row.strip() and not row.strip().startswith("//"): path_line = path_value = None return found class Plan: """The module tree walked from the crate roots: for every module file its old and its new place.""" def __init__(self): self.new, self.flats, self.decls, self.skipped = {}, {}, {}, [] def old_child(self, old, old_flat, name, value): """(file, flat) of the module a declaration names in the old tree.""" if value: base = pathlib.Path(os.path.normpath(old.parent / value)) return (base, True) if base.is_file() else (None, False) plain = directory(old, old_flat) / f"{name}.rs" nested = directory(old, old_flat) / name / "mod.rs" return (plain, False) if plain.is_file() else (nested, True) if nested.is_file() else (None, False) def place(self, canonical, child, dirs, normalise, has_attr): """(new file, flat, normalised) for a child that is not placed yet; flat None keeps the old kind.""" old_dir, new_dir = dirs if normalise and child == canonical: return canonical, False, True if normalise and not canonical.exists() and canonical not in self.new.values(): return canonical, False, True if not has_attr and old_dir != new_dir: return new_dir / child.relative_to(old_dir), None, False return child, None, False def walk(self, old, new, old_flat, new_flat): if old in self.new: return self.new[old], self.flats[old] = new, new_flat dirs = directory(old, old_flat), directory(new, new_flat) rows = [] for name, mod_line, path_line, value in declarations(old): child, child_flat = self.old_child(old, old_flat, name, value) if child is None: continue normalise = value is not None and ".." not in value and not value.endswith("tests.rs") if child in self.new: target, normalised = self.new[child], False else: canonical = dirs[1] / f"{name}.rs" target, flat, normalised = self.place(canonical, child, dirs, normalise, value is not None) if normalise and not normalised: self.skipped.append((str(old), name, "target exists or is taken")) self.walk(child, target, child_flat, child_flat if flat is None else flat) rows.append((name, mod_line, path_line, value, target, normalised)) self.decls[old] = rows def collect(crate_dir): src = pathlib.Path(crate_dir).resolve() / "src" plan = Plan() for root in (p for p in sorted(src.rglob("*.rs")) if is_root(p)): plan.walk(root, root, True, True) return plan def relative(target, start): return pathlib.PurePosixPath(os.path.relpath(target, start).replace("\\", "/")).as_posix() def git(root, *args): subprocess.run(["git", *args], cwd=root, check=True, capture_output=True) def rewrite_file(old, new, rows_info, text): rows, drop = text.split("\n"), set() for _name, _mod_line, path_line, _value, target, normalised in rows_info: if path_line is None: continue if normalised: drop.add(path_line) else: indent = PATH_ATTR.match(rows[path_line]).group(1) rows[path_line] = f'{indent}#[path = "{relative(target, new.parent)}"]' text = "\n".join(r for i, r in enumerate(rows) if i not in drop) if old != new: text = INCLUDE.sub(lambda m: f'{m.group(1)}("{relative(old.parent / m.group(2), new.parent)}")', text) return text def apply_plan(plan, root, apply): moves = {old: new for old, new in plan.new.items() if old != new} for old, new in sorted(moves.items()): print(f"mv {old.relative_to(root).as_posix()} -> {new.relative_to(root).as_posix()}") print(f"{len(moves)} files move; left as they are: {plan.skipped}") if not apply: return contents = {old: old.read_text(encoding="utf-8") for old in plan.new} for old, new in sorted(moves.items()): new.parent.mkdir(parents=True, exist_ok=True) git(root, "mv", str(old), str(new)) for old, new in plan.new.items(): text = rewrite_file(old, new, plan.decls.get(old, []), contents[old]) with open(new, "wb") as handle: handle.write(text.encode("utf-8")) def fix_includes(crate_dir): """Rewrite `include_str!`, `include_bytes!` and `include!` of `.rs` files that moved (read from `git diff -M`).""" root = pathlib.Path(crate_dir).resolve().parents[1] out = subprocess.run(["git", "diff", "-M", "--name-status", "HEAD"], cwd=root, capture_output=True, text=True).stdout moved = {} for line in out.splitlines(): parts = line.split("\t") if parts[0].startswith("R"): moved[pathlib.Path(os.path.normpath(root / parts[1]))] = root / parts[2] changed = 0 for path in pathlib.Path(crate_dir).resolve().rglob("*.rs"): text = path.read_text(encoding="utf-8") def fix(match): target = pathlib.Path(os.path.normpath(path.parent / match.group(2))) if match.group(2).endswith(".rs") and not target.exists() and target in moved: return f'{match.group(1)}("{relative(moved[target], path.parent)}")' return match.group(0) new_text = INCLUDE.sub(fix, text) if new_text != text: changed += 1 with open(path, "wb") as handle: handle.write(new_text.encode("utf-8")) print(f"include paths fixed in {changed} files") if __name__ == "__main__": crate = sys.argv[1] if "--fix-includes" in sys.argv: fix_includes(crate) else: apply_plan(collect(crate), pathlib.Path(crate).resolve().parents[1], "--apply" in sys.argv)