""" Copy-on-Write and cloning utilities for TIMELORD. Leverages macOS APFS clonefile (cp -c -R) for instant, zero-storage cloning, with graceful fallbacks for other platforms. """ import os import platform import shutil import subprocess from pathlib import Path from typing import Callable, List, Optional, Set def is_macos() -> bool: return platform.system().lower() == "darwin" def clone_directory_cow( src: Path, dst: Path, exclude_dirs: Optional[Set[str]] = None, progress_callback: Optional[Callable[[str], None]] = None, allow_existing_dst: bool = False, ) -> bool: """ Clones a directory using Copy-on-Write where supported. On macOS APFS, uses `cp -c -R` which creates block-level clones in milliseconds without consuming extra disk space. """ src = Path(src).resolve() dst = Path(dst).resolve() if exclude_dirs is None: exclude_dirs = {".timelord", ".venv", "__pycache__", ".pytest_cache"} if dst.exists() and not allow_existing_dst: raise FileExistsError(f"Target destination already exists: {dst}") dst.parent.mkdir(parents=True, exist_ok=True) if progress_callback: progress_callback(f"Cloning {src.name} to {dst.name}...") # If on macOS, try APFS clone with cp -c -R if is_macos(): # First copy excluding excluded top-level directories # We can create dst, then copy entries dst.mkdir(parents=True, exist_ok=True) for item in src.iterdir(): if item.name in exclude_dirs: continue target_item = dst / item.name try: # Use macOS cp -c -R for instant APFS clone cmd = ["cp", "-c", "-R", "-p", str(item), str(target_item)] subprocess.run(cmd, check=True, capture_output=True) except (subprocess.CalledProcessError, FileNotFoundError): # Fallback to shutil if cp -c fails (e.g. cross-volume or non-APFS) if item.is_dir(): shutil.copytree( item, target_item, symlinks=True, ignore=shutil.ignore_patterns(*exclude_dirs), ) else: shutil.copy2(item, target_item) return True else: # Linux or other OS: try cp --reflink=auto or fallback to copytree try: cmd = ["cp", "--reflink=auto", "-R", str(src), str(dst)] subprocess.run(cmd, check=True, capture_output=True) # Remove excluded dirs in target for exc in exclude_dirs: exc_path = dst / exc if exc_path.exists(): if exc_path.is_dir(): shutil.rmtree(exc_path) else: exc_path.unlink() return True except Exception: # Fallback def _ignore_filter(directory, contents): return [c for c in contents if c in exclude_dirs] shutil.copytree(src, dst, symlinks=True, ignore=_ignore_filter) return True def copy_file_cow(src: Path, dst: Path) -> bool: """Clones a single file using copy-on-write if possible.""" src = Path(src).resolve() dst = Path(dst).resolve() dst.parent.mkdir(parents=True, exist_ok=True) if is_macos(): try: cmd = ["cp", "-c", "-p", str(src), str(dst)] subprocess.run(cmd, check=True, capture_output=True) return True except Exception: pass try: shutil.copy2(src, dst) return True except Exception: return False