summaryrefslogtreecommitdiff
path: root/timelord/utils/copy_cow.py
blob: 60e6626c5130799fe0b11c856d03710e08866425 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""
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