okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
6.8 KiB117 linesraw
1#!/usr/bin/env python3
2"""Build a LOCAL, TEST-SIGNED release folder (a feed) from a Terminal archive and engine packages, to try `install.sh`, `install.ps1`,
3`strata update` and `strata launch` end to end without any hosting. Nothing is uploaded.
4
5    python packaging/make_local_feed.py --out FEED --terminal strata-terminal-0.1.45-linux-x86_64.tar.gz \
6        --engine /path/to/components/engine/0.1.45-linux-x86_64-cuda [--engine ...] \
7        [--keys KEYDIR] [--url http://127.0.0.1:8099] [--sequence 1]
8    python -m http.server 8099 --bind 127.0.0.1 --directory FEED         # serve it (foreground; stop it with Ctrl+C)
9
10What it writes into FEED (the folder a person would host):
11    strata-feed.json + .sig        the signed feed (Ed25519, the key in KEYDIR, made once, never inside a git checkout)
12    control/*, engine/*            the Terminal (as a "control" package) and each engine package, archived
13    install-manifest.txt           one line per platform for install.sh / install.ps1: platform version url sha256 size (written by feed_tool build-feed)
14    install.sh, install.ps1        the one-line installers with this feed's address filled in (--url)
15    test-trust.json                the PUBLIC test key: `STRATA_UPDATE_TRUSTED_KEYS=<this file>` lets this build trust the feed
16                                   (the real key goes into strata_control/update_keys.json at release; this one never does)
17
18The engine package folders are copied (never changed in place) before they are signed with the test key.
19"""
20
21from __future__ import annotations
22
23import argparse
24import shutil
25import sys
26import tarfile
27import tempfile
28import zipfile
29from pathlib import Path
30
31ROOT = Path(__file__).resolve().parents[1]
32RELEASE_FEED = "https://github.com/Niko1221/Strata/releases/latest/download"      # the address built into install.sh / install.ps1; a local feed bakes its own in its place
33sys.path.insert(0, str(ROOT / "packaging"))
34sys.path.insert(0, str(ROOT))
35
36import feed_tool as ft  # noqa: E402
37
38
39def extract_terminal(archive: Path, into: Path) -> Path:
40    """Unpack a terminal archive; returns the folder that holds python/ and strata.py."""
41    if archive.name.endswith(".zip"):
42        with zipfile.ZipFile(archive) as zf:
43            zf.extractall(into)
44    else:
45        with tarfile.open(archive) as tf:
46            try:
47                tf.extractall(into, filter="data")
48            except TypeError:                       # Python before 3.12 (a Mac's system 3.9): no extraction filters; the archive is our own
49                tf.extractall(into)
50    (inner,) = [p for p in into.iterdir() if p.is_dir()]
51    return inner
52
53
54def main(argv=None) -> int:
55    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
56    ap.add_argument("--out", type=Path, required=True)
57    ap.add_argument("--terminal", type=Path, action="append", default=[], help="a terminal archive (.tar.gz or .zip); repeat per platform")
58    ap.add_argument("--engine", type=Path, action="append", default=[], help="an engine package folder (with engine-component.json)")
59    ap.add_argument("--drafter", type=Path, action="append", default=[], help="a DFlash2 drafter file (the feed's drafters member), listed for metal, hosted flat beside the feed")
60    ap.add_argument("--keys", type=Path, default=None, help="folder for the test key (default: <out>/../feed-test-keys)")
61    ap.add_argument("--url", default="http://127.0.0.1:8099", help="the address this feed will be served at (baked into install.sh/.ps1)")
62    ap.add_argument("--sequence", type=int, default=1)
63    ap.add_argument("--version", default=None, help="control version label (default: from the first terminal archive's VERSION)")
64    ap.add_argument("--channel", default="stable")
65    a = ap.parse_args(argv)
66
67    out = a.out.resolve()
68    keys = (a.keys or out.parent / "feed-test-keys").resolve()
69    if not (keys / "feed-key.json").exists():
70        ft.keygen(keys, allow_git=True)
71    key = ft._load_key(keys / "feed-key.json")
72    shutil.rmtree(out, ignore_errors=True)
73    (out / "engine").mkdir(parents=True)
74    (out / "control").mkdir(parents=True)
75    version = a.version
76    with tempfile.TemporaryDirectory(prefix="strata-feed-") as tmp:
77        tmpdir = Path(tmp)
78        for n, term in enumerate(a.terminal):
79            work = tmpdir / f"t{n}"
80            work.mkdir()
81            folder = extract_terminal(term.resolve(), work)
82            v = version or (folder / "VERSION").read_text(encoding="utf-8").strip()
83            version = v
84            platform = ("windows-x86_64" if (folder / "python" / "python.exe").exists() else
85                        "macos-arm64" if ("darwin" in term.name or "macos" in term.name) else
86                        "linux-aarch64" if "aarch64" in term.name else "linux-x86_64")      # the feed's own platform names
87            fmt = "zip" if platform.startswith("windows") else "tar.gz"
88            entry = ft.pack_control(folder, out / "control", version=v, platform=platform, fmt=fmt)
89            print(f"control {platform} {v}: {entry['size'] // 1048576} MB")
90        for n, pkg in enumerate(a.engine):
91            copy = tmpdir / f"e{n}" / pkg.name
92            shutil.copytree(pkg, copy, symlinks=True)
93            ft.sign_package(copy, key)
94            entry = ft.pack_engine(copy, out / "engine")
95            print(f"engine {entry['platform']}-{entry['backend']} {entry['version']}: {entry['size'] // 1048576} MB")
96            shutil.rmtree(copy.parent, ignore_errors=True)
97    for pack in a.drafter:
98        entry = ft.pack_drafter(pack, out / "drafters", version="1", backends=["metal"], url_prefix="drafters/")
99        print(f"drafter {entry['name']}: {entry['size'] // 1048576} MB")
100    ft.build_feed(out, key=key, sequence=a.sequence, channel=a.channel, engine_dir=out / "engine" if a.engine else None,
101                  control_dir=out / "control" if a.terminal else None,
102                  drafters_dir=out / "drafters" if a.drafter else None)
103    if any("linux-aarch64" in p.name for p in (out / "control").glob("*.entry.json")):       # the Linux ARM64 Terminal reads its own feed file (same bytes here)
104        for suffix in ("", ".sig"):
105            shutil.copy2(out / ("strata-feed.json" + suffix), out / ("strata-feed-linux-aarch64.json" + suffix))
106    base = a.url.rstrip("/")
107    for name in ("install.sh", "install.ps1"):
108        text = (ROOT / "packaging" / name).read_text(encoding="utf-8").replace(RELEASE_FEED, base)
109        (out / name).write_text(text, encoding="utf-8", newline="\n" if name.endswith(".sh") else None)
110    (out / "test-trust.json").write_text((keys / "feed-key.pub.json").read_text(encoding="utf-8"), encoding="utf-8")
111    print(f"feed written to {out}\n  serve it:  python -m http.server {base.rsplit(':', 1)[-1]} --bind 127.0.0.1 --directory {out}\n"
112          f"  trust it:  STRATA_UPDATE_TRUSTED_KEYS={out / 'test-trust.json'}")
113    return 0
114
115
116if __name__ == "__main__":
117    raise SystemExit(main())