#!/usr/bin/env python3 """Build the deterministic marqdo-knowledge beta release archive. The archive is reproducible: sorted entries, commit timestamp for all mtimes, uid/gid 0, normalised modes, gzip without a timestamp. It refuses a dirty tree, a version that does not match `Cargo.toml`, or a HEAD that differs from `--source-sha`. It never publishes anything; tagging is a separate reviewed step. Usage (from the repository root, after `cargo build --release --locked`): python3 tools/release/package.py \ --source-sha "$(git rev-parse HEAD)" \ --version "$(sed -n 's/^version = \"\\(.*\\)\"/\\1/p' Cargo.toml | head -1)" """ from __future__ import annotations import argparse import datetime import gzip import hashlib import json import re import shutil import subprocess import sys import tarfile import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[2] TARGET = "x86_64-unknown-linux-gnu" CORE_BASELINE = ( "cflmy/marqdo-cli@4bbefc92449ee480c8a2c89b0308feb4cda8d0e7 (3.0.0-rc.4)" ) COPY_FILES = ( "README.md", "LICENSE-APACHE", "CHANGELOG.md", "docs/STATUS.md", "docs/ci.md", "docs/releasing.md", ) COPY_TREES = ( "docs/architecture", "docs/releases", "examples", "spec", ) SKIP_TREE_PARTS = {".git", ".marqdo", "target", "dist", ".cargo-home", ".scratch"} SKIP_SUFFIXES = {".sqlite", ".sqlite-journal", ".sqlite-wal", ".sqlite-shm"} def fail(message: str) -> "NoReturn": print(f"package: error: {message}", file=sys.stderr) raise SystemExit(1) def run(command: list[str], *, cwd: Path = ROOT, capture: bool = False) -> str: completed = subprocess.run( command, cwd=cwd, check=True, text=True, capture_output=capture, ) return completed.stdout.strip() if capture else "" def git(*args: str) -> str: return run(["git", *args], capture=True) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def cargo_version() -> str: text = (ROOT / "Cargo.toml").read_text(encoding="utf-8") match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text) if not match: fail("Cargo.toml has no package version") return match.group(1) def check_version_consistency(version: str) -> None: if cargo_version() != version: fail(f"--version {version} does not match Cargo.toml {cargo_version()}") lock = (ROOT / "Cargo.lock").read_text(encoding="utf-8") match = re.search( r'\[\[package\]\]\nname = "marqdo-knowledge"\nversion = "([^"]+)"', lock ) if not match or match.group(1) != version: fail("Cargo.lock marqdo-knowledge version does not match Cargo.toml") tool = json.loads((ROOT / "packaging/tool.json").read_text(encoding="utf-8")) if tool.get("version") != version: fail("packaging/tool.json version does not match Cargo.toml") if tool.get("entrypoint") != "bin/marqdo-knowledge": fail("packaging/tool.json entrypoint must be bin/marqdo-knowledge") if tool.get("requires") != {"api_revision": 1, "analysis": 3}: fail("packaging/tool.json requires must be exactly api_revision 1 / analysis 3") spec = (ROOT / "spec/knowledge.md").read_text(encoding="utf-8") if f'"version": "{version}"' not in spec: fail("spec/knowledge.md tool identity version is stale") notes = ROOT / "docs/releases" / f"{version}.md" if not notes.is_file(): fail(f"missing release notes {notes.relative_to(ROOT)}") def clean_tree() -> None: status = git("status", "--porcelain") if status: fail("working tree is dirty; commit before packaging") head = git("rev-parse", "HEAD") if not re.fullmatch(r"[a-f0-9]{40}", head): fail("HEAD is not a full commit sha") return head def collect_examples(stage: Path, version: str) -> None: examples = ROOT / "examples" if not examples.is_dir(): fail("examples directory is missing") for path in sorted(examples.rglob("*")): relative = path.relative_to(ROOT) if any(part in SKIP_TREE_PARTS for part in relative.parts): continue if path.is_dir() or path.suffix in SKIP_SUFFIXES: continue destination = stage / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, destination) # The compiled database is never shipped. for stale in stage.rglob(".marqdo"): if stale.is_dir(): shutil.rmtree(stale) if not (stage / "examples/mixed/notes.md").is_file(): fail("examples/mixed is missing from the staged archive") def build_stage(stage: Path, version: str, source_sha: str, commit_time: datetime.datetime) -> None: binary = ROOT / "target/release/marqdo-knowledge" if not binary.is_file(): fail("target/release/marqdo-knowledge is missing; run cargo build --release --locked") (stage / "bin").mkdir(parents=True) shutil.copyfile(binary, stage / "bin/marqdo-knowledge") (stage / "bin/marqdo-knowledge").chmod(0o755) for name in COPY_FILES: source = ROOT / name if not source.is_file(): fail(f"missing required file {name}") shutil.copyfile(source, stage / name) shutil.copyfile(ROOT / "packaging/tool.json", stage / "tool.json") for tree in COPY_TREES: source = ROOT / tree if not source.is_dir(): fail(f"missing required directory {tree}") for path in sorted(source.rglob("*")): if path.is_dir() or path.suffix in SKIP_SUFFIXES: continue if any(part in SKIP_TREE_PARTS for part in path.relative_to(ROOT).parts): continue destination = stage / path.relative_to(ROOT) destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, destination) collect_examples(stage, version) (stage / "SOURCE_SHA").write_text(source_sha + "\n", encoding="utf-8") # Per-file manifest. FILES.sha256 and RELEASE_INFO.json are themselves not # listed, so the manifest stays independent of these metadata files. files = [] for path in sorted(stage.rglob("*")): if not path.is_file(): continue relative = path.relative_to(stage).as_posix() if relative in {"FILES.sha256", "RELEASE_INFO.json"}: continue files.append((relative, sha256_file(path), path.stat().st_size)) manifest_lines = "".join( f"{digest} {relative}\n" for relative, digest, _size in files ) (stage / "FILES.sha256").write_text(manifest_lines, encoding="utf-8") manifest_digest = sha256_file(stage / "FILES.sha256") binary_info = { "sha256": sha256_file(stage / "bin/marqdo-knowledge"), "size": (stage / "bin/marqdo-knowledge").stat().st_size, } info = { "schema": "marqdo.knowledge.release-info", "schema_version": 1, "product": "marqdo-knowledge", "product_version": version, "channel": "beta", "target": TARGET, "build_profile": "release", "source_sha": source_sha, "commit_time_utc": commit_time.strftime("%Y-%m-%dT%H:%M:%SZ"), "protocols": { "cli_tool": 1, "tool_api_revision": 1, "analysis": 3, "sqlite_schema": 1, "okf": "0.3", }, "binaries": {"marqdo-knowledge": binary_info}, "core_baseline": CORE_BASELINE, "files_manifest": "FILES.sha256", "files_manifest_sha256": manifest_digest, "file_count": len(files) + 2, "known_limitations": "docs/STATUS.md", "notes": [ "Checksums prove content integrity only; they are not a publisher signature.", "Install through `marqdo tool install `; direct execution requires a compatible core CLI.", "Run `python3 tools/release/smoke.py --archive ` before publishing.", ], } (stage / "RELEASE_INFO.json").write_text( json.dumps(info, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8", ) def write_archive(stage: Path, commit_time: datetime.datetime, out_dir: Path, version: str) -> Path: out_dir.mkdir(parents=True, exist_ok=True) base = f"marqdo-knowledge-{version}-{TARGET}" archive = out_dir / f"{base}.tar.gz" if archive.exists(): archive.unlink() with tempfile.NamedTemporaryFile(dir=out_dir, delete=False) as raw: raw_path = Path(raw.name) try: with raw_path.open("wb") as raw_file: with gzip.GzipFile(filename="", mode="wb", fileobj=raw_file, mtime=0, compresslevel=9) as compressed: with tarfile.open(fileobj=compressed, mode="w", format=tarfile.GNU_FORMAT) as tar: for path in sorted(stage.rglob("*")): relative = path.relative_to(stage).as_posix() info = tarfile.TarInfo(name=f"{base}/{relative}") info.uid = 0 info.gid = 0 info.uname = "" info.gname = "" info.mtime = int(commit_time.timestamp()) if path.is_dir(): info.type = tarfile.DIRTYPE info.mode = 0o755 tar.addfile(info) else: info.type = tarfile.REGTYPE info.mode = 0o755 if relative.startswith("bin/") else 0o644 info.size = path.stat().st_size with path.open("rb") as handle: tar.addfile(info, handle) shutil.move(raw_path, archive) finally: if raw_path.exists(): raw_path.unlink() digest = sha256_file(archive) checksum = out_dir / f"{archive.name}.sha256" checksum.write_text(f"{digest} {archive.name}\n", encoding="utf-8") print(f"archive: {archive}") print(f"sha256: {digest}") print(f"manifest: {out_dir / 'RELEASE_INFO.json'}") return archive def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-sha", required=True) parser.add_argument("--version", required=True) parser.add_argument("--out-dir", default="dist") args = parser.parse_args() head = clean_tree() if args.source_sha != head: fail(f"--source-sha {args.source_sha} does not match HEAD {head}") check_version_consistency(args.version) version_output = run( [str(ROOT / "target/release/marqdo-knowledge"), "--version"], capture=True ) if version_output != f"marqdo-knowledge {args.version}": fail(f"release binary reports `{version_output}`, expected version {args.version}") commit_epoch = int(git("show", "-s", "--format=%ct", head)) commit_time = datetime.datetime.fromtimestamp(commit_epoch, datetime.timezone.utc) out_dir = (ROOT / args.out_dir).resolve() if not Path(args.out_dir).is_absolute() else Path(args.out_dir) with tempfile.TemporaryDirectory(prefix="marqdo-knowledge-package-") as temporary: stage = Path(temporary) build_stage(stage, args.version, head, commit_time) archive = write_archive(stage, commit_time, out_dir, args.version) shutil.copyfile(stage / "RELEASE_INFO.json", out_dir / "RELEASE_INFO.json") shutil.copyfile(stage / "FILES.sha256", out_dir / "FILES.sha256") print(f"source_sha: {head}") print(f"target: {TARGET}") return 0 if __name__ == "__main__": sys.exit(main())