okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221The linux-aarch64 platform: engine packages, Control (Terminal) and the signed feed for the DGX Sparkf436dba81

main
7.5 KiB160 linesraw
1#!/usr/bin/env python3
2"""Write the hash-pinned runtime lock of one terminal target.
3
4The terminal archive installs its Python packages from `packaging/locks/runtime-<target>-cp312.txt` with
5`pip install --require-hashes --no-deps --only-binary=:all:`: every package, direct or not, is named with an exact
6version and the SHA-256 of the wheel(s) accepted for it, so a build can only ever install the files this lock lists.
7The lock is made here, from `requirements.txt` + `requirements-monitor.txt` (the direct, version-pinned runtime
8packages) by letting pip resolve and download the wheels for the target's tags and hashing what it fetched.
9
10    python packaging/lock_wheels.py --target windows-x86_64          # writes packaging/locks/...
11    python packaging/lock_wheels.py --target linux-x86_64 --check    # fails when the committed lock differs
12    python packaging/lock_wheels.py --target linux-x86_64 --download wheelhouse/   # exactly the locked wheels
13
14Run it when a pin in requirements.txt changes, review the diff, commit. Building an archive never runs it.
15"""
16
17from __future__ import annotations
18
19import argparse
20import hashlib
21import re
22import subprocess
23import sys
24import tempfile
25from pathlib import Path
26
27ROOT = Path(__file__).resolve().parents[1]
28LOCKS = ROOT / "packaging" / "locks"
29INPUTS = ("requirements.txt", "requirements-monitor.txt")
30
31#: pip's tags for each target, and the environment markers evaluate under for it.
32TARGETS = {
33    "windows-x86_64": {"platforms": ["win_amd64"], "env": {"sys_platform": "win32", "platform_system": "Windows",
34                                                            "os_name": "nt"}},
35    "linux-x86_64": {"platforms": ["manylinux2014_x86_64", "manylinux_2_17_x86_64", "manylinux_2_28_x86_64",
36                                   "manylinux_2_34_x86_64", "linux_x86_64"],
37                     "env": {"sys_platform": "linux", "platform_system": "Linux", "os_name": "posix"}},
38    "linux-aarch64": {"platforms": ["manylinux2014_aarch64", "manylinux_2_17_aarch64", "manylinux_2_28_aarch64",
39                                    "manylinux_2_34_aarch64", "linux_aarch64"],
40                      "env": {"sys_platform": "linux", "platform_system": "Linux", "os_name": "posix"}},
41    "darwin-arm64": {"platforms": ["macosx_11_0_arm64", "macosx_12_0_arm64", "macosx_13_0_arm64",
42                                   "macosx_14_0_arm64"],
43                     "env": {"sys_platform": "darwin", "platform_system": "Darwin", "os_name": "posix"}},
44}
45PYTHON = "3.12"
46ABI = "cp312"
47
48
49def lock_path(target: str) -> Path:
50    return LOCKS / f"runtime-{target}-{ABI}.txt"
51
52
53def sha256(path: Path) -> str:
54    h = hashlib.sha256()
55    with path.open("rb") as fh:
56        for block in iter(lambda: fh.read(1 << 20), b""):
57            h.update(block)
58    return h.hexdigest()
59
60
61def norm(name: str) -> str:
62    return re.sub(r"[-_.]+", "-", name).lower()
63
64
65def _dropped_for_target(target: str) -> set[str]:
66    """Direct requirements whose environment marker is false for the target (pip evaluated markers for the host that
67    runs this script: a Windows-only package must not land in the Linux lock, nor the reverse)."""
68    from packaging.requirements import Requirement
69    env = {"python_version": PYTHON, "python_full_version": PYTHON + ".15", "implementation_name": "cpython",
70           "platform_python_implementation": "CPython", **TARGETS[target]["env"]}
71    dropped = set()
72    for name in INPUTS:
73        for line in (ROOT / name).read_text(encoding="utf-8").splitlines():
74            line = line.split(" #")[0].strip()
75            if not line or line.startswith("#"):
76                continue
77            req = Requirement(line)
78            if req.marker is not None and not req.marker.evaluate(env):
79                dropped.add(norm(req.name))
80    # a requirement listed twice with different markers (numpy) is kept when any line applies
81    kept = set()
82    for name in INPUTS:
83        for line in (ROOT / name).read_text(encoding="utf-8").splitlines():
84            line = line.split(" #")[0].strip()
85            if not line or line.startswith("#"):
86                continue
87            req = Requirement(line)
88            if req.marker is None or req.marker.evaluate(env):
89                kept.add(norm(req.name))
90    return dropped - kept
91
92
93def build_lock(target: str) -> str:
94    spec = TARGETS[target]
95    with tempfile.TemporaryDirectory(prefix="strata-lock-") as tmp:
96        cmd = [sys.executable, "-m", "pip", "download", "--quiet", "--only-binary=:all:",
97               "--python-version", PYTHON, "--implementation", "cp", "--abi", ABI, "-d", tmp]
98        for p in spec["platforms"]:
99            cmd += ["--platform", p]
100        for name in INPUTS:
101            cmd += ["-r", str(ROOT / name)]
102        subprocess.run(cmd, check=True)
103        wheels: dict[str, tuple[str, list[str]]] = {}
104        for whl in sorted(Path(tmp).glob("*.whl")):
105            name, version = whl.name.split("-")[:2]
106            wheels.setdefault(norm(name), (version, []))[1].append(sha256(whl))
107    drop = _dropped_for_target(target)
108    out = [
109        "# Hash-pinned runtime packages for the " + target + " terminal archive (CPython 3.12, " + ABI + ").",
110        "# Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with",
111        "#   pip install --require-hashes --no-deps --only-binary=:all: -r <this file>",
112        "# and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff.",
113    ]
114    for name in sorted(wheels):
115        if name in drop:
116            continue
117        version, hashes = wheels[name]
118        out.append(f"{name}=={version} \\")
119        out.append(" \\\n".join(f"    --hash=sha256:{h}" for h in sorted(set(hashes))))
120    return "\n".join(out) + "\n"
121
122
123def download_locked(target: str, dest: Path) -> int:
124    """Fetch exactly the wheels the committed lock names (pip verifies every hash) into `dest`, for a build on a
125    machine with no internet: package_terminal.py --wheelhouse dest. Works from any host for any target."""
126    spec = TARGETS[target]
127    dest.mkdir(parents=True, exist_ok=True)
128    cmd = [sys.executable, "-m", "pip", "download", "--quiet", "--only-binary=:all:", "--require-hashes", "--no-deps",
129           "--python-version", PYTHON, "--implementation", "cp", "--abi", ABI, "-d", str(dest),
130           "-r", str(lock_path(target))]
131    for p in spec["platforms"]:
132        cmd += ["--platform", p]
133    subprocess.run(cmd, check=True)
134    count = len(list(dest.glob("*.whl")))
135    print(f"{count} wheels in {dest}")
136    return 0
137
138
139def main() -> int:
140    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
141    ap.add_argument("--target", choices=sorted(TARGETS), required=True)
142    ap.add_argument("--check", action="store_true", help="compare with the committed lock instead of writing")
143    ap.add_argument("--download", metavar="DIR", help="fetch the locked wheels into DIR (hash-checked) and stop")
144    a = ap.parse_args()
145    if a.download:
146        return download_locked(a.target, Path(a.download))
147    text = build_lock(a.target)
148    path = lock_path(a.target)
149    if a.check:
150        same = path.exists() and path.read_text(encoding="utf-8") == text
151        print(("lock is current: " if same else "lock DIFFERS: ") + str(path))
152        return 0 if same else 1
153    LOCKS.mkdir(parents=True, exist_ok=True)
154    path.write_text(text, encoding="utf-8", newline="\n")
155    print(f"wrote {path} ({text.count('==')} packages)")
156    return 0
157
158
159if __name__ == "__main__":
160    sys.exit(main())