File size: 3,834 Bytes
9049b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Create K sandbox copies per repository for parallel Judge grading.

Each copy is `git clone --shared` of the mirror (no object duplication) with
its own `.venv` installed from the repository's requirements.lock, plus the
build backends needed for offline editable rebuilds. Layout:
    <pool_root>/<owner__name>/<i>/   i in 0..K-1

Usage:
    python -m r2e_local.make_pool --mirrors <repos root> --bootstrap <bootstrap root> \
        --pool <pool root> --copies 2 [--repos owner/name ...] [--python-root <uv python dir>]
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

BACKENDS = [
    "setuptools", "wheel", "setuptools-scm", "hatchling", "hatch-vcs", "hatch-fancy-pypi-readme",
    "poetry-core", "flit-core", "pdm-backend", "versioningit", "pbr", "editables",
    "hatch-requirements-txt", "setuptools-git-versioning", "poetry-dynamic-versioning",
]


def make_one(mirror: Path, boot: dict, lock: Path, dest: Path, env: dict) -> str:
    if (dest / ".venv" / "bin" / "python").exists():
        return f"exists {dest}"
    dest.parent.mkdir(parents=True, exist_ok=True)
    if not (dest / ".git").exists():
        subprocess.run(["git", "clone", "-q", "--shared", "--no-checkout", f"file://{mirror}", str(dest)], check=True)
    subprocess.run(["git", "-C", str(dest), "checkout", "-q", "--detach", boot["ref"]], check=True)
    py = boot.get("extra", {}).get("python_version", "3.12")
    py = ".".join(py.split(".")[:2])
    subprocess.run(["uv", "venv", "-q", "--python", py, ".venv"], cwd=dest, env=env, check=True)
    # The lock is a `uv pip freeze` of the bootstrap venv: drop the editable
    # self-reference (`-e file:///.../sandboxes/<repo>`) and any other local
    # path pins; the copy gets its own editable install via rebuild_cmds below.
    pinned = [
        line for line in lock.read_text().splitlines()
        if line.strip() and not line.startswith(("-e ", "#")) and "file://" not in line
    ]
    lock_copy = dest / ".venv" / "requirements.pool.txt"
    lock_copy.write_text("\n".join(pinned) + "\n")
    subprocess.run(["uv", "pip", "install", "-q", "--python", ".venv/bin/python", "-r", str(lock_copy)], cwd=dest, env=env, check=True)
    subprocess.run(["uv", "pip", "install", "-q", "--python", ".venv/bin/python", *BACKENDS], cwd=dest, env=env, check=False)
    for cmd in boot.get("rebuild_cmds") or []:
        subprocess.run(["bash", "-c", cmd], cwd=dest, env=env, check=False)
    return f"built {dest}"


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--mirrors", type=Path, required=True)
    ap.add_argument("--bootstrap", type=Path, required=True)
    ap.add_argument("--pool", type=Path, required=True)
    ap.add_argument("--copies", type=int, default=2)
    ap.add_argument("--repos", nargs="*", default=None)
    ap.add_argument("--workers", type=int, default=4)
    args = ap.parse_args(argv)
    env = dict(os.environ)
    env.setdefault("UV_LINK_MODE", "hardlink")
    jobs = []
    for bdir in sorted(args.bootstrap.iterdir()):
        bj = bdir / "bootstrap.json"
        if not bj.exists():
            continue
        boot = json.loads(bj.read_text())
        if args.repos and boot["repo"] not in args.repos:
            continue
        if not boot.get("smoke_passed"):
            continue
        key = bdir.name
        for i in range(args.copies):
            jobs.append((args.mirrors / key, boot, bdir / "requirements.lock", args.pool / key / str(i)))
    with ThreadPoolExecutor(max_workers=args.workers) as ex:
        for line in ex.map(lambda j: make_one(*j, env), jobs):
            print(line, flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())