Files
marqdo/scripts/project-release.py
T
cflmy 507305c9d7 feat: classify .zip library archives as archives in the public projection (marqdo#106)
The projection lists both tar.gz and zip for platform-independent library
releases; .zip must map to the archive asset kind so the website can offer it
as a download format. Add coverage in the independent-release projection test.
2026-12-03 08:56:40 +08:00

684 lines
33 KiB
Python

#!/usr/bin/env python3
"""Project the public release snapshot from verified release facts.
The root repository is the only producer of the public recommendation data.
This script combines three real inputs and refuses to guess anything:
1. `scripts/reconcile-releases.py --plan --report-out` facts: the tag -> source
SHA, `release-evidence.json` digest and asset bytes were verified against
Gitea and Woodpecker for the exact published release;
2. an acceptance record under `docs/release-acceptance/`: the maintainer-approved
product x platform x version x capability scope. Its components must be
pinned by the root Git tree at exactly the published source SHA and its
Bundle dependencies must match the root gitlinks;
3. the recursive component catalog at the projected root commit
(`components.toml` + gitlinks + `.gitmodules`).
Output follows the website's existing read-only contract
(`/data/current.json` pointer plus one immutable
`/data/snapshots/<sha256>.json`). The script never tags, publishes, writes to
Gitea or promotes a component release; it only emits the projection bytes and
fails closed when a fact is missing or inconsistent.
Usage:
python3 scripts/project-release.py \
--root . \
--root-sha "$(git rev-parse HEAD)" \
--reconcile-report reconcile-report.json \
--acceptance docs/release-acceptance/marqdo-linux-x86_64-3.0.0-rc.7.json \
--generated-at 2026-12-02T06:30:00Z \
--revision 0 \
--out-dir dist/public-data
"""
from __future__ import annotations
import argparse
import datetime
import hashlib
import json
import re
import sys
import tomllib
from pathlib import Path
import impact
FORGE = "https://git.cflmy.cn"
CI = "https://ci.cflmy.cn"
SNAPSHOT_SCHEMA_VERSION = 1
POINTER_SCHEMA_VERSION = 1
ACCEPTANCE_SCHEMA = "marqdo.release-acceptance"
ACCEPTANCE_SCHEMA_VERSION = 1
RECONCILE_SCHEMA = "marqdo.release-reconcile.v1"
SHA = re.compile(r"[0-9a-f]{40}")
HEX = re.compile(r"[a-f0-9]{64}")
ID = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9._:@/+~-]{0,199}")
BASENAME = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9._+~-]{0,199}")
TAG = re.compile(r"(?:mqdh-)?v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?")
CHANNELS = ("stable", "alpha", "beta", "rc")
PRODUCTS = ("marqdo", "mqdh")
KINDS = ("core", "tool", "stdlib", "extension", "domain", "app", "test")
STATES = ("active", "planned")
RELEASES = ("base", "optional", "none")
DECISIONS = ("accepted", "rejected")
class ProjectionError(Exception):
pass
def fail(message: str) -> "NoReturn":
raise ProjectionError(message)
def require(condition: bool, message: str) -> None:
if not condition:
fail(message)
def official_url(value, what: str) -> str:
require(isinstance(value, str), f"{what} must be a string")
prefix = value.split("//", 1)[0] if "//" in value else ""
require(prefix == "https:", f"{what} must be https: {value!r}")
require(not any(ch in value for ch in "%\\ "), f"{what} must not contain encoded/space paths")
origin = value.split("/", 3)[:3]
require("/".join(origin) in (FORGE, CI, "https://marqdo.com"), f"{what} has a non-official origin: {value}")
require(not value.endswith("/") or value.count("/") > 3, f"{what} must name a path")
return value
def read_json(path: Path) -> dict:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
fail(f"cannot read {path}: {error}")
require(isinstance(value, dict), f"{path} must contain a JSON object")
return value
def stamp(value: str, what: str) -> str:
try:
parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
except (AttributeError, TypeError, ValueError) as error:
fail(f"{what} is not ISO-8601: {error}")
require(parsed.tzinfo is not None, f"{what} must carry a time zone")
return value
def utc_z(value: str, what: str) -> str:
"""Normalize an ISO-8601 timestamp to the website contract (`...Z`)."""
stamp(value, what)
parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(datetime.timezone.utc)
return parsed.replace(microsecond=0).isoformat().replace("+00:00", "Z")
def channel_of(version: str) -> str:
require(isinstance(version, str) and TAG.fullmatch(f"v{version}"), f"invalid release version {version!r}")
suffix = version.split("-", 1)[1] if "-" in version else ""
if not suffix:
return "stable"
label = suffix.split(".", 1)[0]
require(label in ("alpha", "beta", "rc"), f"unknown prerelease label {label!r}")
return label
def load_acceptance(path: Path) -> dict:
record = read_json(path)
required = {
"schema", "schema_version", "product", "channel", "version", "platform",
"root_base_sha", "acceptance_url", "root_release_url", "install_guide_url",
"components", "enabled_capabilities", "excluded_capabilities",
"required_gates", "deferred", "decision", "reviewer", "accepted_at",
}
require(set(record) >= required, f"{path}: missing acceptance fields {sorted(required - set(record))}")
extra = set(record) - required - {"notes"}
require(not extra, f"{path}: unknown acceptance fields {sorted(extra)}")
require(record["schema"] == ACCEPTANCE_SCHEMA and record["schema_version"] == ACCEPTANCE_SCHEMA_VERSION,
f"{path}: unsupported acceptance schema")
require(record["product"] in PRODUCTS, f"{path}: invalid product")
require(record["channel"] in CHANNELS, f"{path}: invalid channel")
require(channel_of(record["version"]) == record["channel"],
f"{path}: channel {record['channel']} does not match version {record['version']}")
require(record["decision"] in DECISIONS, f"{path}: invalid decision")
stamp(record["accepted_at"], f"{path}: accepted_at")
require(isinstance(record["reviewer"], str) and record["reviewer"].strip(), f"{path}: reviewer is required")
for field in ("acceptance_url", "root_release_url", "install_guide_url"):
official_url(record[field], f"{path}: {field}")
require(isinstance(record["root_base_sha"], str) and SHA.fullmatch(record["root_base_sha"]),
f"{path}: root_base_sha must be a full commit SHA")
platform = record["platform"]
require(isinstance(platform, dict) and set(platform) >= {"target", "os", "arch"},
f"{path}: platform needs target/os/arch")
require(isinstance(platform["target"], str) and BASENAME.fullmatch(platform["target"]),
f"{path}: invalid platform target")
require(isinstance(platform.get("minimum_runtime"), str), f"{path}: platform.minimum_runtime is required")
require(isinstance(record["enabled_capabilities"], list) and record["enabled_capabilities"],
f"{path}: enabled_capabilities is required")
require(isinstance(record["excluded_capabilities"], list), f"{path}: excluded_capabilities must be a list")
require(isinstance(record["components"], list) and record["components"], f"{path}: components are required")
require(isinstance(record["required_gates"], dict), f"{path}: required_gates must be an object")
require(isinstance(record["deferred"], list), f"{path}: deferred must be a list")
for item in record["deferred"]:
require(isinstance(item, dict) and set(item) >= {"item", "state", "scope", "tracker", "reason", "risk", "revisit"},
f"{path}: deferred item is missing fields")
official_url(item["tracker"], f"{path}: deferred tracker")
for component in record["components"]:
require(isinstance(component, dict) and set(component) >= {"id", "release"},
f"{path}: accepted component needs id/release")
release = component["release"]
require(isinstance(release, dict) and set(release) >= {"repository", "tag", "source_sha", "index_sha256"},
f"{path}: accepted release needs repository/tag/source_sha/index_sha256")
require(isinstance(release["repository"], str) and re.fullmatch(r"cflmy/[A-Za-z0-9-]+", release["repository"]),
f"{path}: invalid release repository")
release_version = release.get("version", record["version"])
require(isinstance(release_version, str) and TAG.fullmatch(f"v{release_version}"),
f"{path}: invalid accepted release version")
require(set(release) <= {"repository", "tag", "source_sha", "index_sha256", "version"},
f"{path}: accepted release has unknown fields")
require(isinstance(release["tag"], str) and TAG.fullmatch(release["tag"]), f"{path}: invalid release tag")
# The top-level record version is authoritative for the product; an
# application product may pin a differently versioned runtime release.
require(release["tag"] in {f"v{release_version}", f"mqdh-v{release_version}"},
f"{path}: release tag does not match version {release_version}")
require(isinstance(release["source_sha"], str) and SHA.fullmatch(release["source_sha"]),
f"{path}: invalid release source SHA")
require(isinstance(release["index_sha256"], str) and HEX.fullmatch(release["index_sha256"]),
f"{path}: invalid release evidence digest")
require(isinstance(record["platform"]["target"], str), f"{path}: missing platform target")
return record
def load_report(path: Path) -> dict:
report = read_json(path)
require(report.get("schema") == RECONCILE_SCHEMA and report.get("schema_version") == 1,
f"{path}: unsupported reconcile report")
require(report.get("scan_complete") is True, f"{path}: release scan is not complete")
require(isinstance(report.get("root_sha"), str) and SHA.fullmatch(report["root_sha"]),
f"{path}: invalid root_sha")
require(isinstance(report.get("results"), list), f"{path}: results must be a list")
return report
def select_component(graph: dict[str, dict], component_id: str, pins: dict[str, str]) -> dict:
require(component_id in graph, f"acceptance names unknown component {component_id!r}")
require(component_id in pins, f"component {component_id!r} has no gitlink")
return graph[component_id]
def verified_release(report: dict, repository: str, tag: str) -> dict:
matches = [item for item in report["results"]
if item.get("repository") == repository and item.get("tag") == tag]
require(len(matches) == 1, f"reconcile report does not contain exactly one {repository} {tag}")
entry = matches[0]
require(entry.get("status") in {"pending", "tracked"},
f"{repository} {tag} is not a verified release: {entry.get('status')} {entry.get('error', '')}".strip())
return entry
def normalize(entry: dict) -> dict:
"""Drop the reconcile bookkeeping and keep the verified public facts."""
return {
"repository": entry["repository"],
"tag": entry["tag"],
"source_sha": entry["source_sha"],
"index_sha256": entry["index_sha256"],
"ci": entry["ci"],
"assets": sorted(entry["assets"], key=lambda asset: asset["name"]),
"dependencies": sorted(entry["dependencies"], key=lambda dep: dep["id"]),
"published_at": entry["published_at"],
}
def validate(acceptance: dict, report: dict, graph: dict[str, dict], pins: dict[str, str]) -> list[dict]:
require(acceptance["decision"] == "accepted", "only an accepted record can be projected")
target = acceptance["platform"]["target"]
releases = []
covered = set()
for component in acceptance["components"]:
component_id = component["id"]
identity = select_component(graph, component_id, pins)
require(identity["state"] == "active", f"component {component_id!r} is not active")
release = component["release"]
version = release.get("version", acceptance["version"])
kind = identity["kind"]
expected_tag = f"mqdh-v{version}" if kind == "app" else f"v{version}"
require(release["tag"] == expected_tag,
f"{component_id}: {kind} release tag {release['tag']} != {expected_tag}")
pinned = pins[component_id]
require(pinned == release["source_sha"],
f"{component_id}: released source {release['source_sha']} != root gitlink {pinned}")
entry = normalize(verified_release(report, release["repository"], release["tag"]))
require(entry["source_sha"] == release["source_sha"],
f"{component_id}: reconcile source SHA mismatch")
require(entry["index_sha256"] == release["index_sha256"],
f"{component_id}: release evidence digest mismatch")
accepted_assets = component.get("assets")
if accepted_assets is not None:
require(isinstance(accepted_assets, list) and accepted_assets,
f"{component_id}: assets must be a non-empty list")
published = {(item["name"], item["size"], item["sha256"], item["target"]) for item in entry["assets"]}
accepted = {(item.get("name"), item.get("size"), item.get("sha256"), item.get("target"))
for item in accepted_assets}
require(accepted == published, f"{component_id}: accepted assets do not match the published release")
for asset in entry["assets"]:
require(asset["target"] == target,
f"{component_id}: asset {asset['name']} target {asset['target']} != {target}")
for dependency in entry["dependencies"]:
require(dependency["id"] in graph, f"{component_id}: unknown Bundle dependency {dependency['id']!r}")
require(pins.get(dependency["id"]) == dependency["source_sha"],
f"{component_id}: Bundle dependency {dependency['id']} {dependency['source_sha']} "
f"!= root gitlink {pins.get(dependency['id'])}")
covered.add(component_id)
releases.append({**entry, "component": component_id, "kind": kind, "version": version})
# Every declared requirement of an accepted component must be covered by
# another accepted release or by a verified Bundle dependency.
dependencies = {dep["id"] for release in releases for dep in release["dependencies"]}
required = set()
for component_id in covered:
required |= close_over(graph, component_id) - {component_id}
missing = required - covered - dependencies
require(not missing, f"accepted scope misses required components: {sorted(missing)}")
return releases
def close_over(graph: dict[str, dict], component_id: str) -> set[str]:
seen: set[str] = set()
pending = list(graph[component_id].get("requires", []))
while pending:
current = pending.pop()
require(current in graph, f"unknown component reference {current!r}")
if current in seen:
continue
seen.add(current)
pending.extend(graph[current].get("requires", []))
return seen
def load_components(repo: Path, revision: str) -> tuple[list[dict], dict[str, str]]:
rows: list[dict] = []
pins: dict[str, str] = {}
seen: set[str] = set()
def walk(path: Path, sha: str, depth: int) -> None:
catalog = impact.read_catalog(path, sha, "root" if depth == 0 else path.name)
entries = impact.tree_entries(path, sha)
urls = impact.submodule_urls(path, sha)
for component in catalog:
component_id = component.get("id")
component_path = component.get("path")
require(isinstance(component_id, str) and ID.fullmatch(component_id), f"invalid component id {component_id!r}")
require(isinstance(component_path, str) and component_path, f"{component_id}: invalid path")
require(component_id not in seen, f"duplicate component id {component_id}")
seen.add(component_id)
require(component.get("kind") in KINDS, f"{component_id}: invalid kind")
require(component.get("state") in STATES, f"{component_id}: invalid state")
require(component.get("release") in RELEASES, f"{component_id}: invalid release class")
require(isinstance(component.get("scope"), str) and component["scope"].strip(), f"{component_id}: missing scope")
requires = component.get("requires", [])
checks_with = component.get("checks_with", [])
require(isinstance(requires, list) and isinstance(checks_with, list), f"{component_id}: invalid references")
mode_sha = entries.get(component_path)
pin = mode_sha[1] if mode_sha and mode_sha[0] == "160000" else None
row = {
"id": component_id,
"kind": component["kind"],
"state": component["state"],
"scope": component["scope"],
"requires": list(requires),
"checks_with": list(checks_with),
"release": component["release"],
"repository": (urls.get(component_path) or "").removesuffix(".git") or None,
}
rows.append(row)
if pin:
pins[component_id] = pin
if component["kind"] == "domain" and depth == 0 and pin:
domain = path / component_path
require((domain / ".git").exists(),
f"active domain {component_id} cannot be expanded: missing checkout")
walk(domain, pin, depth + 1)
walk(repo, revision, 0)
by_id = {row["id"]: row for row in rows}
for row in rows:
for reference in row["requires"] + row["checks_with"]:
require(reference in by_id, f"{row['id']}: dangling component reference {reference!r}")
if row["state"] == "active":
require(row["repository"], f"active component {row['id']} has no public repository")
return rows, pins
def release_id(component_id: str, version: str) -> str:
return f"{component_id}-{version}"
def asset_kind(name: str) -> str:
if name.endswith(".tar.gz") or name.endswith(".zip"):
return "archive"
if name.endswith(".sha256"):
return "checksum"
if name.endswith(".json"):
return "evidence"
return "manifest"
def asset_platform(kind: str, target: str) -> str:
return "supported" if kind == "archive" else "not-applicable"
def independent_rows(report: dict, components: list[dict], existing: dict[str, dict],
repositories: set[str], refs: set[str]) -> list[dict]:
"""Verified, independently released components that are not root-accepted.
The rows come from the same reconcile facts as accepted releases (tag ->
SHA, same-SHA CI, evidence digest, asset bytes). They are exposed for
discovery as ``integration_state: pending`` and never enter an offer,
recommendation or download list; root acceptance stays a separate fact.
"""
by_component = {component["id"]: component for component in components}
rows: list[dict] = []
for entry in report["results"]:
if not isinstance(entry, dict):
continue
if entry.get("repository") not in repositories:
continue
if entry.get("status") not in {"pending", "tracked"}:
continue
component_id = entry.get("component")
require(component_id in by_component,
f"independent release names unknown component {component_id!r}")
kind = by_component[component_id]["kind"]
require(kind != "app", f"application release {component_id} must go through acceptance")
tag = entry.get("tag")
require(isinstance(tag, str) and tag.startswith("v"), f"invalid independent tag {tag!r}")
version = tag[1:]
require(basename_ok(version), f"invalid independent version {version!r}")
rid = release_id(component_id, version)
if rid in existing:
continue
source_sha = entry.get("source_sha")
index_sha256 = entry.get("index_sha256")
ci = entry.get("ci")
published_at = entry.get("published_at")
require(isinstance(source_sha, str) and SHA.fullmatch(source_sha),
f"{component_id}: invalid independent source SHA")
require(isinstance(index_sha256, str) and HEX.fullmatch(index_sha256),
f"{component_id}: invalid independent evidence digest")
require(isinstance(ci, dict) and isinstance(ci.get("url"), str),
f"{component_id}: missing independent CI evidence")
asset_rows = []
archive_ids = []
for asset in entry.get("assets") or []:
require(isinstance(asset, dict), f"{component_id}: invalid independent asset")
name = asset.get("name")
require(isinstance(name, str) and BASENAME.fullmatch(name),
f"{component_id}: invalid independent asset name")
kind_name = asset_kind(name)
aid = f"{rid}-{name}"
require(ID.fullmatch(aid), f"{component_id}: invalid independent asset id {aid}")
row = {
"asset_id": aid,
"name": name,
"size": asset["size"],
"sha256": asset["sha256"],
"target": asset["target"],
"kind": kind_name,
"download_url": f"{FORGE}/{entry['repository']}/releases/download/{tag}/{name}",
"platform_status": asset_platform(kind_name, asset["target"]),
"runtime_requirements": [],
"signature_state": "unsigned",
}
asset_rows.append(row)
if kind_name == "archive":
archive_ids.append(aid)
require(archive_ids, f"{component_id}: independent release has no archive asset")
require(asset_rows, f"{component_id}: independent release has no assets")
rows.append({
"release_id": rid,
"component_id": component_id,
"version": version,
"tag": tag,
"channel": channel_of(version),
"source_sha": source_sha,
"published_at": utc_z(published_at, "published_at"),
"release_url": f"{FORGE}/{entry['repository']}/releases/tag/{tag}",
"evidence_url": f"{FORGE}/{entry['repository']}/releases/download/{tag}/release-evidence.json",
"evidence_sha256": index_sha256,
"distribution_state": "available",
"integration_state": "pending",
"assets": asset_rows,
})
refs.update({rows[-1]["release_url"], rows[-1]["evidence_url"], ci["url"]})
return rows
def basename_ok(value: str) -> bool:
return BASENAME.fullmatch(value) is not None
def build_snapshot(acceptances: list[dict], report: dict, components: list[dict],
generated_at: str, *, include_independent: bool = False,
independent_repositories: set[str] | None = None) -> dict:
"""Merge one or more accepted products into the single public snapshot."""
by_component = {component["id"]: component for component in components}
app_components = {component["id"] for component in components if component["kind"] == "app"}
rows: dict[str, dict] = {}
block_assets: dict[str, list[str]] = {}
offers: list[dict] = []
recommendations: list[dict] = []
refs: set[str] = set()
for acceptance, releases in acceptances:
version = acceptance["version"]
channel = acceptance["channel"]
target = acceptance["platform"]["target"]
runtime = [f"Linux x86_64 ({target})", acceptance["platform"]["minimum_runtime"]]
accepted_rows: dict[str, list[str]] = {}
for release in releases:
component_id = release["component"]
release_version = release["version"]
rid = release_id(component_id, release_version)
asset_rows = []
archive_ids = []
for asset in release["assets"]:
kind = asset_kind(asset["name"])
aid = f"{rid}-{asset['name']}"
require(ID.fullmatch(aid), f"invalid asset id {aid}")
row = {
"asset_id": aid,
"name": asset["name"],
"size": asset["size"],
"sha256": asset["sha256"],
"target": asset["target"],
"kind": kind,
"download_url": f"{FORGE}/{release['repository']}/releases/download/{release['tag']}/{asset['name']}",
"platform_status": asset_platform(kind, asset["target"]),
"runtime_requirements": runtime if kind == "archive" else [],
"signature_state": "unsigned",
}
asset_rows.append(row)
if kind == "archive":
archive_ids.append(aid)
require(archive_ids, f"{component_id}: accepted release has no archive asset")
row = {
"release_id": rid,
"component_id": component_id,
"version": release_version,
"tag": release["tag"],
"channel": channel_of(release_version),
"source_sha": release["source_sha"],
"published_at": utc_z(release["published_at"], "published_at"),
"release_url": f"{FORGE}/{release['repository']}/releases/tag/{release['tag']}",
"evidence_url": f"{FORGE}/{release['repository']}/releases/download/{release['tag']}/release-evidence.json",
"evidence_sha256": release["index_sha256"],
"distribution_state": "available",
"integration_state": "accepted",
"assets": asset_rows,
}
existing = rows.get(rid)
require(existing is None or existing == row,
f"release {rid} has inconsistent facts across acceptance records")
rows[rid] = row
block_assets[rid] = [asset["asset_id"] for asset in asset_rows]
accepted_rows[rid] = archive_ids
refs.update({row["release_url"], row["evidence_url"], release["ci"]["url"],
acceptance["acceptance_url"], acceptance["root_release_url"]})
members = []
primary: list[str] = []
for rid in sorted(accepted_rows):
component_id = rows[rid]["component_id"]
require(component_id in by_component, f"accepted release {component_id} is not in the catalog")
application = component_id in app_components
if application:
primary.extend(accepted_rows[rid])
installation = "included" if application or acceptance["product"] == "marqdo" else "managed"
members.append({
"release_id": rid,
"installation": installation,
"asset_ids": block_assets[rid],
})
if not primary:
for rid in sorted(accepted_rows):
primary.extend(accepted_rows[rid])
require(primary, f"{acceptance['product']}: accepted scope has no primary archive asset")
offer_id = f"{acceptance['product']}-{version}-{target}"
offers.append({
"offer_id": offer_id,
"product": acceptance["product"],
"version": version,
"channel": channel,
"target": target,
"acceptance_ref": acceptance["acceptance_url"],
"root_release_ref": acceptance["root_release_url"],
"primary_asset_ids": primary,
"components": members,
"supported": True,
"distribution_state": "available",
"known_limitations": [str(item) for item in acceptance["excluded_capabilities"]],
"install_guide_url": acceptance["install_guide_url"],
})
recommendations.append({
"product": acceptance["product"],
"channel": channel,
"target": target,
"offer_id": offer_id,
})
if include_independent:
independent = independent_rows(
report, components, rows, set(independent_repositories or set()), refs)
for row in independent:
rows[row["release_id"]] = row
snapshot = {
"schema_version": SNAPSHOT_SCHEMA_VERSION,
"snapshot_revision": None, # filled by write_outputs
"root_source_sha": report["root_sha"],
"generated_at": utc_z(generated_at, "generated_at"),
"source_evidence_refs": sorted(refs),
"components": sorted(components, key=lambda row: row["id"]),
"releases": sorted(rows.values(), key=lambda row: row["release_id"]),
"offers": sorted(offers, key=lambda row: row["offer_id"]),
"recommendations": sorted(recommendations,
key=lambda row: (row["product"], row["target"], row["channel"], row["offer_id"])),
"withdrawals": [],
}
return snapshot
def write_outputs(out_dir: Path, snapshot: dict, revision: int, verified_at: str) -> dict:
require(revision >= 0, "revision must be non-negative")
pointer_path = out_dir / "current.json"
if pointer_path.exists():
existing = read_json(pointer_path)
current = existing.get("revision")
require(isinstance(current, int) and revision == current + 1,
f"existing pointer revision {current} requires revision {current + 1}, got {revision}")
else:
require(revision == 0, "first publication must use revision 0")
snapshot["snapshot_revision"] = revision
body = (json.dumps(snapshot, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
digest = hashlib.sha256(body).hexdigest()
snapshot_dir = out_dir / "snapshots"
snapshot_dir.mkdir(parents=True, exist_ok=True)
target = snapshot_dir / f"{digest}.json"
require(not target.exists() or target.read_bytes() == body,
f"snapshot {digest} already exists with different bytes")
target.write_bytes(body)
pointer = {
"schema_version": POINTER_SCHEMA_VERSION,
"revision": revision,
"snapshot": f"/data/snapshots/{digest}.json",
"sha256": digest,
"verified_at": utc_z(verified_at, "verified_at"),
}
pointer_path.write_text(json.dumps(pointer, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
return {"pointer": pointer, "snapshot_path": str(target), "revision": revision}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument("--root-sha", required=True)
parser.add_argument("--reconcile-report", type=Path, required=True)
parser.add_argument("--acceptance", type=Path, action="append", required=True,
help="accepted product record; repeat to project several products")
parser.add_argument("--generated-at", required=True)
parser.add_argument("--verified-at", default=None)
parser.add_argument("--revision", type=int, required=True)
parser.add_argument("--include-independent-releases", action="store_true",
help="also expose verified component releases that root did not accept")
parser.add_argument("--independent-repository", action="append", default=[],
help="owner/name whose verified non-accepted releases become pending rows (repeatable)")
parser.add_argument("--out-dir", type=Path, required=True)
args = parser.parse_args(argv)
root = args.root.resolve()
root_sha = impact.resolve(root, args.root_sha)
require(SHA.fullmatch(root_sha), "--root-sha must resolve to a full commit SHA")
stamp(args.generated_at, "--generated-at")
verified_at = args.verified_at or args.generated_at
stamp(verified_at, "--verified-at")
try:
acceptances = [load_acceptance(path) for path in args.acceptance]
report = load_report(args.reconcile_report)
require(report["root_sha"] == root_sha,
f"reconcile report root {report['root_sha']} != projected root {root_sha}")
for acceptance in acceptances:
try:
impact.git(root, "merge-base", "--is-ancestor", acceptance["root_base_sha"], root_sha)
except impact.ImpactError:
fail(f"root_base_sha {acceptance['root_base_sha']} is not an ancestor of {root_sha}")
components, pins = load_components(root, root_sha)
graph = {row["id"]: {**row, "sha": pins.get(row["id"])} for row in components}
validated = [(acceptance, validate(acceptance, report, graph, pins))
for acceptance in acceptances]
snapshot = build_snapshot(
validated, report, components, args.generated_at,
include_independent=args.include_independent_releases,
independent_repositories=set(args.independent_repository or []))
result = write_outputs(args.out_dir, snapshot, args.revision, verified_at)
except ProjectionError as error:
print(f"project-release: {error}", file=sys.stderr)
return 1
print(json.dumps({"schema": "marqdo.public-release-projection.v1",
"root_source_sha": root_sha,
"products": [{"product": acceptance["product"],
"version": acceptance["version"],
"channel": acceptance["channel"],
"target": acceptance["platform"]["target"]}
for acceptance, _ in validated],
**result}, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))