#!/usr/bin/env python3 """ Sanitize logs and text files by replacing absolute .cursor worktree paths with a safer relative marker. Example absolute paths are shown using forward-slashes to avoid source-level escape issues, e.g.: C:/Users//.cursor/worktrees/... Creates a backup copy with suffix .bak for each file modified. Usage: python tools/sanitize_cursor_paths.py path/to/logs [--dry-run] This is safe to run on a logs directory. It will only update files that contain matches and will save a backup as .bak before writing changes. """ from __future__ import annotations import argparse import re from pathlib import Path # Regex to match Windows absolute .cursor worktree paths # Use raw string to avoid Unicode escape issues _CURSOR_RE = re.compile(r"C:\\Users\\[^\\\s]+\\.cursor\\worktrees\\") def sanitize_file(p: Path, dry_run: bool = False) -> int: """Sanitize a single file by replacing .cursor worktree paths. Args: p: Path to the file to sanitize dry_run: If True, only check for matches without modifying Returns: 1 if file was modified or would be modified, 0 otherwise """ text = p.read_text(encoding="utf-8", errors="replace") if not _CURSOR_RE.search(text): return 0 new_text = _CURSOR_RE.sub(".cursor/worktrees/", text) if dry_run: return 1 bak = p.with_suffix(p.suffix + ".bak") bak.write_text(text, encoding="utf-8") p.write_text(new_text, encoding="utf-8") return 1 def main() -> None: """Main entry point for the sanitize script.""" ap = argparse.ArgumentParser(description="Sanitize .cursor absolute paths in files") ap.add_argument("path", type=Path, help="File or directory to scan") ap.add_argument( "--dry-run", action="store_true", help="Only report matches, do not modify" ) args = ap.parse_args() target = args.path files = [] if target.is_dir(): files = list(target.rglob("*.log")) + list(target.rglob("*.txt")) elif target.is_file(): files = [target] else: print(f"No such file or directory: {target}") raise SystemExit(2) modified = 0 for f in files: try: res = sanitize_file(f, dry_run=args.dry_run) if res: modified += 1 print(("DRY:" if args.dry_run else "MODIFIED:"), f) except Exception as e: print("ERROR processing", f, e) print("Done. Files matched/modified:", modified) if __name__ == "__main__": main()