289 lines
14 KiB
Python
289 lines
14 KiB
Python
"""Build and verify the relocatable Tcl library with the Ziran package driver."""
|
|
|
|
import argparse
|
|
from contextlib import contextmanager
|
|
import hashlib
|
|
import http.server
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shlex
|
|
import shutil
|
|
import ssl
|
|
import subprocess
|
|
import tempfile
|
|
import threading
|
|
import tomllib
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
REPOSITORY = "https://git.waozi.xyz/ziranlang/tcl.git"
|
|
PROFILE = "default"
|
|
TOOL_REPOSITORY = "https://git.waozi.xyz/ziranlang/ziran.git"
|
|
ZIRAN = os.environ.get("ZIRAN", "ziran")
|
|
|
|
|
|
def command(*args, cwd=ROOT, env=None, strip=True):
|
|
output = subprocess.run(args, cwd=cwd, env=env, text=True, check=True, timeout=90,
|
|
stdout=subprocess.PIPE).stdout
|
|
return output.strip() if strip else output
|
|
|
|
|
|
def git(*args, cwd=ROOT):
|
|
return command("git", *args, cwd=cwd)
|
|
|
|
|
|
def require(condition, message):
|
|
if not condition:
|
|
raise ValueError(message)
|
|
|
|
|
|
def digest_file(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 output_paths(development):
|
|
directory = ROOT / ("build/artifacts-dev" if development else "build/artifacts")
|
|
return directory / f"{PROFILE}.zx", directory / f"{PROFILE}.json"
|
|
|
|
|
|
def read_project(development):
|
|
manifest = tomllib.loads((ROOT / "ziran.toml").read_text())
|
|
lock = json.loads((ROOT / "ziran.lock").read_text())
|
|
pin = dict(lock["toolchain"])
|
|
require(pin["url"] == TOOL_REPOSITORY == manifest["toolchain"]["git"],
|
|
"The toolchain must name the canonical Ziran repository")
|
|
require(pin["ref"] == pin["commit"] == manifest["toolchain"]["ref"]
|
|
and re.fullmatch(r"[0-9a-f]{40}", pin["commit"]),
|
|
"The Tcl toolchain lock must pin an exact Git revision")
|
|
flags = ("--offline",) if development else ("--locked", "--offline")
|
|
toolchain = Path(command(ZIRAN, "pkg", "path", "ziran", *flags)).resolve()
|
|
tool_commit = git("rev-parse", "HEAD", cwd=toolchain)
|
|
if development:
|
|
pin.update(ref=tool_commit, commit=tool_commit)
|
|
else:
|
|
require(tool_commit == pin["commit"], "The compiler checkout differs from ziran.lock")
|
|
require(not git("status", "--porcelain", cwd=toolchain), "The compiler checkout is dirty")
|
|
return manifest, lock, pin, toolchain
|
|
|
|
|
|
def provenance(library, manifest, lock, pin, development):
|
|
commit = git("rev-parse", "HEAD")
|
|
provider = package_id(REPOSITORY, commit)
|
|
require(library.is_file() and library.stat().st_size > 0, "The compiler did not produce a ZX library")
|
|
return {"format": 1, "repository": REPOSITORY, "commit": commit, "package": provider,
|
|
"profile": PROFILE, "sha256": digest_file(library), "toolchain": pin,
|
|
"dependencies": lock["packages"], "exports": manifest["exports"],
|
|
"development": development}
|
|
|
|
|
|
def inspect_library(launcher, library, data):
|
|
toolchain = data["toolchain"]
|
|
tool_id = package_id(toolchain["url"], toolchain["commit"])
|
|
descriptor = command(launcher, "pkg", "zx", "inspect-ir", library, strip=False)
|
|
expected = f"2\t{data['package']}\t{tool_id}\t{data['profile']}\t{data['sha256']}\n"
|
|
if data["development"]:
|
|
fields = descriptor.removesuffix("\n").split("\t")
|
|
require(len(fields) == 6 and fields[:4] == ["dev", data["package"], tool_id, PROFILE]
|
|
and re.fullmatch(r"[0-9a-f]{64}", fields[4]) and fields[5] == data["sha256"],
|
|
"Expected a development ZX library with matching provider, toolchain, profile and digest")
|
|
data["source_sha256"] = fields[4]
|
|
else:
|
|
require(descriptor == expected, "The ZX library has a different provider, toolchain, profile or digest")
|
|
return descriptor.encode()
|
|
|
|
|
|
def build(development):
|
|
origin = git("remote", "get-url", "origin")
|
|
require(origin in (REPOSITORY, REPOSITORY.removesuffix(".git")), "Unexpected Tcl origin")
|
|
if not development:
|
|
require(not git("status", "--porcelain"), "Production artifacts need the exact clean Tcl revision")
|
|
manifest, lock, pin, toolchain = read_project(development)
|
|
launcher = toolchain / "build/bin/ziran"
|
|
library, receipt = output_paths(development)
|
|
library.parent.mkdir(parents=True, exist_ok=True)
|
|
flags = ("--offline",) if development else ("--locked", "--offline")
|
|
pack = "pack-dev" if development else "pack-ir"
|
|
with tempfile.TemporaryDirectory(prefix="pack-", dir=library.parent) as staging:
|
|
output = Path(staging) / library.name
|
|
command(launcher, "pkg", "zx", pack, REPOSITORY, git("rev-parse", "HEAD"), PROFILE, output, *flags)
|
|
data = provenance(output, manifest, lock, pin, development)
|
|
inspect_library(launcher, output, data)
|
|
output.replace(library)
|
|
with tempfile.NamedTemporaryFile(mode="w", dir=receipt.parent, delete=False) as temporary:
|
|
temporary.write(json.dumps(data, indent=2, sort_keys=True) + "\n")
|
|
Path(temporary.name).replace(receipt)
|
|
print(f"{library.relative_to(ROOT)} {data['sha256']}")
|
|
|
|
|
|
def verify_outputs(development):
|
|
manifest, lock, pin, toolchain = read_project(development)
|
|
library, receipt = output_paths(development)
|
|
data = provenance(library, manifest, lock, pin, development)
|
|
descriptor = inspect_library(toolchain / "build/bin/ziran", library, data)
|
|
require(json.loads(receipt.read_text()) == data, "Artifact metadata no longer matches the library and checkout")
|
|
return library, data, toolchain, descriptor
|
|
|
|
|
|
@contextmanager
|
|
def fixture_registry(directory, library, data, descriptor):
|
|
namespace = f"/api/packages/ziranlang/generic/tcl-zx-library/{data['commit']}/{data['profile']}.zx"
|
|
paths = [f"{namespace}.tsv", namespace]
|
|
requests = []
|
|
|
|
class Registry(http.server.BaseHTTPRequestHandler):
|
|
def log_message(self, *_):
|
|
pass
|
|
|
|
def do_GET(self):
|
|
requests.append(self.path)
|
|
if self.path not in paths:
|
|
self.send_error(404)
|
|
return
|
|
metadata = self.path == paths[0]
|
|
self.send_response(200)
|
|
self.send_header("Content-Length", str(len(descriptor) if metadata else library.stat().st_size))
|
|
self.end_headers()
|
|
if metadata:
|
|
self.wfile.write(descriptor)
|
|
else:
|
|
with library.open("rb") as source:
|
|
shutil.copyfileobj(source, self.wfile)
|
|
|
|
key = directory / "registry.key"
|
|
certificate = directory / "registry.pem"
|
|
subprocess.run(["openssl", "req", "-new", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1",
|
|
"-subj", "/CN=git.waozi.xyz", "-addext", "subjectAltName=DNS:git.waozi.xyz",
|
|
"-keyout", key, "-out", certificate], check=True, capture_output=True)
|
|
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
tls.load_cert_chain(certificate, key)
|
|
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Registry) as server:
|
|
server.socket = tls.wrap_socket(server.socket, server_side=True)
|
|
thread = threading.Thread(target=server.serve_forever)
|
|
thread.start()
|
|
try:
|
|
# Keep the canonical TLS hostname and package identity while
|
|
# routing the fixture process's registry requests to loopback.
|
|
client = shutil.which("curl")
|
|
require(client is not None, "The registry smoke needs curl")
|
|
wrapper = directory / "curl"
|
|
wrapper.write_text(f'#!/bin/sh\nexec {shlex.quote(client)} --disable --connect-to '
|
|
f'git.waozi.xyz:443:127.0.0.1:{server.server_port} "$@"\n')
|
|
wrapper.chmod(0o700)
|
|
yield certificate
|
|
require(requests == paths, f"Unexpected registry requests during ziran add: {requests}")
|
|
finally:
|
|
server.shutdown()
|
|
thread.join()
|
|
|
|
|
|
def smoke(development, registry):
|
|
require(not (development and registry), "Development libraries use a local library directory")
|
|
library, data, toolchain, descriptor = verify_outputs(development)
|
|
require(data["dependencies"] == [], "The smoke seeds Tcl only and has no transitive package artifacts")
|
|
fixture = ROOT / "tests/fixtures/core.tcl"
|
|
expected = fixture.with_suffix(".out").read_text()
|
|
launcher = toolchain / "build/bin/ziran"
|
|
pin = data["toolchain"]
|
|
|
|
with tempfile.TemporaryDirectory(prefix="artifact-smoke-", dir=library.parent) as scratch:
|
|
app = Path(scratch)
|
|
cache = app / "cache"
|
|
env = os.environ.copy()
|
|
env["XDG_CACHE_HOME"] = str(cache)
|
|
env["GIT_ALLOW_PROTOCOL"] = ""
|
|
for key in ("ZIRAN_PACKAGE_MAP", "ZIRAN_LOCK_GIT_OBJECTS", "ZIRAN_PACKAGE_NETRC", "ZIRAN_PINNED_LAUNCHER",
|
|
"ZIRAN_ZX_REGISTRY", "ZIRAN_ZX_PROFILE", "ZIRAN_DEV_ZX_DIR"):
|
|
env.pop(key, None)
|
|
|
|
(app / "ziran.toml").write_text(f'''[package]
|
|
name = "tcl_artifact_smoke"
|
|
module_roots = ["."]
|
|
|
|
[toolchain]
|
|
git = "{pin['url']}"
|
|
ref = "{pin['commit']}"
|
|
''')
|
|
# Reuse the verified local compiler without adding a Tcl source override.
|
|
(app / "ziran.local.toml").write_text(f"[overrides]\nziran = {json.dumps(str(toolchain))}\n")
|
|
shutil.copyfile(ROOT / "tests/artifact_smoke.zi", app / "app.zi")
|
|
(app / "fixture.zi").write_text("Script :: #string TCL_SMOKE_END\n" + fixture.read_text() + "TCL_SMOKE_END;\n")
|
|
|
|
lock = app / "ziran.lock"
|
|
if development:
|
|
stage = app / "libraries"
|
|
stage.mkdir()
|
|
shutil.copyfile(library, stage / f"{data['package']}.zx")
|
|
env["ZIRAN_DEV_ZX_DIR"] = str(stage)
|
|
with (app / "ziran.toml").open("a", encoding="utf-8") as manifest:
|
|
manifest.write(f'\n[dependencies.tcl]\ngit = "{REPOSITORY}"\nref = "{data["commit"]}"\n')
|
|
node = {"id": data["package"], "name": "tcl", "url": REPOSITORY, "commit": data["commit"],
|
|
"ref": data["commit"], "dependencies": {}}
|
|
lock.write_text(json.dumps({"format": 1, "packages": [node], "toolchain": pin,
|
|
"root": {"name": "tcl_artifact_smoke", "dependencies": {"tcl": node["id"]},
|
|
"dependency_refs": {"tcl": node["commit"]}}}), encoding="utf-8")
|
|
else:
|
|
add = (launcher, "add", REPOSITORY, "--ref", data["commit"])
|
|
if registry:
|
|
command(*add, cwd=app, env=env)
|
|
else:
|
|
with fixture_registry(app, library, data, descriptor) as certificate:
|
|
fixture_env = {**env, "PATH": f"{app}{os.pathsep}{env['PATH']}",
|
|
"CURL_CA_BUNDLE": str(certificate), "NO_PROXY": "git.waozi.xyz", "no_proxy": "git.waozi.xyz"}
|
|
command(*add, cwd=app, env=fixture_env)
|
|
saved = lock.read_bytes()
|
|
entries = json.loads(saved)["packages"]
|
|
checked = {"profile": PROFILE, "sha256": data["sha256"], "toolchain": package_id(pin["url"], pin["commit"])}
|
|
require(len(entries) == 1 and entries[0]["id"] == data["package"] and entries[0]["checked"] == checked,
|
|
"ziran add did not lock the exact relocatable Tcl library")
|
|
require(not (app / "ziran.zx.lock").exists(), "Expected a library pin in ziran.lock")
|
|
command(launcher, "lock", "--offline", cwd=app, env=env)
|
|
require(lock.read_bytes() == saved, "Offline lock changed the selected Tcl library")
|
|
command(launcher, "bundle", "--project", "--offline", "--entry", "app:main", "-o", "app.zx", "app.zi",
|
|
cwd=app, env=env)
|
|
actual = command(launcher, "run", "--backend", "engine", "app.zx", cwd=app, env=env, strip=False)
|
|
require(actual == expected + "0\n", f"Unexpected Tcl output from the source-free consumer\n{actual}")
|
|
require(not (cache / "ziran/sources").exists(), "The consumer materialized a source cache")
|
|
mode = "Development library" if development else "Gitea library" if registry else "TLS registry fixture library"
|
|
print(f"{mode}: offline bundle and run matched core.tcl without Tcl source")
|
|
|
|
|
|
def publish(netrc):
|
|
library, data, toolchain, _ = verify_outputs(False)
|
|
require(not git("status", "--porcelain"), "Publishing needs the exact clean Tcl revision")
|
|
require(netrc.is_file() and netrc.stat().st_mode & 0o077 == 0, "Pass a private netrc file with --netrc")
|
|
published = command(toolchain / "build/bin/ziran", "pkg", "zx", "publish-ir", REPOSITORY,
|
|
data["commit"], PROFILE, library, "--netrc", netrc.resolve())
|
|
require(published == data["sha256"], "Gitea publication returned a different SHA-256")
|
|
print(published)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
commands.add_parser("build").add_argument("--development", action="store_true")
|
|
source = commands.add_parser("smoke").add_mutually_exclusive_group()
|
|
source.add_argument("--development", action="store_true")
|
|
source.add_argument("--registry", action="store_true")
|
|
commands.add_parser("publish").add_argument("--netrc", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
try:
|
|
if args.command == "build":
|
|
build(args.development)
|
|
elif args.command == "smoke":
|
|
smoke(args.development, args.registry)
|
|
else:
|
|
publish(args.netrc)
|
|
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error:
|
|
parser.exit(1, f"{error}\n")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|