#!/usr/bin/env python3 """Move large inline `mod NAME { ... }` blocks of a Rust file into their own files (STRA-338). `foo.rs` keeps the attributes, visibility and name of the module and ends the block with `;`; the body moves, dedented, to `foo/NAME.rs` (beside the file for `mod.rs`, `lib.rs` and `main.rs`). The module path is the same as before, so `super::` paths, test ids and visibility need no edit. Relative `include_str!` / `include_bytes!` paths get one more `../` (the body sits one directory deeper). A block that contains a `#[path]` attribute is left alone. The compiler judges the rest. Usage: scripts/dev/extract_modules.py [--dry-run] [--min-lines 60] FILE.rs... prints "moved|skipped " """ import argparse import pathlib import re import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from rustsplit.items import parse_items # noqa: E402 from rustsplit.lexer import tokenize # noqa: E402 INCLUDE = re.compile(r'(include(?:_str|_bytes)?!\(\s*")(?=[^/])') PATH_ATTR = re.compile(r"#\[\s*path\s*=") MODULE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*\{") HEADER = "//! Moved out of the parent file by STRA-338 (same module path as before).\n\n" 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 child_dir(path): return path.parent if path.name in ("mod.rs", "lib.rs", "main.rs") else path.with_suffix("") def brace_index(text, item): """Index of the `{` that opens the module body.""" for tok in tokenize(text[item.head:item.end]): if tok.text == "{": return item.head + tok.start raise ValueError("no opening brace") def dedent(body): return "\n".join(row[4:] if row.startswith(" ") else row for row in body.split("\n")) def plan(text, directory, min_lines, explicit=False): """(new source text, {file: text}, [skipped reasons]) for the inline modules of `text` with at least `min_lines` lines.""" edits, files, skipped = [], {}, [] for item in parse_items(text): found = MODULE.match(text[item.head:item.end]) if item.kind == "other" else None if found is None: continue name, opening = found.group(1), brace_index(text, item) body = text[opening + 1:item.end - 1] if body.count("\n") < min_lines: continue if PATH_ATTR.search(body): skipped.append(f"{name}: contains a #[path] attribute") elif (directory / f"{name}.rs").exists(): skipped.append(f"{name}: {directory / (name + '.rs')} exists") else: content = INCLUDE.sub(lambda m: m.group(1) + "../", dedent(body).strip("\n")) files[directory / f"{name}.rs"] = HEADER + content + "\n" # explicit `#[path]` for a module file that is not a mod.rs: right whether the file is a plain module, was itself # loaded through `#[path]` (its `mod x;` would look beside it), or is an integration test crate root attr = f'#[path = "{directory.name}/{name}.rs"]' + chr(10) if explicit else "" edits.append((item.head, item.end, attr + text[item.head:opening].rstrip() + ";")) for start, end, replacement in sorted(edits, reverse=True): text = text[:start] + replacement + text[end:] return text, files, skipped _LOADED = [] def loaded_by_path(): """File names that some source file loads through `#[path = "...name.rs"]` (scanned once).""" if not _LOADED: from split_module import path_targets _LOADED.append(path_targets()) return _LOADED[0] def process(path, min_lines, dry_run): # explicit `#[path]` only where `mod x;` would look in the wrong place: a file loaded through `#[path]` (its children are # searched beside it) or an integration test crate root; a plain module finds `foo/x.rs` by itself integration_root = path.parent.name == "tests" and path.parent.parent.joinpath("Cargo.toml").exists() explicit = path.name not in ("mod.rs", "lib.rs", "main.rs") and (path.name in loaded_by_path() or integration_root) text, files, skipped = plan(read(path), child_dir(path), min_lines, explicit) if not files: return "skipped", "; ".join(skipped) or "no inline module of that size" if not dry_run: for target, body in files.items(): target.parent.mkdir(parents=True, exist_ok=True) write(target, body) write(path, text) detail = ", ".join(f"{p.name} ({b.count(chr(10))} lines)" for p, b in files.items()) return "moved", detail + (f" | left: {'; '.join(skipped)}" if skipped else "") def main(argv): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--dry-run", action="store_true") parser.add_argument("--min-lines", type=int, default=60) parser.add_argument("files", nargs="+") args = parser.parse_args(argv) for name in args.files: verdict, detail = process(pathlib.Path(name), args.min_lines, args.dry_run) print(f"{verdict} {name} {detail}") return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))