"""Turn `#[path = "x.rs"] mod x;` declarations into ordinary modules (STRA-338 stage 10, ratchet `path-include`). Usage: python scripts/dev/path_to_modules.py CRATE_DIR [--apply] [--all] A module declared with a `#[path]` attribute that the `path-include` ratchet counts (anything but `dir/name.rs` and `...tests.rs`; `--all` takes every `#[path]`) is moved to the file the compiler would look for without the attribute, and the attribute is dropped. A file that is loaded through `#[path]` owns its directory like a `mod.rs`, so the children of a moved module are moved the same way (their `#[path]` or their place next to the parent changes), and the relative paths of `include_str!`/`include_bytes!` in a moved file are rewritten. Without --apply the plan is printed. Offline refactoring aid, not part of the product. """ import collections 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 COUNTED = re.compile(r'^(?!(?:[^"]*tests\.rs$)|(?:[A-Za-z0-9_]+/[A-Za-z0-9_]+\.rs$))') PATH_ATTR = re.compile(r'path\s*=\s*"([^"]+)"') STD_ROOTS = ("lib.rs", "main.rs", "mod.rs") NL = chr(10) def canonical_base(new_file, keeps_attr): """The directory the children of a module are looked up in.""" if new_file.name in STD_ROOTS or keeps_attr: return new_file.parent return new_file.parent / new_file.stem def plan(crate, every): src = crate.root_dir.resolve() / "src" declared_by = collections.Counter(child.file for mod in crate.by_file.values() for child in mod.children.values()) """(moves {old file: new file}, dropped [(parent file, module name)], problems [str]).""" moves, dropped, problems = {}, [], [] new_file = {crate.root.file: crate.root.file} keeps = {crate.root.file: False} changed = {crate.root.file: False} queue = [crate.root] seen_targets = {} while queue: parent = queue.pop(0) base = canonical_base(new_file[parent.file], keeps[parent.file]) for name, child in parent.children.items(): if child.file in new_file: continue attrs = parent.decl_attrs.get(name, "") path = PATH_ATTR.search(attrs) current = child.file is_modrs = current.name == "mod.rs" canonical = base / name / "mod.rs" if is_modrs else base / f"{name}.rs" shared = declared_by[current] > 1 # a file two parents declare (each owns a copy of its state) cannot be moved if shared or not current.is_relative_to(src): # a file of the crate's `tests/` directory stays where it is new_file[current], keeps[current], changed[current] = current, True, False queue.append(child) continue if path: counted = every or COUNTED.match(path.group(1)) is not None relocate = counted or changed[parent.file] else: relocate = changed[parent.file] and current != canonical if relocate: if canonical != current: moves[current] = canonical if path: dropped.append((parent.file, name)) new_file[current], keeps[current] = canonical, False changed[current] = canonical != current or bool(path) or changed[parent.file] else: new_file[current], keeps[current] = current, bool(path) changed[current] = False if relocate: if canonical in seen_targets and seen_targets[canonical] != current: problems.append(f"{canonical} is the target of {seen_targets[canonical]} and of {current}") seen_targets[canonical] = current queue.append(child) return moves, dropped, problems def rewrite_includes(text, old, new): """Fix the relative path of include_str!/include_bytes! in a file that moves from `old` to `new`.""" def fix(m): target = (old.parent / m.group(2)).resolve() return f'{m.group(1)}"{os.path.relpath(target, new.parent).replace(os.sep, "/")}"' return re.sub(r'(include_(?:str|bytes)!\()"([^"]+)"', fix, text) def drop_attr(text, name): """Remove the `#[path = "..."]` lines that belong to `mod NAME;` (a name declared twice under different cfgs loses both; the other attributes of the declaration stay).""" lines, found, i = text.split(NL), False, 0 while i < len(lines): if re.match(rf"\s*(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+{name}\s*;", lines[i]): j = i - 1 while j >= 0 and lines[j].strip().startswith("#["): if PATH_ATTR.search(lines[j]): del lines[j] i, found = i - 1, True j -= 1 i += 1 if not found: raise SystemExit(f"no #[path] attribute for mod {name}") return NL.join(lines) def main(): crate_dir = pathlib.Path(sys.argv[1]).resolve() apply, every = "--apply" in sys.argv, "--all" in sys.argv crate = Crate(crate_dir) moves, dropped, problems = plan(crate, every) for old, new in sorted(moves.items()): print(f"{old.relative_to(crate_dir)} -> {new.relative_to(crate_dir)}") print(f"{len(moves)} files move, {len(dropped)} #[path] attributes are dropped, {len(problems)} problems") for p in problems: print("PROBLEM", p) for old, new in moves.items(): if new.exists() and new not in moves: print("PROBLEM target exists:", new) problems.append(str(new)) if not apply or problems: return 1 if problems else 0 texts = {f: f.read_text(encoding="utf-8") for f in crate.by_file} for parent_file, name in dropped: texts[parent_file] = drop_attr(texts[parent_file], name) for old, new in moves.items(): texts[old] = rewrite_includes(texts[old], old, new) for f, text in texts.items(): with open(f, "w", encoding="utf-8", newline="\n") as handle: handle.write(text) for old, new in sorted(moves.items(), key=lambda kv: len(kv[0].parts)): new.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["git", "-C", str(crate_dir), "mv", str(old), str(new)], check=True) return 0 if __name__ == "__main__": sys.exit(main())