Files
rsReticulum/scripts/ci/check_source_release_contract.py

196 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Validate rsReticulum's source-release invariants."""
from __future__ import annotations
import argparse
import json
import re
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
EXPECTED_RUST_VERSION = "1.89"
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
def fail(message: str) -> None:
raise SystemExit(f"source-release contract failed: {message}")
def command(*args: str) -> str:
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
def metadata() -> dict[str, object]:
output = command(
"cargo",
"metadata",
"--format-version",
"1",
"--locked",
"--no-deps",
)
return json.loads(output)
def check_packages(document: dict[str, object]) -> str:
packages = document["packages"]
assert isinstance(packages, list)
versions = {package["version"] for package in packages}
if len(versions) != 1:
fail(f"workspace packages do not share one version: {sorted(versions)}")
problems = []
for package in packages:
name = package["name"]
if package["publish"] != []:
problems.append(f"{name} is not marked publish = false")
if package["rust_version"] != EXPECTED_RUST_VERSION:
problems.append(
f"{name} exposes rust-version {package['rust_version']!r}, "
f"expected {EXPECTED_RUST_VERSION!r}"
)
if problems:
fail("; ".join(problems))
return str(versions.pop())
def check_workflow_actions() -> None:
workflows = ROOT / ".github/workflows"
for workflow_path in sorted([*workflows.glob("*.yml"), *workflows.glob("*.yaml")]):
workflow = workflow_path.read_text()
action_uses = re.findall(
r"^\s*(?:-\s+)?uses:\s+([^\s#]+)", workflow, re.MULTILINE
)
for action in action_uses:
if action.startswith("./"):
continue
if "@" not in action or not SHA_PATTERN.fullmatch(
action.rsplit("@", 1)[1]
):
fail(
f"workflow action is not pinned to a commit "
f"({workflow_path.name}): {action}"
)
def check_release_workflow() -> None:
workflow = (ROOT / ".github/workflows/release.yml").read_text()
if not re.search(r"^\s*toolchain:\s*1\.89\.0\s*$", workflow, re.MULTILINE):
fail("release workflow does not select Rust 1.89.0")
if "ref: ${{ env.SOURCE_REF }}" not in workflow or "SOURCE_REF: ${{ github.sha }}" not in workflow:
fail("release workflow must check out the immutable event commit")
if " if: github.event_name == 'push' || !inputs.qualify_only\n needs: package" not in workflow:
fail("publication must exclude qualification and require verified archives")
if "--candidate-tag" not in workflow or "actions/workflows/ci.yml/runs?head_sha=" not in workflow:
fail("release workflow must qualify untagged sources and require exact-source CI")
publishers = re.findall(
r"^ - uses: softprops/action-gh-release@[0-9a-f]{40}[^\n]*\n"
r" with:\n((?: [^\n]*\n)+)",
workflow,
re.MULTILINE,
)
if len(publishers) != 1:
fail("release workflow must have one explicit GitHub publisher")
inputs = dict(re.findall(r"^ ([a-z_]+): (.*)$", publishers[0], re.MULTILINE))
expected = {
"tag_name": "${{ env.RELEASE_TAG }}",
"name": "${{ env.RELEASE_TAG }}",
"body": '""',
"generate_release_notes": "false",
"append_body": "false",
}
if any(inputs.get(key) != value for key, value in expected.items()) or "body_path" in inputs:
fail("GitHub releases must use the exact version tag as title and an empty body")
release_builds = [
line.strip()
for line in workflow.splitlines()
if "cargo build" in line and "--release" in line
]
if not release_builds or any("--locked" not in line for line in release_builds):
fail("every release Cargo build must use --locked")
def check_documentation(version: str) -> None:
changelog = (ROOT / "CHANGELOG.md").read_text()
if not re.search(r"^## Unreleased\s*$", changelog, re.MULTILINE):
fail("CHANGELOG.md is missing an Unreleased section")
if not re.search(
rf"^## {re.escape(version)} - \d{{4}}-\d{{2}}-\d{{2}}\s*$",
changelog,
re.MULTILINE,
):
fail(f"CHANGELOG.md is missing the current {version} release section")
readme = (ROOT / "README.md").read_text()
unlocked = re.findall(
r"^.*cargo build --release(?![^\n]*--locked).*$", readme, re.MULTILINE
)
if unlocked:
fail("README.md contains an unlocked release build command")
def check_release_tag(release_tag: str, version: str) -> None:
if not re.fullmatch(r"v\d+\.\d+\.\d+", release_tag):
fail("release tags must have the form vX.Y.Z")
expected_tag = f"v{version}"
if release_tag != expected_tag:
fail(f"release tag {release_tag!r} does not match {expected_tag!r}")
try:
tag_type = command("git", "cat-file", "-t", release_tag)
except subprocess.CalledProcessError:
fail(f"release tag {release_tag!r} is not present in this checkout")
if tag_type != "tag":
fail(f"release tag {release_tag!r} must be an annotated tag")
head = command("git", "rev-parse", "HEAD")
try:
tagged_commit = command("git", "rev-list", "-n", "1", release_tag)
except subprocess.CalledProcessError:
fail(f"release tag {release_tag!r} is not present in this checkout")
if head != tagged_commit:
fail(f"HEAD {head} is not the commit named by {release_tag} ({tagged_commit})")
def check_candidate_tag(tag: str, version: str) -> None:
if not re.fullmatch(r"v\d+\.\d+\.\d+", tag) or tag != f"v{version}":
fail("candidate tag must match the workspace version as vX.Y.Z")
result = subprocess.run(
["git", "show-ref", "--verify", "--quiet", f"refs/tags/{tag}"], cwd=ROOT
)
if result.returncode != 1:
fail("candidate qualification requires an untagged version")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
tags = parser.add_mutually_exclusive_group()
tags.add_argument("--release-tag", help="also verify the existing annotated vX.Y.Z tag matches the workspace version and HEAD")
tags.add_argument("--candidate-tag", help="also verify vX.Y.Z matches the workspace version and has no local tag yet")
args = parser.parse_args()
version = check_packages(metadata())
check_workflow_actions()
check_release_workflow()
check_documentation(version)
subprocess.run(
["python3", "tools/check-api-baseline.py", "--metadata-only"],
cwd=ROOT,
check=True,
)
if args.candidate_tag:
check_candidate_tag(args.candidate_tag, version)
if args.release_tag:
check_release_tag(args.release_tag, version)
print(f"source-release contract passed for rsReticulum {version}")
if __name__ == "__main__":
main()