File size: 3,762 Bytes
7e2301f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Push the local PhotonTTS source tree to the remote marimo GPU box (/root/PhotonTTS).

  MARIMO_URL=... MARIMO_TOKEN=... python tools/push_remote.py [--exec-script PATH]

Tars the repo (code only), sends it through the marimo-pair execute-code.sh script, and
extracts it on the remote. Credentials come from env vars only; never commit them.
"""

from __future__ import annotations

import base64
import io
import os
import subprocess
import sys
import tarfile
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SKIP_DIRS = {".git", ".venv", "__pycache__", ".pytest_cache", "runs", "data"}
DEFAULT_EXEC = Path.home() / ".claude/skills/marimo-pair/scripts/execute-code.sh"
REMOTE_DIR = "/root/PhotonTTS"


def build_tar() -> bytes:
    buf = io.BytesIO()
    with tarfile.open(fileobj=buf, mode="w:gz") as tar:
        for p in sorted(ROOT.rglob("*")):
            rel = p.relative_to(ROOT)
            if any(part in SKIP_DIRS for part in rel.parts) or p.is_dir() or p.suffix == ".pyc":
                continue
            tar.add(p, arcname=rel.as_posix())
    return buf.getvalue()


def find_bash() -> str:
    """On Windows, plain 'bash' resolves to WSL; prefer Git Bash."""
    if os.name != "nt":
        return "bash"
    for c in (os.environ.get("PHOTON_BASH"), r"C:\Program Files\Git\bin\bash.exe", r"C:\Program Files\Git\usr\bin\bash.exe"):
        if c and Path(c).exists():
            return c
    return "bash"


CHUNK = 20_000  # execute-code.sh passes code as one jq argument; Windows caps args at ~32K chars
STAGING = "/root/.photon_push.b64"


def run_remote(code: str, url: str, token: str, exec_script: Path) -> str:
    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="ascii") as f:
        f.write(code)
        tmp = f.name
    try:
        r = subprocess.run([find_bash(), exec_script.as_posix(), "--url", url, "--token", token, Path(tmp).as_posix()],
                           capture_output=True, text=True, encoding="utf-8", errors="replace")
    finally:
        os.unlink(tmp)
    out = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if not l.startswith("Warning"))
    if r.returncode != 0 or "Traceback" in out:
        raise RuntimeError(out)
    return out


def main():
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    url, token = os.environ["MARIMO_URL"], os.environ["MARIMO_TOKEN"]
    exec_script = Path(sys.argv[sys.argv.index("--exec-script") + 1]) if "--exec-script" in sys.argv else DEFAULT_EXEC
    payload = base64.b64encode(build_tar()).decode()
    chunks = [payload[i : i + CHUNK] for i in range(0, len(payload), CHUNK)]
    for i, c in enumerate(chunks):
        mode = "w" if i == 0 else "a"
        run_remote(f"open({STAGING!r}, {mode!r}).write({c!r})\n", url, token, exec_script)
    code = (
        "import base64, io, tarfile, os, shutil\n"
        f"dst = {REMOTE_DIR!r}\n"
        "os.makedirs(dst, exist_ok=True)\n"
        "for name in os.listdir(dst):\n"
        "    if name not in ('runs', 'data', '.venv'):\n"
        "        p = os.path.join(dst, name)\n"
        "        shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)\n"
        f"data = base64.b64decode(open({STAGING!r}).read())\n"
        f"assert len(data) == {len(payload) * 3 // 4 - payload[-2:].count('=')}, 'truncated push'\n"
        "with tarfile.open(fileobj=io.BytesIO(data), mode='r:gz') as t:\n"
        "    t.extractall(dst, filter='data')\n"
        f"os.remove({STAGING!r})\n"
        "n = sum(len(f) for _, _, f in os.walk(dst))\n"
        "print(f'pushed {len(data)} bytes -> {dst} ({n} files)')\n"
    )
    print(run_remote(code, url, token, exec_script), f"[{len(chunks)} chunks]")


if __name__ == "__main__":
    main()