Files
leleka/scripts/dev/split_module.py

88 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""Split an oversized Rust module file into child modules (STRA-338): its fns and impl blocks move, the rest stays.
`foo.rs` keeps its `use` lines, types, constants, macros and nested modules; every top-level `fn` and `impl` block
moves into `foo/<name>.rs` groups of about --target lines, each starting with `use super::*;`. The parent ends with
`mod <name>;` and `pub use <name>::*;` for every group, so all paths stay as they were. Moved free fns and the fns and
consts of inherent impls get `pub(super)` when they had no visibility, `super::` paths are shifted one level, and
`#[test]` items stay where they are. Crate roots (lib.rs, main.rs, bin/*) are skipped. A file that is itself loaded
through `#[path]` gets explicit child paths. The compiler and the tests judge the result; hot-path crates also need
the GPU identity and A/B gates.
Usage: scripts/dev/split_module.py [--dry-run] [--target 250] FILE.rs...
"""
import argparse
import pathlib
import re
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from rustsplit.split import plan_split # noqa: E402
def read(path):
with open(path, encoding="utf-8", newline="") as handle:
return handle.read().replace("\r\n", "\n")
def write(path, text):
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write(text)
def is_root(path):
return path.name in ("lib.rs", "main.rs") or "bin" in path.parts or "examples" in path.parts
def child_dir(path):
return path.parent if path.name in ("mod.rs", "lib.rs", "main.rs") else path.with_suffix("")
def path_targets():
"""File names that some source file of the workspace loads through `#[path = "...name.rs"]` (scanned once)."""
root = pathlib.Path(__file__).resolve().parents[2]
found = set()
for top in ("crates", "control-plane", "desktop-core"):
for source in (root / top).rglob("*.rs"):
if "target" not in source.parts:
found.update(re.findall(r'#\[path\s*=\s*"[^"]*?([\w.\-]+\.rs)"', read(source)))
return found
def process(path, target, dry_run, loaded, allow_root=False):
if is_root(path) and not (allow_root and path.name in ("lib.rs", "main.rs") or "examples" in path.parts and path.name == "main.rs"):
return "skipped", "crate root, bin or example"
directory = child_dir(path)
# a file loaded through `#[path]`, or an integration test crate root (tests/foo.rs): `mod x;` would look beside it
integration_root = path.parent.name == "tests" and path.parent.parent.joinpath("Cargo.toml").exists()
explicit = directory.name if path.name in loaded or integration_root else None
reserved = {p.stem for p in directory.glob("*.rs")} if directory.is_dir() else set()
result = plan_split(read(path), target, explicit, reserved | {"tests", path.stem})
if result is None:
return "skipped", "no fn or impl to move"
if not dry_run:
directory.mkdir(parents=True, exist_ok=True)
write(path, result[0])
for name, text in result[1].items():
write(directory / f"{name}.rs", text)
return "split", f"{len(result[1])} children, parent {result[0].count(chr(10))} lines"
def main(argv):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--target", type=int, default=250)
parser.add_argument("--allow-root", action="store_true", help="also split a lib.rs crate root")
parser.add_argument("files", nargs="+")
args = parser.parse_args(argv)
loaded = path_targets()
for name in args.files:
verdict, detail = process(pathlib.Path(name), args.target, args.dry_run, loaded, args.allow_root)
print(f"{verdict} {name} {detail}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))