Implements the scoped public prerelease policy from marqdo#85 for the `marqdo` base product on Linux x86_64 (glibc >= 2.39): - add `docs/RELEASE-POLICY.md`: product x platform x version x capability scope, channel rules, B0/B1/B2/S gates, deferral records, acceptance record requirements and the public-data projection contract; - accept CLI `v3.0.0-rc.7` (source 63562d8) with its exact Bundle 0.3.0 component pins, same-SHA Woodpecker pipeline #176, deterministic archive, cold install, frozen conformance and shared-host performance WARN; - add `scripts/project-release.py` to derive the `/data/current.json` pointer and immutable snapshot from verified reconcile facts + the acceptance record + the pinned recursive catalog, failing closed on any SHA, asset or Bundle mismatch; - add negative-path tests for source-SHA, asset, Bundle dependency, channel, scan-completeness and revision errors; - pin `cli` to the released source SHA and link the policy from README and the development contract. Not accepted in this scope: Windows/macOS native support, strict L1 PASS, dedicated-node performance PASS, installer signing, MQDH/AI releases and the website production /data/ hosting. Those keep their real UNVERIFIED / UNSUPPORTED state and own trackers.
543 lines
25 KiB
Python
543 lines
25 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"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")
|
|
require(isinstance(release["tag"], str) and TAG.fullmatch(release["tag"]), f"{path}: invalid release tag")
|
|
require(release["tag"] == f"v{record['version']}", f"{path}: release tag does not match 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"]
|
|
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})
|
|
|
|
# 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"):
|
|
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 build_snapshot(acceptance: dict, report: dict, components: list[dict], pins: dict[str, str],
|
|
releases: list[dict], generated_at: str) -> dict:
|
|
version = acceptance["version"]
|
|
channel = acceptance["channel"]
|
|
target = acceptance["platform"]["target"]
|
|
runtime = [f"Linux x86_64 ({target})", acceptance["platform"]["minimum_runtime"]]
|
|
|
|
release_rows = []
|
|
asset_ids: dict[str, list[str]] = {}
|
|
offer_primary: list[str] = []
|
|
for release in releases:
|
|
component_id = release["component"]
|
|
rid = release_id(component_id, version)
|
|
asset_rows = []
|
|
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":
|
|
offer_primary.append(aid)
|
|
require(offer_primary, f"{component_id}: accepted release has no archive asset")
|
|
asset_ids[rid] = [row["asset_id"] for row in asset_rows]
|
|
release_rows.append({
|
|
"release_id": rid,
|
|
"component_id": component_id,
|
|
"version": version,
|
|
"tag": release["tag"],
|
|
"channel": channel,
|
|
"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,
|
|
})
|
|
|
|
by_component = {component["id"]: component for component in components}
|
|
members = []
|
|
for release_row in release_rows:
|
|
component_id = release_row["component_id"]
|
|
members.append({
|
|
"release_id": release_row["release_id"],
|
|
"installation": "included",
|
|
"asset_ids": asset_ids[release_row["release_id"]],
|
|
})
|
|
require(component_id in by_component, f"accepted release {component_id} is not in the catalog")
|
|
|
|
offer_id = f"{acceptance['product']}-{version}-{target}"
|
|
offer = {
|
|
"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": offer_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"],
|
|
}
|
|
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({
|
|
*(row["release_url"] for row in release_rows),
|
|
*(row["evidence_url"] for row in release_rows),
|
|
*(row["ci"]["url"] for row in releases),
|
|
acceptance["acceptance_url"],
|
|
acceptance["root_release_url"],
|
|
}),
|
|
"components": sorted(components, key=lambda row: row["id"]),
|
|
"releases": sorted(release_rows, key=lambda row: row["release_id"]),
|
|
"offers": [offer],
|
|
"recommendations": [{
|
|
"product": acceptance["product"],
|
|
"channel": channel,
|
|
"target": target,
|
|
"offer_id": 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, required=True)
|
|
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("--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:
|
|
acceptance = load_acceptance(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}")
|
|
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}
|
|
releases = validate(acceptance, report, graph, pins)
|
|
snapshot = build_snapshot(acceptance, report, components, pins, releases,
|
|
args.generated_at)
|
|
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,
|
|
"product": acceptance["product"],
|
|
"version": acceptance["version"],
|
|
"channel": acceptance["channel"],
|
|
"target": acceptance["platform"]["target"],
|
|
**result}, ensure_ascii=False, indent=2))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main(sys.argv[1:]))
|