scripts/dev/path_to_modules.py moves each module declared with #[path] to the file the compiler looks for without the attribute, moves the children of a path-loaded file with it (such a file owns its directory like mod.rs) and rewrites include_str!/include_bytes! paths. Only the two declarations that point into the crate's tests/ directory keep their attribute. No code changes: parent files lose attribute lines. Gates that quote source paths follow: smoke-groups.json (directory patterns for runtime-gr/gdn/moe/qsa/ple/mtp; 7 real-model smokes now classify as model-assets, 3 fallback smokes now sit in their runtime group), docs/gpu-bringup.md table, docs and the qsa oracle pin path. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
139 lines
6.0 KiB
Python
139 lines
6.0 KiB
Python
"""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 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"
|
|
"""(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"
|
|
if 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)}"{pathlib.PurePosixPath(os.path.relpath(target, new.parent)).as_posix()}"'
|
|
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())
|