Files
tk/scripts/checked_package.py
waozi 4e792756eb
Tk ZX libraries / package (push) Failing after 20m52s
Verify adding Tcl through the Tk package lock
2026-11-22 04:35:26 -03:00

436 lines
23 KiB
Python

#!/usr/bin/env python3
"""Build, test and publish Tk's relocatable ZX libraries."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import tomllib
ROOT = Path(__file__).resolve().parents[1]
REPOSITORY = "https://git.waozi.xyz/ziranlang/tk.git"
PROFILES = {
"default": (),
"no-canvas": ("TK_NO_CANVAS",),
"bitmap": ("TK_BITMAP",),
"bitmap-no-canvas": ("TK_BITMAP", "TK_NO_CANVAS"),
"bitmap-menu": ("TK_BITMAP", "TK_MENU"),
"full": ("TK_BITMAP", "TK_LISTBOX", "TK_MENU"),
"listbox-no-canvas": ("TK_LISTBOX", "TK_NO_CANVAS"),
}
def run(*args, capture=False, cwd=ROOT, env=None):
return subprocess.run(args, cwd=cwd, env=env, check=True, text=True,
stdout=subprocess.PIPE if capture else None).stdout
def git(directory, *args):
return run("git", *args, capture=True, cwd=directory).strip()
def require(condition, message):
if not condition:
raise ValueError(message)
def hex_string(value, length):
return isinstance(value, str) and re.fullmatch(f"[0-9a-f]{{{length}}}", value) is not None
def object_sha(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def package_id(repository, commit):
return "p" + hashlib.sha256(f"{repository}\n{commit}".encode()).hexdigest()[:16]
def read_json(path):
return json.loads(path.read_text(encoding="utf-8"))
def save_json(path, value):
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
temporary.replace(path)
def read_manifest(path):
with path.open("rb") as stream:
return tomllib.load(stream)
def graph():
manifest = read_manifest(ROOT / "ziran.toml")
lock = read_json(ROOT / "ziran.lock")
require(lock["format"] == 1 and lock["root"]["name"] == "tk", "expected a Tk source lock")
tool = lock["toolchain"]
declared = manifest["toolchain"]
require(hex_string(tool.get("commit"), 40) and tool["commit"] == declared["ref"] == tool["ref"]
and tool["url"] == declared["git"], "Tk must lock the toolchain to its declared exact commit")
(tcl,) = lock["packages"]
declared = manifest["dependencies"]["tcl"]
require(hex_string(tcl.get("commit"), 40) and tcl["commit"] == declared["ref"] == tcl["ref"]
and tcl["url"] == declared["git"] and lock["root"]["dependencies"] == {"tcl": tcl["id"]}
and lock["root"]["dependency_refs"] == {"tcl": tcl["commit"]}
and not tcl["dependencies"], "Tk must lock precisely its exact Tcl dependency")
require(not any(key in record for record in (tool, tcl) for key in ("local", "development")),
"ZX libraries require a production source lock")
return manifest, lock, tcl, tool
def provider_revision(development=False):
commit = git(ROOT, "rev-parse", "HEAD")
require(hex_string(commit, 40) and git(ROOT, "remote", "get-url", "origin").removesuffix(".git") == REPOSITORY.removesuffix(".git"),
"expected the canonical Tk HTTPS origin and exact revision")
if not development:
require(not git(ROOT, "status", "--porcelain", "--untracked-files=normal"),
"produce or publish from a clean Tk checkout")
return commit
def toolchain(args, tcl, tool):
flags = ("--offline",) if args.development else ("--locked", "--offline")
if args.development:
launcher = Path(run(args.ziran, "pkg", "path", "ziran", *flags, capture=True).strip()).resolve()
commit = git(launcher, "rev-parse", "HEAD")
path = Path(run(args.ziran, "pkg", "path", "tcl", *flags, capture=True).strip()).resolve()
require(git(path, "rev-parse", "HEAD") == tcl["commit"], "Tcl checkout differs from the lock")
tool = {**tool, "ref": commit, "commit": commit}
else:
tool_id = package_id(tool["url"], tool["commit"])
cache = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
# `pkg path` resolves the whole graph as source, including pinned ZX libraries.
launcher = (cache / "ziran/sources" / tool_id).resolve()
require((launcher / "build/bin/ziran").is_file() and git(launcher, "rev-parse", "HEAD") == tool["commit"]
and not git(launcher, "status", "--porcelain"),
"production libraries require the clean locked Ziran checkout and compiler in the cache")
pin = tcl.get("checked", {})
require(pin.get("profile") == "default" and hex_string(pin.get("sha256"), 64)
and pin.get("toolchain") == tool_id,
"production Tk requires a matching, exact Tcl default ZX library in ziran.lock")
return launcher, tool, flags
def descriptor_text(provider, tool, profile, digest):
return f"2\t{provider}\t{tool}\t{profile}\t{digest}\n"
def inspect_library(ziran, path, provider, tool, profile, digest=None, *, development=False):
require(path.suffix == ".zx", f"expected a .zx library at {path}")
actual_digest = object_sha(path)
require(digest is None or (hex_string(digest, 64) and actual_digest == digest), f"SHA-256 mismatch for {path}")
actual = run(ziran, "pkg", "zx", "inspect-ir", str(path), capture=True)
fields = actual.removesuffix("\n").split("\t")
fingerprint = None
if development:
require(len(fields) == 6 and fields[:4] == ["dev", provider, tool, profile]
and hex_string(fields[4], 64) and fields[5] == actual_digest,
f"development ZX library identity differs from its package, toolchain or profile for {path}")
fingerprint = fields[4]
else:
require(actual == descriptor_text(provider, tool, profile, actual_digest),
f"ZX library identity differs from its package, toolchain or profile for {path}")
return actual_digest, fingerprint
def pack(args):
manifest, _, tcl, tool = graph()
commit = provider_revision(args.development)
compiler, tool, flags = toolchain(args, tcl, tool)
args.output.mkdir(parents=True, exist_ok=True)
profiles = {}
launcher = compiler / "build/bin/ziran"
operation = "pack-dev" if args.development else "pack-ir"
provider = package_id(REPOSITORY, commit)
tool_id = package_id(tool["url"], tool["commit"])
with tempfile.TemporaryDirectory(prefix="pack-", dir=args.output) as staging:
for name, defines in PROFILES.items():
file = Path(staging) / f"{name}.zx"
feature_flags = [arg for define in defines for arg in ("--define", define)]
run(launcher, "pkg", "zx", operation, REPOSITORY, commit, name, str(file), *feature_flags, *flags)
digest, fingerprint = inspect_library(launcher, file, provider, tool_id, name, development=args.development)
profiles[name] = {"file": file.name, "defines": defines, "sha256": digest}
if fingerprint is not None:
profiles[name]["source_sha256"] = fingerprint
for profile in profiles.values():
file = profile["file"]
(Path(staging) / file).replace(args.output / file)
save_json(args.output / "manifest.json", {
"format": 1, "kind": "zx-library", "repository": REPOSITORY, "commit": commit,
"package": provider, "development": args.development, "exports": manifest["exports"], "profiles": profiles,
"toolchain": {"url": tool["url"], "commit": tool["commit"], "id": tool_id},
"dependencies": {"tcl": {"url": tcl["url"], "commit": tcl["commit"], "id": tcl["id"]}},
})
print(f"Packed {len(profiles)} Tk ZX library profiles in {args.output}")
def verified_library(ziran, directory, catalog, name):
profile = catalog["profiles"][name]
require(profile["file"] == f"{name}.zx" and tuple(profile["defines"]) == PROFILES[name],
f"unexpected artifact recipe for {name}")
path = directory / profile["file"]
sha = profile["sha256"]
_, fingerprint = inspect_library(ziran, path, catalog["package"], catalog["toolchain"]["id"], name, sha,
development=catalog["development"])
require(profile.get("source_sha256") == fingerprint, f"source fingerprint mismatch for {path}")
return path, sha
def read_catalog(directory, tcl, tool, development):
catalog = read_json(directory / "manifest.json")
require(catalog["format"] == 1 and catalog["kind"] == "zx-library"
and catalog["repository"] == REPOSITORY and hex_string(catalog["commit"], 40)
and catalog["development"] is development and set(catalog["profiles"]) == PROFILES.keys()
and catalog["package"] == package_id(REPOSITORY, catalog["commit"]), "invalid checked Tk producer manifest")
require(catalog["dependencies"]["tcl"] == {key: tcl[key] for key in ("url", "id", "commit")}
and catalog["toolchain"] == {"url": tool["url"], "commit": tool["commit"],
"id": package_id(tool["url"], tool["commit"])},
"artifact manifest differs from the locked Tcl or toolchain identity")
return catalog
def publish(args):
manifest, _, tcl, tool = graph()
catalog = read_catalog(args.output, tcl, tool, False)
require(args.netrc.is_file() and args.netrc.stat().st_mode & 0o077 == 0,
"Pass a private netrc file with --netrc")
require(catalog["commit"] == provider_revision() and catalog["exports"] == manifest["exports"],
"packed files do not match the clean provider checkout")
# Validate the entire set before the first upload.
checked = {name: verified_library(args.ziran, args.output, catalog, name) for name in PROFILES}
for name, (file, sha) in checked.items():
result = run(args.ziran, "pkg", "zx", "publish-ir", REPOSITORY, catalog["commit"], name, str(file),
"--netrc", str(args.netrc.resolve()), capture=True)
require(result.strip() == sha, f"registry returned the wrong SHA-256 for {name}")
print(f"Published {len(checked)} Tk ZX library profiles")
def library_url(repository, commit, profile):
name = repository.rsplit("/", 1)[1].removesuffix(".git")
return f"https://git.waozi.xyz/api/packages/ziranlang/generic/{name}-zx-library/{commit}/{profile}.zx"
def fixture_transport(app, env, routes):
fixture = app / "registry"
fixture.mkdir()
save_json(fixture / "routes.json", {url: str(path.resolve()) for url, path in routes.items()})
curl = fixture / "curl"
# Serve checked bytes at the canonical registry URLs without live network access.
curl.write_text(f"#!{sys.executable}\n" + """import json
from pathlib import Path
import shutil
import sys
root = Path(__file__).resolve().parent
args = sys.argv[1:]
assert args[-2] == "--" and "--upload-file" not in args
source = json.loads((root / "routes.json").read_text())[args[-1]]
with (root / "requests").open("a", encoding="ascii") as requests:
requests.write(args[-1] + "\\n")
shutil.copyfile(source, args[args.index("--output") + 1])
print("200", end="")
""", encoding="utf-8")
curl.chmod(0o700)
return {**env, "PATH": f"{fixture}:{env['PATH']}",
"XDG_CACHE_HOME": str(app / "cache"), "GIT_ALLOW_PROTOCOL": ""}, fixture / "requests"
def fetch_library(ziran, node, profile, digest, *, app=ROOT, env=None):
fetched = run(ziran, "pkg", "zx", "fetch-ir", node["url"], node["commit"], profile, digest,
cwd=app, env=env, capture=True).strip()
path = Path(fetched)
require(path.is_file() and path.suffix == ".zx" and object_sha(path) == digest,
f"fetch-ir did not return the pinned {node['name']} {profile} ZX library")
return path
def discovery_smoke(launcher, compiler, tool, app, env, packages, libraries, registry):
app.mkdir()
routes = {}
expected_pins = {}
tool_id = package_id(tool["url"], tool["commit"])
for node, (file, digest) in zip(packages, libraries, strict=True):
url = library_url(node["url"], node["commit"], "default")
descriptor = app / f"{node['name']}.zx.tsv"
descriptor.write_text(descriptor_text(node["id"], tool_id, "default", digest), encoding="ascii")
routes[url] = file
routes[url + ".tsv"] = descriptor
expected_pins[node["name"]] = {"profile": "default", "sha256": digest, "toolchain": tool_id}
env = {**env, "XDG_CACHE_HOME": str(app / "cache")}
if registry:
requests = None
else:
env, requests = fixture_transport(app, env, routes)
(app / "ziran.toml").write_text(f'''[package]
name = "tk_discovery_smoke"
module_roots = ["."]
[toolchain]
git = "{tool['url']}"
ref = "{tool['commit']}"
''', encoding="utf-8")
(app / "ziran.local.toml").write_text(f"[overrides]\nziran = {json.dumps(str(compiler))}\n", encoding="utf-8")
lock_path = app / "ziran.lock"
tcl, tk = packages
run(launcher, "add", tk["url"], "--ref", tk["commit"], cwd=app, env=env)
transitive = read_json(lock_path)
rows = {node["id"]: node for node in transitive["packages"]}
require(transitive["root"]["dependencies"] == {"tk": tk["id"]}
and rows[tk["id"]]["dependencies"] == {"tcl": tcl["id"]},
"adding Tk must record its transitive Tcl dependency")
tcl_revision = rows[rows[tk["id"]]["dependencies"]["tcl"]]["commit"]
require(tcl_revision == tcl["commit"], "Tk resolved a different Tcl revision")
run(launcher, "add", tcl["url"], "--ref", tcl_revision, cwd=app, env=env)
saved = lock_path.read_bytes()
locked = read_json(lock_path)
rows = {node["name"]: node for node in locked["packages"]}
require(len(locked["packages"]) == len(packages) and
{name: row["checked"] for name, row in rows.items()} == expected_pins and
locked["root"]["dependencies"] == {node["name"]: node["id"] for node in packages} and
rows["tk"]["dependencies"] == {"tcl": tcl["id"]} and rows["tk"]["id"] == tk["id"],
"ordinary add did not pin one Tcl identity shared with Tk")
if requests is not None:
before = requests.read_bytes()
require(set(before.decode("ascii").splitlines()) == routes.keys(), "add did not fetch both descriptors and libraries")
run(launcher, "lock", "--offline", cwd=app, env=env)
require(lock_path.read_bytes() == saved and not (app / "ziran.zx.lock").exists(),
"offline lock did not preserve the discovered library pins in ziran.lock")
shutil.copyfile(ROOT / "tests/discovery_smoke.zi", app / "discovery_smoke.zi")
run(launcher, "bundle", "--project", "--offline", "--entry", "discovery_smoke:main", "-o", "app.zx",
"discovery_smoke.zi", cwd=app, env=env)
actual = run(launcher, "run", "--backend", "engine", "app.zx", cwd=app, env=env, capture=True)
require(actual == "42\n0\n", f"Unexpected result from automatically discovered Tcl and Tk libraries\n{actual}")
require((requests is None or requests.read_bytes() == before) and not (app / "cache/ziran/sources").exists(),
"offline build fetched a provider or materialized its source cache")
print("Ordinary add and offline lock preserved both default libraries and the shared Tcl state")
def smoke(args):
manifest, lock, tcl, tool = graph()
compiler, tool, _ = toolchain(args, tcl, tool)
launcher = compiler / "build/bin/ziran"
digest = args.tcl_sha256 if args.development else tcl["checked"]["sha256"]
require(hex_string(digest, 64), "Pass the Tcl development library digest with --tcl-sha256")
require(args.tcl_sha256 in (None, digest), "Tcl library digest differs from ziran.lock")
require(not args.development or args.tcl_library is not None, "Pass the Tcl development file with --tcl-library")
catalog = read_catalog(args.output, tcl, tool, args.development)
require(catalog["commit"] == git(ROOT, "rev-parse", "HEAD") and catalog["exports"] == manifest["exports"],
"artifact manifest does not match this Tk revision")
checked = {name: verified_library(launcher, args.output, catalog, name) for name in PROFILES}
profile = "full"
library, sha = checked[profile]
tk = {"id": catalog["package"], "name": "tk", "url": REPOSITORY, "commit": catalog["commit"],
"ref": catalog["commit"], "dependencies": lock["root"]["dependencies"],
"dependency_refs": lock["root"]["dependency_refs"]}
dependencies = ({key: value for key, value in tcl.items() if key != "checked"}, tk)
tcl_library = args.tcl_library
if not args.registry and tcl_library is None:
tcl_library = fetch_library(launcher, tcl, "default", digest)
if tcl_library is not None:
inspect_library(launcher, tcl_library, tcl["id"], catalog["toolchain"]["id"], "default", digest,
development=args.development)
with tempfile.TemporaryDirectory(prefix="artifact-smoke-", dir=args.output) as scratch:
app = Path(scratch)
env = os.environ.copy()
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR",
"SESSION_MANAGER", "ZIRAN_PACKAGE_MAP", "ZIRAN_LOCK_GIT_OBJECTS", "ZIRAN_PACKAGE_NETRC",
"ZIRAN_PINNED_LAUNCHER", "ZIRAN_ZX_PROFILE", "ZIRAN_ZX_REGISTRY", "ZIRAN_DEV_ZX_DIR"):
env.pop(key, None)
env.update(XDG_CACHE_HOME=str(app / "cache"), GIT_ALLOW_PROTOCOL="")
entries = ["[package]\nname = 'tk_artifact_smoke'\nmodule_roots = ['.']\n",
f"[toolchain]\ngit = '{tool['url']}'\nref = '{tool['commit']}'\n"]
entries.extend(f"[dependencies.{node['name']}]\ngit = '{node['url']}'\nref = '{node['commit']}'\n"
for node in dependencies)
(app / "ziran.toml").write_text("\n".join(entries), encoding="utf-8")
save_json(app / "ziran.lock", {"format": 1, "toolchain": tool, "packages": list(dependencies),
"root": {"name": "tk_artifact_smoke",
"dependencies": {node["name"]: node["id"] for node in dependencies},
"dependency_refs": {node["name"]: node["commit"] for node in dependencies}}})
(app / "ziran.local.toml").write_text(f"[overrides]\nziran = {json.dumps(str(compiler))}\n", encoding="utf-8")
for file in ("widgets_test.zi", "widget_fixtures.zi"):
shutil.copyfile(ROOT / "tests" / file, app / file)
features = [arg for define in PROFILES[profile] for arg in ("--define", define)]
project = ("--project", "--offline", *features, "--entry", "widgets_test:main")
bundle = (launcher, "bundle", *project, "-o", "app.zx", "widgets_test.zi")
requests = None
if args.development:
stage = app / "libraries"
stage.mkdir()
shutil.copyfile(tcl_library, stage / f"{tcl['id']}.zx")
shutil.copyfile(library, stage / f"{tk['id']}.zx")
env["ZIRAN_DEV_ZX_DIR"] = str(stage)
else:
save_json(app / "ziran.zx.lock", {"format": 1, "packages": [
{"package": tcl["id"], "profile": "default", "sha256": digest},
{"package": tk["id"], "profile": profile, "sha256": sha},
]})
if not args.registry:
routes = {library_url(REPOSITORY, tk["commit"], name): path for name, (path, _) in checked.items()}
routes[library_url(tcl["url"], tcl["commit"], "default")] = tcl_library
env, requests = fixture_transport(app, env, routes)
missing = subprocess.run(bundle, cwd=app, env=env, text=True, capture_output=True)
require(missing.returncode != 0 and "absent from the offline cache" in missing.stderr,
f"Expected a library failure with the empty cache\n{missing.stdout}{missing.stderr}")
tcl_library = fetch_library(launcher, tcl, "default", digest, app=app, env=env)
for name, (_, library_digest) in checked.items():
fetch_library(launcher, tk, name, library_digest, app=app, env=env)
if requests is not None:
before = requests.read_bytes()
require(set(before.decode("ascii").splitlines()) == routes.keys(), "fetch-ir did not verify every library")
run(*bundle, cwd=app, env=env)
actual = run(launcher, "run", "--backend", "engine", "app.zx", cwd=app, env=env, capture=True)
expected = (ROOT / "tests/widgets_test.out").read_text(encoding="utf-8")
require(actual == expected + "0\n", f"Unexpected Tcl/Tk output from the source-free ZX consumer\n{actual}")
run(launcher, "build", *project, "--target=c", "--exe", "-o", "native", "widgets_test.zi", cwd=app, env=env)
native = run(app / "native/widgets_test", cwd=app, env=env, capture=True)
require(native == expected, f"Unexpected Tcl/Tk output from the source-free native consumer\n{native}")
require((requests is None or requests.read_bytes() == before) and not (app / "cache/ziran/sources").exists(),
"offline build fetched a provider or materialized its source cache")
if not args.development:
discovery_smoke(launcher, compiler, tool, app / "discovery", env, dependencies,
((tcl_library, digest), checked["default"]), args.registry)
mode = "development" if args.development else "Gitea" if args.registry else "production fixture"
print(f"Verified {len(checked)} Tk {mode} ZX libraries. Source-free native and ZX consumers matched widgets_test.out")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ziran", default=os.environ.get("ZIRAN", "ziran"))
commands = parser.add_subparsers(dest="command", required=True)
for name in ("pack", "smoke", "publish"):
command = commands.add_parser(name)
command.add_argument("--output", type=Path)
if name == "pack":
command.add_argument("--development", action="store_true")
if name == "smoke":
source = command.add_mutually_exclusive_group()
source.add_argument("--development", action="store_true")
source.add_argument("--registry", action="store_true")
command.add_argument("--tcl-library", type=Path)
command.add_argument("--tcl-sha256")
if name == "publish":
command.add_argument("--netrc", type=Path, required=True)
args = parser.parse_args()
if args.output is None:
args.output = ROOT / ("build/artifacts-dev" if getattr(args, "development", False) else "build/artifacts")
args.output = args.output.resolve()
try:
{"pack": pack, "smoke": smoke, "publish": publish}[args.command](args)
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
parser.exit(1, f"{error}\n")
if __name__ == "__main__":
main()