#!/usr/bin/env python3 """Move a trailing inline `#[cfg(test)] mod tests { ... }` of a Rust module file into its own file (STRA-338). `foo.rs` gets `#[cfg(test)]` and `mod tests;`; the body moves, dedented, to `foo/tests.rs`, so the test ids (`foo::tests::name`) and the production code stay exactly as they were. A file that was itself loaded through `#[path]` looks for `tests.rs` beside it instead: the compiler reports those, add `#[path = "foo/tests.rs"]` by hand. Crate roots (lib.rs, main.rs, bin/*, examples/*) are skipped. Relative `include_str!` / `include_bytes!` paths inside the moved body get one more `../` (the file sits one directory deeper). The compiler is the judge of the rest. Usage: scripts/dev/extract_tests.py [--dry-run] FILE.rs... prints "moved|skipped " per file """ import argparse import pathlib import re import sys OPEN = re.compile(r"^(?:pub(?:\(crate\))? )?mod tests \{$") INCLUDE = re.compile(r'(include_(?:str|bytes)!\(\s*")(?=[^/])') HEADER = "//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).\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 find_block(lines): """Index of the one `#[cfg(test)]` line that opens a `mod tests {` at column 0, or None.""" hits = [i for i, row in enumerate(lines[:-1]) if row == "#[cfg(test)]" and OPEN.match(lines[i + 1])] return hits[0] if len(hits) == 1 else None def block_end(lines, start): """Index of the column-0 `}` that closes the tests module, or None when code follows it.""" end = next((i for i in range(start + 2, len(lines)) if lines[i] == "}"), None) return end if end is not None and not any(row.strip() for row in lines[end + 1:]) else None def is_plain_module(path): """False for crate roots, bins, examples and benches.""" parts = path.parts if path.name in ("lib.rs", "main.rs") or any(d in parts for d in ("bin", "examples", "benches")): return False return "tests" not in parts[:-1] def dedent(rows): return [row[4:] if row.startswith(" ") else row for row in rows] def deepen_includes(text): """One more `../` before every relative include path; the macro and its string may sit on different lines.""" return INCLUDE.sub(lambda m: m.group(1) + "../", text) def target_path(path): """`foo.rs` -> `foo/tests.rs`; `foo/mod.rs` -> `foo/tests.rs`.""" return path.with_name("tests.rs") if path.name == "mod.rs" else path.with_suffix("") / "tests.rs" def split_text(text): """(new source, tests file text), or a reason string when the file has no single trailing tests module.""" lines = text.split("\n") start = find_block(lines) end = block_end(lines, start) if start is not None else None if end is None: return "no single trailing mod tests block that ends the file" body = deepen_includes("\n".join(dedent(lines[start + 2:end]))) declaration = ["#[cfg(test)]", "mod tests;", ""] return "\n".join(lines[:start] + declaration), HEADER + body.rstrip("\n") + "\n" def process(path, dry_run): if not is_plain_module(path): return "skipped", "crate root, bin, example or bench" result = split_text(read(path)) if isinstance(result, str): return "skipped", result destination = target_path(path) if destination.exists(): return "skipped", f"{destination} already exists" if not dry_run: destination.parent.mkdir(parents=True, exist_ok=True) write(destination, result[1]) write(path, result[0]) return "moved", str(destination) def main(argv): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--dry-run", action="store_true") parser.add_argument("files", nargs="+") args = parser.parse_args(argv) for name in args.files: verdict, detail = process(pathlib.Path(name), args.dry_run) print(f"{verdict} {name} {detail}") return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))