"""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] 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 counted `#[path]` (one that is not `tests.rs` and not the `dir/name.rs` form) gets the location its parent's directory gives it: `/.rs`, and the directory that holds its children moves with it. Then * the `#[path]` of every declaration whose target is now the default location 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. Without --apply the plan is printed. A module that two parents declare is moved for the first parent only; a target that already exists is reported and left. 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") COUNTED = re.compile(r'#\[path\s*=\s*"(?![^"]*tests\.rs")(?![A-Za-z0-9_]+/[A-Za-z0-9_]+\.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 module_dir(path): return path.parent if is_root(path) 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: def __init__(self, src): self.src, self.new, self.visited = src, {}, set() self.decls = {} # old file -> [(name, mod line, path line, path value, old child)] self.skipped = [] def old_child(self, old_parent, name, value): base = old_parent.parent / value if value else module_dir(old_parent) / f"{name}.rs" base = pathlib.Path(os.path.normpath(base)) if base.is_file(): return base alt = module_dir(old_parent) / name / "mod.rs" return alt if not value and alt.is_file() else None def walk(self, old, new): if old in self.visited: return self.visited.add(old) self.new[old] = new rows = [] for name, mod_line, path_line, value in declarations(old): child = self.old_child(old, name, value) if child is None: continue canonical = module_dir(new) / f"{name}.rs" counted = value is not None and ".." not in value and COUNTED.search(f'#[path = "{value}"') is not None if child in self.new: target = self.new[child] elif counted and child != canonical and not canonical.exists() and canonical not in self.new.values(): target = canonical else: if counted and child != canonical: self.skipped.append((str(old), name, "target exists or is taken")) target = self.keep(old, new, child) rows.append((name, mod_line, path_line, value, child, target)) self.walk(child, target) self.decls[old] = rows def keep(self, old, new, child): """The child stays where it is, unless its parent's directory moved: then the directory content moves along.""" old_dir, new_dir = module_dir(old), module_dir(new) if old_dir != new_dir and child.is_relative_to(old_dir): return new_dir / child.relative_to(old_dir) return child def collect(crate_dir): src = pathlib.Path(crate_dir).resolve() / "src" plan = Plan(src) roots = [p for p in sorted(src.rglob("*.rs")) if is_root(p)] for root in roots: plan.walk(root, root) 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(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()}") if not apply: print(f"{len(moves)} files would move; skipped: {plan.skipped}") 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(): rows = contents[old].split("\n") drop = [] for name, mod_line, path_line, value, child, target in plan.decls.get(old, []): default = module_dir(new) / f"{name}.rs" if path_line is None: continue if target == default: drop.append(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 set(drop)) if old != new: text = INCLUDE.sub(lambda m: f'{m.group(1)}("{relative(old.parent / m.group(2), new.parent)}")', text) with open(new, "wb") as handle: handle.write(text.encode("utf-8")) print(f"moved {len(moves)} files; skipped {plan.skipped}") if __name__ == "__main__": crate = sys.argv[1] plan = collect(crate) rewrite(plan, pathlib.Path(crate).resolve().parents[1], "--apply" in sys.argv)