# SPDX-License-Identifier: MIT """Move tainted Rust items aside unread (the clean rewrite, docs/restart.md). python3 scratch/withdraw.py ranges FILE # item kind, name and line range only python3 scratch/withdraw.py move FILE A-B[,C-D] DEST # move those lines to DEST `ranges` prints, for each `fn`/`enum`/`struct`/`impl`/`const` item, its kind, name and the 1-based line range including the doc comments and attributes directly above it; never the item's body. `move` appends the lines to DEST (under scratch/withdrawn/, git-ignored) and removes them from FILE, printing only how many lines moved. """ import re import sys from pathlib import Path ITEM = re.compile(r"^\s*(?:pub(?:\([a-z]+\))?\s+)?(?:const\s+)?(fn|enum|struct|impl|const|mod)\b\s*(?:<[^>]*>\s*)?([A-Za-z_0-9]+)?") def item_end(lines: list[str], start: int) -> int: depth = 0 opened = False for index in range(start, len(lines)): code = lines[index].split("//", 1)[0] code = re.sub(r"'(?:\\.|[^'\\])'", "", code) code = re.sub(r'"(?:\\.|[^"\\])*"', "", code) for char in code: if char == "{": depth += 1 opened = True elif char == "}": depth -= 1 if opened and depth <= 0: return index if not opened and code.rstrip().endswith(";"): return index return len(lines) - 1 def ranges(path: Path) -> None: lines = path.read_text().splitlines() for index, line in enumerate(lines): match = ITEM.match(line) if not match: continue top = index while top > 0 and re.match(r"^\s*(///|#\[|//)", lines[top - 1]): top -= 1 end = item_end(lines, index) indent = len(line) - len(line.lstrip()) print(f"{' ' * indent}{match.group(1)} {match.group(2) or ''} {top + 1}-{end + 1}") def move(path: Path, spec: str, dest: Path) -> None: lines = path.read_text().splitlines(keepends=True) chosen: set[int] = set() for part in spec.split(","): a, b = part.split("-") chosen.update(range(int(a) - 1, int(b))) taken = [lines[i] for i in sorted(chosen)] kept = [line for i, line in enumerate(lines) if i not in chosen] dest.parent.mkdir(parents=True, exist_ok=True) with dest.open("a") as out: out.write(f"// ---- from {path} lines {spec}\n") out.writelines(taken) path.write_text("".join(kept)) print(f"moved {len(taken)} lines from {path} to {dest}") if __name__ == "__main__": if sys.argv[1] == "ranges": ranges(Path(sys.argv[2])) elif sys.argv[1] == "move": move(Path(sys.argv[2]), sys.argv[3], Path(sys.argv[4])) else: raise SystemExit(__doc__)