Add two subcommands to the single release implementation: - archive-dir: package an already-built Tool bundle directory as deterministic tar.gz + zip with fixed metadata, sorted members, preserved executable bits and cross-format content verification; - publish-assets: the same evidence/draft/readback/no-overwrite transaction for externally built assets, so Rust Tool repositories publish their binaries through CI instead of packaging source files. Also allow the tool kind for generated release notes. Tests keep passing.
1146 lines
52 KiB
Python
1146 lines
52 KiB
Python
#!/usr/bin/env python3
|
|
"""Publish one independent Marqdo stdlib/extension component release.
|
|
|
|
This is the single implementation of the component release transaction used by
|
|
every active library repository (marqdo#96 M1). A component repository only
|
|
needs Python 3 and git (the bootstrap in ``.woodpecker/publish.yml`` downloads
|
|
this file at a pinned root commit) and never checks out the root repository or a
|
|
sibling component.
|
|
|
|
Artifact
|
|
--------
|
|
The published assets are deterministic ``tar.gz`` and ``zip`` archives of
|
|
*only* the reviewed release paths of the exact tagged commit. The tree and
|
|
bytes are read from the Git object database with ``git ls-tree`` / ``git
|
|
cat-file`` (never ``git archive``, never the working tree), so attributes such
|
|
as ``export-ignore`` / ``export-subst`` cannot silently drop or rewrite released
|
|
files. The tar metadata is fixed (mtime 0, uid/gid 0, mode 0644, sorted paths)
|
|
and the gzip stream is written with mtime 0 and no filename; the zip uses a
|
|
fixed DOS timestamp, ``create_system=3``, regular-file 0644 attributes and UTF-8
|
|
name flags. Both formats carry exactly the same file set and bytes (tar.gz is
|
|
the Linux/POSIX convention, zip the Windows one; the content is platform
|
|
independent). Packaging twice must produce identical bytes in the same
|
|
Python/zlib environment; that property is checked per format on every run. The
|
|
archive member set and bytes are compared back to the exact commit blobs before
|
|
anything is uploaded.
|
|
|
|
Evidence
|
|
--------
|
|
``release-evidence.json`` follows the ecosystem-wide schema already verified by
|
|
``scripts/reconcile-releases.py``::
|
|
|
|
repository, component_id, tag, source_sha,
|
|
ci: {pipeline_number, url, source_sha},
|
|
assets: [{name, size, target, sha256}],
|
|
dependencies: [{id, source_sha[, asset_sha256]}]
|
|
|
|
No parallel stdlib/ext release manifest is introduced. The same-SHA Woodpecker
|
|
pipeline of the ``ci`` workflow is discovered through the public read-only API.
|
|
Selection is deterministic (the lowest successful same-SHA pipeline number), so
|
|
re-running the transaction reproduces the same evidence instead of picking a
|
|
newer pipeline that appeared later. A release is never published without a
|
|
successful same-SHA component CI.
|
|
|
|
Publish transaction
|
|
-------------------
|
|
Gitea Release is used as the immutable asset store: create/reuse a *draft*,
|
|
upload the payload assets first and ``release-evidence.json`` last, re-read every
|
|
byte and compare sha256, then make the release public. Published releases are
|
|
never deleted or overwritten. Re-running with identical bytes is idempotent;
|
|
different bytes for the same tag fail closed. An interrupted draft can be
|
|
discarded explicitly with ``--reset-draft``. The remote tag is checked before
|
|
publishing: an existing tag must already point at the released commit.
|
|
|
|
Commands
|
|
--------
|
|
release.py check --repository cflmy/marqdo-std-text --component-id std-text \
|
|
--kind stdlib --allow modules --allow README.md
|
|
release.py publish --repository cflmy/marqdo-std-text --component-id std-text \
|
|
--kind stdlib --allow modules --allow README.md \
|
|
--tag v0.1.0 \
|
|
--dependency "id=cli,source_sha=<sha>,asset_sha256=<digest>"
|
|
|
|
Environment for ``publish``: ``GITEA_PUBLISH_TOKEN`` holds the protected
|
|
publishing token; ordinary push/PR lanes never receive it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import gzip
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import mimetypes
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
import unicodedata
|
|
import zipfile
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
FORGE = "https://git.cflmy.cn"
|
|
CI = "https://ci.cflmy.cn"
|
|
INDEX = "release-evidence.json"
|
|
WORKFLOW = "ci"
|
|
SHA_RE = re.compile(r"[0-9a-f]{40}")
|
|
DIGEST_RE = re.compile(r"[0-9a-f]{64}")
|
|
VERSION_RE = re.compile(
|
|
r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
|
|
r"(-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?"
|
|
)
|
|
BASENAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,254}")
|
|
MAX_INDEX_BYTES = 1024 * 1024
|
|
MAX_ASSET_BYTES = 1024 * 1024 * 1024
|
|
MAX_TREE_BYTES = 256 * 1024 * 1024
|
|
MAX_DEPENDENCIES = 256
|
|
ALLOWED_EVENTS = {"push", "pull_request", "manual"}
|
|
KIND_SUFFIX = {"stdlib": "-source", "extension": "-package", "tool": "-tool"}
|
|
ARCHIVE_FORMATS = ("tar.gz", "zip")
|
|
ZIP_MIN_TIME = (1980, 1, 1, 0, 0, 0)
|
|
FIXED_MTIME = 0
|
|
FIXED_MODE = 0o644
|
|
PATHSPEC_MAGIC = set("*?[")
|
|
|
|
|
|
class ReleaseError(Exception):
|
|
"""A release precondition, artifact or transaction failed."""
|
|
|
|
|
|
def require(condition: object, message: str) -> None:
|
|
if not condition:
|
|
raise ReleaseError(message)
|
|
|
|
|
|
def sha256_bytes(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
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 git(root: Path, *args: str, binary: bool = False):
|
|
result = subprocess.run(
|
|
["git", "-C", str(root), *args], capture_output=True
|
|
)
|
|
if result.returncode != 0:
|
|
raise ReleaseError(
|
|
f"git {' '.join(args)} failed: {result.stderr.decode(errors='replace').strip()}"
|
|
)
|
|
return result.stdout if binary else result.stdout.decode().strip()
|
|
|
|
|
|
def resolved_head(root: Path) -> str:
|
|
value = git(root, "rev-parse", "HEAD")
|
|
require(SHA_RE.fullmatch(value) is not None, "HEAD is not a full commit SHA")
|
|
return value
|
|
|
|
|
|
def commit_exists(root: Path, revision: str) -> bool:
|
|
result = subprocess.run(
|
|
["git", "-C", str(root), "cat-file", "-e", f"{revision}^{{commit}}"],
|
|
capture_output=True,
|
|
)
|
|
return result.returncode == 0
|
|
|
|
|
|
def safe_relative(entry: str) -> bool:
|
|
if not entry or entry.startswith(("/", "\\")) or entry == ".":
|
|
return False
|
|
if any(character in PATHSPEC_MAGIC for character in entry):
|
|
return False
|
|
parts = Path(entry).parts
|
|
return bool(parts) and not any(part in ("", ".", "..") for part in parts)
|
|
|
|
|
|
def validate_version(tag: str) -> str:
|
|
require(tag.startswith("v"), f"tag {tag!r} must start with 'v'")
|
|
version = tag[1:]
|
|
require(VERSION_RE.fullmatch(version) is not None, f"invalid release version {version!r}")
|
|
return version
|
|
|
|
|
|
def artifact_stem(repository: str, version: str, kind: str) -> str:
|
|
name = repository.split("/", 1)[-1]
|
|
require(BASENAME_RE.fullmatch(name) is not None, "repository name is not a safe basename")
|
|
return f"{name}-{version}{KIND_SUFFIX[kind]}"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Deterministic archive built from the exact Git objects
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def released_files(root: Path, source_sha: str, allow: list[str]) -> list[tuple[str, bytes]]:
|
|
"""Return ``(repository_path, bytes)`` for the allowlisted files of one commit."""
|
|
for entry in allow:
|
|
require(safe_relative(entry), f"unsafe release path: {entry!r}")
|
|
listing = git(root, "ls-tree", "-r", "-z", source_sha, "--", *allow, binary=True)
|
|
records = [record for record in listing.split(b"\0") if record]
|
|
require(records, "release paths match no file at the tagged commit")
|
|
selected: dict[str, bytes] = {}
|
|
folded: dict[str, str] = {}
|
|
total = 0
|
|
for record in records:
|
|
header, _, raw_path = record.partition(b"\t")
|
|
fields = header.decode("ascii", "strict").split()
|
|
require(len(fields) == 3, "invalid git tree record")
|
|
mode, kind, blob = fields
|
|
path = raw_path.decode("utf-8")
|
|
require(kind == "blob", f"released path is not a regular file: {path} ({mode})")
|
|
require(mode in ("100644", "100755"), f"released path has unsupported mode: {path}")
|
|
require(safe_relative(path), f"unsafe released path: {path}")
|
|
require(
|
|
any(path == entry or path.startswith(entry.rstrip("/") + "/") for entry in allow),
|
|
f"released path outside the reviewed allow list: {path}",
|
|
)
|
|
normalised = unicodedata.normalize("NFC", path)
|
|
key = normalised.casefold()
|
|
require(key not in folded,
|
|
f"case/NFC collision between released paths: {folded.get(key)!r} and {path!r}")
|
|
require(path not in selected, f"duplicate released path: {path}")
|
|
folded[key] = path
|
|
data = git(root, "cat-file", "blob", blob, binary=True)
|
|
total += len(data)
|
|
require(total <= MAX_TREE_BYTES, "released tree exceeds the size limit")
|
|
selected[path] = data
|
|
return [(path, selected[path]) for path in sorted(selected)]
|
|
|
|
|
|
def build_archive(prefix: str, files: list[tuple[str, bytes]]) -> bytes:
|
|
"""Build the reproducible tar.gz stream from resolved file bytes."""
|
|
require(files, "archive would be empty")
|
|
tar_buffer = io.BytesIO()
|
|
with tarfile.open(fileobj=tar_buffer, mode="w", format=tarfile.PAX_FORMAT) as archive:
|
|
for relative, data in files:
|
|
info = tarfile.TarInfo(name=f"{prefix}/{relative}")
|
|
info.size = len(data)
|
|
info.mtime = FIXED_MTIME
|
|
info.uid = 0
|
|
info.gid = 0
|
|
info.uname = ""
|
|
info.gname = ""
|
|
info.mode = FIXED_MODE
|
|
archive.addfile(info, io.BytesIO(data))
|
|
output = io.BytesIO()
|
|
with gzip.GzipFile(fileobj=output, mode="wb", compresslevel=9,
|
|
mtime=0, filename="") as compressed:
|
|
compressed.write(tar_buffer.getvalue())
|
|
payload = output.getvalue()
|
|
require(payload.startswith(b"\x1f\x8b\x08\x00\x00\x00\x00\x00"),
|
|
"archive is not a reproducible gzip stream")
|
|
return payload
|
|
|
|
|
|
def check_archive(payload: bytes, prefix: str, files: list[tuple[str, bytes]]) -> None:
|
|
"""Verify the archive is exactly the released commit tree, byte for byte."""
|
|
expected = {f"{prefix}/{relative}": data for relative, data in files}
|
|
seen: dict[str, bytes] = {}
|
|
with tarfile.open(fileobj=io.BytesIO(payload), mode="r:gz") as archive:
|
|
members = archive.getmembers()
|
|
require(members, "archive is empty")
|
|
for member in members:
|
|
name = member.name
|
|
require(not name.startswith(("/", "\\")), f"absolute archive path: {name}")
|
|
require("\\" not in name, f"backslash in archive path: {name}")
|
|
require(all(ord(character) >= 32 for character in name),
|
|
f"control character in archive path: {name!r}")
|
|
parts = name.split("/")
|
|
require(all(part not in ("", ".", "..") for part in parts),
|
|
f"traversal archive path: {name}")
|
|
require(member.isfile(), f"unexpected archive member: {name} ({member.type!r})")
|
|
require(not member.issym() and not member.islnk(), f"link in archive: {name}")
|
|
require(name in expected, f"archive member outside the released tree: {name}")
|
|
require(name not in seen, f"duplicate archive member: {name}")
|
|
handle = archive.extractfile(member)
|
|
require(handle is not None, f"cannot read archive member: {name}")
|
|
seen[name] = handle.read()
|
|
require(set(seen) == set(expected),
|
|
"archive does not contain exactly the released commit files")
|
|
for name, data in expected.items():
|
|
require(seen[name] == data, f"archive bytes differ from the commit blob: {name}")
|
|
|
|
|
|
def build_zip(prefix: str, files: list[tuple[str, bytes]]) -> bytes:
|
|
"""Build the reproducible Windows-friendly zip of the same released tree."""
|
|
require(files, "zip would be empty")
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED,
|
|
compresslevel=9) as archive:
|
|
for relative, data in files:
|
|
info = zipfile.ZipInfo(f"{prefix}/{relative}", date_time=ZIP_MIN_TIME)
|
|
info.compress_type = zipfile.ZIP_DEFLATED
|
|
info.create_system = 3 # Unix, fixed for cross-host reproducibility
|
|
info.external_attr = 0o100644 << 16 # regular file, 0644, no exec bit
|
|
info.flag_bits |= 0x800 # UTF-8 names
|
|
archive.writestr(info, data)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def check_zip(payload: bytes, prefix: str, files: list[tuple[str, bytes]]) -> None:
|
|
"""Verify the zip is exactly the released commit tree, byte for byte."""
|
|
expected = {f"{prefix}/{relative}": data for relative, data in files}
|
|
seen: dict[str, bytes] = {}
|
|
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
|
infos = archive.infolist()
|
|
require(infos, "zip is empty")
|
|
for info in infos:
|
|
name = info.filename
|
|
require(not name.startswith(("/", "\\")), f"absolute zip path: {name}")
|
|
require("\\" not in name, f"backslash in zip path: {name}")
|
|
require(all(ord(character) >= 32 for character in name),
|
|
f"control character in zip path: {name!r}")
|
|
parts = name.split("/")
|
|
require(all(part not in ("", ".", "..") for part in parts),
|
|
f"traversal zip path: {name}")
|
|
require(not info.is_dir(), f"unexpected zip directory entry: {name}")
|
|
require(name in expected, f"zip member outside the released tree: {name}")
|
|
require(name not in seen, f"duplicate zip member: {name}")
|
|
require(info.create_system == 3, f"zip member {name} has an unstable creator system")
|
|
mode = (info.external_attr >> 16) & 0o170000
|
|
require(mode in (0, 0o100000), f"zip member {name} is not a regular file")
|
|
seen[name] = archive.read(info)
|
|
require(set(seen) == set(expected),
|
|
"zip does not contain exactly the released commit files")
|
|
for name, data in expected.items():
|
|
require(seen[name] == data, f"zip bytes differ from the commit blob: {name}")
|
|
|
|
|
|
def directory_files(root: Path) -> list[tuple[str, bytes, int]]:
|
|
"""Read a built package directory into (relative path, bytes, mode) entries."""
|
|
require(root.is_dir(), f"package directory does not exist: {root}")
|
|
files: list[tuple[str, bytes, int]] = []
|
|
for path in sorted(root.rglob("*"), key=lambda item: item.relative_to(root).as_posix()):
|
|
relative = path.relative_to(root).as_posix()
|
|
require(not path.is_symlink(), f"symbolic link in package directory: {relative}")
|
|
if path.is_dir():
|
|
continue
|
|
require(path.is_file(), f"non-regular file in package directory: {relative}")
|
|
require(safe_relative(relative), f"unsafe package path: {relative}")
|
|
data = path.read_bytes()
|
|
require(len(data) <= MAX_TREE_BYTES, f"package file exceeds the size limit: {relative}")
|
|
mode = 0o755 if os.access(path, os.X_OK) else 0o644
|
|
files.append((relative, data, mode))
|
|
require(files, "package directory is empty")
|
|
return files
|
|
|
|
|
|
def build_dir_targz(prefix: str, files: list[tuple[str, bytes, int]]) -> bytes:
|
|
buffer = io.BytesIO()
|
|
with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as archive:
|
|
for relative, data, mode in files:
|
|
info = tarfile.TarInfo(name=f"{prefix}/{relative}")
|
|
info.size = len(data)
|
|
info.mtime = FIXED_MTIME
|
|
info.uid = 0
|
|
info.gid = 0
|
|
info.uname = ""
|
|
info.gname = ""
|
|
info.mode = mode
|
|
archive.addfile(info, io.BytesIO(data))
|
|
output = io.BytesIO()
|
|
with gzip.GzipFile(fileobj=output, mode="wb", compresslevel=9,
|
|
mtime=0, filename="") as compressed:
|
|
compressed.write(buffer.getvalue())
|
|
payload = output.getvalue()
|
|
require(payload.startswith(b"\x1f\x8b\x08\x00\x00\x00\x00\x00"),
|
|
"package archive is not a reproducible gzip stream")
|
|
return payload
|
|
|
|
|
|
def build_dir_zip(prefix: str, files: list[tuple[str, bytes, int]]) -> bytes:
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED,
|
|
compresslevel=9) as archive:
|
|
for relative, data, mode in files:
|
|
info = zipfile.ZipInfo(f"{prefix}/{relative}", date_time=ZIP_MIN_TIME)
|
|
info.compress_type = zipfile.ZIP_DEFLATED
|
|
info.create_system = 3
|
|
info.external_attr = (0o100000 | mode) << 16
|
|
info.flag_bits |= 0x800
|
|
archive.writestr(info, data)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def check_dir_archive(payload: bytes, prefix: str,
|
|
files: list[tuple[str, bytes, int]], extension: str) -> None:
|
|
expected = {f"{prefix}/{relative}": (data, mode) for relative, data, mode in files}
|
|
seen: dict[str, tuple[bytes, int]] = {}
|
|
if extension == "zip":
|
|
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
|
for info in archive.infolist():
|
|
require(not info.is_dir(), f"unexpected directory entry: {info.filename}")
|
|
require(info.filename in expected, f"member outside the package: {info.filename}")
|
|
require(info.filename not in seen, f"duplicate member: {info.filename}")
|
|
mode = (info.external_attr >> 16) & 0o777
|
|
seen[info.filename] = (archive.read(info), mode)
|
|
else:
|
|
with tarfile.open(fileobj=io.BytesIO(payload), mode="r:gz") as archive:
|
|
for member in archive.getmembers():
|
|
require(member.isfile(), f"unexpected tar member: {member.name}")
|
|
require(member.name in expected, f"member outside the package: {member.name}")
|
|
require(member.name not in seen, f"duplicate member: {member.name}")
|
|
handle = archive.extractfile(member)
|
|
require(handle is not None, f"cannot read tar member: {member.name}")
|
|
seen[member.name] = (handle.read(), member.mode & 0o777)
|
|
require(set(seen) == set(expected), "package archive does not match the bundle directory")
|
|
for name, (data, mode) in expected.items():
|
|
require(seen[name][0] == data, f"package bytes differ from the bundle: {name}")
|
|
require((seen[name][1] & 0o111) == (mode & 0o111),
|
|
f"package executable bit differs from the bundle: {name}")
|
|
|
|
|
|
def package_directory(root: Path, prefix: str, out_dir: Path) -> list[dict]:
|
|
files = directory_files(root)
|
|
artifacts = []
|
|
for extension, builder, checker in (("tar.gz", build_dir_targz, check_dir_archive),
|
|
("zip", build_dir_zip, check_dir_archive)):
|
|
payload = builder(prefix, files)
|
|
require(payload == builder(prefix, files),
|
|
f"packaging the same bundle twice produced different {extension} bytes")
|
|
checker(payload, prefix, files, extension)
|
|
name = f"{prefix}.{extension}"
|
|
path = out_dir / name
|
|
checksum = out_dir / f"{name}.sha256"
|
|
path.write_bytes(payload)
|
|
digest = sha256_bytes(payload)
|
|
checksum.write_text(f"{digest} {name}\n", encoding="utf-8")
|
|
artifacts.append({"format": extension, "path": path, "checksum": checksum,
|
|
"name": name, "size": len(payload), "sha256": digest})
|
|
return artifacts
|
|
|
|
|
|
def package_assets(
|
|
root: Path, source_sha: str, repository: str, component_id: str, version: str,
|
|
kind: str, allow: list[str], out_dir: Path,
|
|
) -> dict:
|
|
require(SHA_RE.fullmatch(source_sha) is not None, "source SHA must be 40 lowercase hex")
|
|
require(commit_exists(root, source_sha), "source SHA is not a commit in this repository")
|
|
require(component_id != "" and "/" not in component_id, "invalid component id")
|
|
stem = artifact_stem(repository, version, kind)
|
|
prefix = f"{repository.split('/', 1)[-1]}-{version}"
|
|
files = released_files(root, source_sha, allow)
|
|
tar_payload = build_archive(prefix, files)
|
|
require(tar_payload == build_archive(prefix, files),
|
|
"packaging the same commit twice produced different tar.gz bytes")
|
|
check_archive(tar_payload, prefix, files)
|
|
zip_payload = build_zip(prefix, files)
|
|
require(zip_payload == build_zip(prefix, files),
|
|
"packaging the same commit twice produced different zip bytes")
|
|
check_zip(zip_payload, prefix, files)
|
|
artifacts = []
|
|
for extension, payload in (("tar.gz", tar_payload), ("zip", zip_payload)):
|
|
name = f"{stem}.{extension}"
|
|
path = out_dir / name
|
|
checksum = out_dir / f"{name}.sha256"
|
|
path.write_bytes(payload)
|
|
digest = sha256_bytes(payload)
|
|
checksum.write_text(f"{digest} {name}\n", encoding="utf-8")
|
|
artifacts.append({
|
|
"format": extension,
|
|
"path": path,
|
|
"checksum": checksum,
|
|
"name": name,
|
|
"size": len(payload),
|
|
"sha256": digest,
|
|
})
|
|
return {
|
|
"stem": stem,
|
|
"prefix": prefix,
|
|
"source_sha": source_sha,
|
|
"files": len(files),
|
|
"artifacts": artifacts,
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Evidence
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def parse_dependency(raw: str) -> dict:
|
|
fields: dict[str, str] = {}
|
|
for part in raw.split(","):
|
|
require("=" in part, f"invalid dependency field: {raw!r}")
|
|
key, value = part.split("=", 1)
|
|
key = key.strip()
|
|
require(key in {"id", "source_sha", "asset_sha256"},
|
|
f"unknown dependency field: {key!r}")
|
|
require(key not in fields, f"duplicate dependency field: {key!r}")
|
|
fields[key] = value.strip()
|
|
component = fields.get("id", "")
|
|
source_sha = fields.get("source_sha", "")
|
|
require(component != "" and "/" not in component, f"invalid dependency id: {raw!r}")
|
|
require(SHA_RE.fullmatch(source_sha) is not None,
|
|
f"dependency {component} needs a full source_sha: {raw!r}")
|
|
record = {"id": component, "source_sha": source_sha}
|
|
asset = fields.get("asset_sha256")
|
|
if asset:
|
|
require(DIGEST_RE.fullmatch(asset) is not None,
|
|
f"dependency {component} has an invalid asset_sha256")
|
|
record["asset_sha256"] = asset
|
|
return record
|
|
|
|
|
|
def build_evidence(*, repository: str, component_id: str, tag: str, source_sha: str,
|
|
ci: dict, assets: list[dict], dependencies: list[dict],
|
|
target: str = "source") -> dict:
|
|
require(component_id != "" and "/" not in component_id, "invalid component id")
|
|
require(tag != "" and " " not in tag, "invalid tag")
|
|
names: set[str] = set()
|
|
records = []
|
|
for asset in assets:
|
|
name = asset["name"]
|
|
require(BASENAME_RE.fullmatch(name) is not None, f"unsafe asset name: {name!r}")
|
|
require(name != INDEX, "release-evidence.json must not describe itself")
|
|
require(name not in names, f"duplicate asset: {name}")
|
|
require(type(asset["size"]) is int and asset["size"] > 0, f"empty asset: {name}")
|
|
require(DIGEST_RE.fullmatch(asset["sha256"]) is not None, f"invalid digest: {name}")
|
|
names.add(name)
|
|
require(BASENAME_RE.fullmatch(target) is not None, f"invalid asset target: {target!r}")
|
|
records.append({"name": name, "size": asset["size"],
|
|
"target": target, "sha256": asset["sha256"]})
|
|
require(records, "a release needs at least one payload asset")
|
|
require(len(records) <= 127, "too many release assets")
|
|
seen: set[str] = set()
|
|
deps = []
|
|
for dependency in dependencies:
|
|
require(dependency["id"] not in seen, f"duplicate dependency: {dependency['id']}")
|
|
require(dependency["id"] != component_id, "a component cannot depend on itself")
|
|
require(len(deps) < MAX_DEPENDENCIES, "too many release dependencies")
|
|
seen.add(dependency["id"])
|
|
record = {"id": dependency["id"], "source_sha": dependency["source_sha"]}
|
|
if "asset_sha256" in dependency:
|
|
record["asset_sha256"] = dependency["asset_sha256"]
|
|
deps.append(record)
|
|
return {
|
|
"repository": repository,
|
|
"component_id": component_id,
|
|
"tag": tag,
|
|
"source_sha": source_sha,
|
|
"ci": ci,
|
|
"assets": records,
|
|
"dependencies": deps,
|
|
}
|
|
|
|
|
|
def write_evidence(evidence: dict, out: Path) -> Path:
|
|
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
|
require(len(payload.encode()) <= MAX_INDEX_BYTES, "release-evidence.json exceeds 1 MiB")
|
|
out.write_text(payload, encoding="utf-8")
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# HTTP clients
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
"""Never forward the publish token to another URL or host via a redirect."""
|
|
|
|
def redirect_request(self, request, fp, code, message, headers, newurl):
|
|
return None
|
|
|
|
|
|
OPENER = urllib.request.build_opener(NoRedirect)
|
|
|
|
|
|
def api_request(url: str, token: str, *, method: str = "GET", payload: dict | None = None,
|
|
raw: bytes | None = None, content_type: str = "application/json"):
|
|
headers = {"Accept": "application/json"}
|
|
if token:
|
|
headers["Authorization"] = f"token {token}"
|
|
data = raw
|
|
if payload is not None:
|
|
data = json.dumps(payload).encode()
|
|
headers["Content-Type"] = content_type
|
|
elif raw is not None:
|
|
headers["Content-Type"] = content_type
|
|
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with OPENER.open(request, timeout=120) as response:
|
|
return response.status, response.read(), dict(response.headers)
|
|
except urllib.error.HTTPError as error:
|
|
if 300 <= error.code < 400:
|
|
raise ReleaseError(f"unexpected redirect from {url}") from error
|
|
return error.code, error.read(), dict(error.headers)
|
|
except (urllib.error.URLError, TimeoutError) as error:
|
|
raise ReleaseError(f"request failed: {url}: {error}") from error
|
|
|
|
|
|
def read_json(url: str, token: str = "") -> object:
|
|
status, body, _ = api_request(url, token)
|
|
require(status == 200, f"GET {url} returned HTTP {status}")
|
|
try:
|
|
return json.loads(body)
|
|
except ValueError as error:
|
|
raise ReleaseError(f"GET {url} did not return JSON: {error}") from error
|
|
|
|
|
|
def ci_repository(repository: str, token: str) -> int:
|
|
forge = read_json(f"{FORGE}/api/v1/repos/{repository}", token)
|
|
ci = read_json(f"{CI}/api/repos/lookup/{repository}")
|
|
require(isinstance(forge, dict) and type(forge.get("id")) is int,
|
|
"Gitea does not identify the canonical repository")
|
|
require(isinstance(ci, dict) and ci.get("full_name") == repository
|
|
and type(ci.get("id")) is int and ci["id"] > 0
|
|
and ci.get("forge_remote_id") == str(forge["id"]),
|
|
"Woodpecker does not identify the canonical repository")
|
|
return ci["id"]
|
|
|
|
|
|
def discover_ci(repository: str, source_sha: str, workflow: str, token: str) -> dict:
|
|
"""Find the deterministic same-SHA component CI pipeline for the release."""
|
|
require(SHA_RE.fullmatch(source_sha) is not None, "release SHA must be a full commit")
|
|
repo_id = ci_repository(repository, token)
|
|
pipelines: list[dict] = []
|
|
for page in range(1, 5):
|
|
listing = read_json(f"{CI}/api/repos/{repo_id}/pipelines?per_page=50&page={page}")
|
|
require(isinstance(listing, list), "Woodpecker pipeline listing is malformed")
|
|
pipelines.extend(item for item in listing if isinstance(item, dict))
|
|
if len(listing) < 50:
|
|
break
|
|
candidates = sorted(
|
|
(item for item in pipelines
|
|
if item.get("commit") == source_sha and item.get("status") == "success"
|
|
and item.get("event") in ALLOWED_EVENTS
|
|
and type(item.get("number")) is int and item["number"] > 0),
|
|
key=lambda item: item["number"],
|
|
)
|
|
require(candidates, f"no successful same-SHA Woodpecker pipeline for {source_sha}")
|
|
# Deterministic: the oldest successful same-SHA run cannot change later, so
|
|
# re-running the transaction reproduces the same evidence.
|
|
number = candidates[0]["number"]
|
|
detail = read_json(f"{CI}/api/repos/{repo_id}/pipelines/{number}")
|
|
require(isinstance(detail, dict) and detail.get("number") == number
|
|
and detail.get("commit") == source_sha and detail.get("status") == "success",
|
|
f"Woodpecker pipeline {number} identity changed while verifying")
|
|
require(any(
|
|
isinstance(item, dict) and item.get("name") == workflow
|
|
and item.get("state") == "success"
|
|
and any(isinstance(step, dict) and step.get("type") == "commands"
|
|
and step.get("state") == "success" for step in item.get("children", []))
|
|
for item in detail.get("workflows", [])
|
|
), f"same-SHA pipeline {number} has no successful {workflow!r} workflow")
|
|
return {
|
|
"pipeline_number": number,
|
|
"url": f"{CI}/repos/{repo_id}/pipeline/{number}",
|
|
"source_sha": source_sha,
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Gitea release transaction
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def release_api(repository: str, tag: str = "") -> str:
|
|
base = f"{FORGE}/api/v1/repos/{repository}/releases"
|
|
return f"{base}/tags/{urllib.parse.quote(tag, safe='')}" if tag else base
|
|
|
|
|
|
def remote_tag_commit(repository: str, tag: str, token: str) -> str | None:
|
|
status, body, _ = api_request(
|
|
f"{FORGE}/api/v1/repos/{repository}/tags/{urllib.parse.quote(tag, safe='')}", token)
|
|
if status == 404:
|
|
return None
|
|
require(status == 200, f"tag lookup for {tag} returned HTTP {status}")
|
|
try:
|
|
data = json.loads(body)
|
|
except ValueError as error:
|
|
raise ReleaseError(f"tag lookup for {tag} is not JSON: {error}") from error
|
|
commit = ((data.get("commit") if isinstance(data, dict) else None) or {}).get("sha")
|
|
require(isinstance(commit, str) and SHA_RE.fullmatch(commit) is not None,
|
|
f"remote tag {tag} has no verifiable commit identity")
|
|
return commit
|
|
|
|
|
|
def find_release(repository: str, tag: str, token: str) -> dict | None:
|
|
status, body, _ = api_request(release_api(repository, tag), token)
|
|
if status == 404:
|
|
return None
|
|
require(status == 200, f"release lookup for {tag} returned HTTP {status}")
|
|
try:
|
|
release = json.loads(body)
|
|
except ValueError as error:
|
|
raise ReleaseError(f"release lookup for {tag} is not JSON: {error}") from error
|
|
require(isinstance(release, dict) and type(release.get("id")) is int,
|
|
f"release lookup for {tag} is malformed")
|
|
return release
|
|
|
|
|
|
def release_assets(repository: str, tag: str, token: str) -> dict:
|
|
"""Return name -> release asset record, verifying canonical download URLs."""
|
|
release = find_release(repository, tag, token)
|
|
require(release is not None, f"release {tag} is missing after publish")
|
|
assets: dict[str, dict] = {}
|
|
for asset in release.get("assets") or []:
|
|
name = asset.get("name")
|
|
require(isinstance(name, str) and BASENAME_RE.fullmatch(name) is not None,
|
|
"release carries an unsafe asset name")
|
|
expected = (
|
|
f"{FORGE}/{repository}/releases/download/"
|
|
f"{urllib.parse.quote(tag, safe='')}/{urllib.parse.quote(name, safe='')}"
|
|
)
|
|
require(asset.get("browser_download_url") == expected,
|
|
f"asset {name} has a non-canonical download URL")
|
|
require(name not in assets, f"duplicate release asset {name}")
|
|
assets[name] = asset
|
|
return assets
|
|
|
|
|
|
def download_verified(asset: dict, token: str) -> bytes:
|
|
headers = {"Accept": "application/octet-stream"}
|
|
if token:
|
|
headers["Authorization"] = f"token {token}"
|
|
request = urllib.request.Request(asset["browser_download_url"], headers=headers)
|
|
try:
|
|
with OPENER.open(request, timeout=120) as response:
|
|
data = response.read(MAX_ASSET_BYTES + 1)
|
|
except urllib.error.HTTPError as error:
|
|
raise ReleaseError(
|
|
f"asset download {asset['name']} returned HTTP {error.code}") from error
|
|
except (urllib.error.URLError, TimeoutError) as error:
|
|
raise ReleaseError(f"asset download {asset['name']} failed: {error}") from error
|
|
require(len(data) <= MAX_ASSET_BYTES, f"asset {asset['name']} exceeds the size limit")
|
|
require(len(data) == int(asset.get("size") or -1),
|
|
f"asset {asset['name']} size differs from its release record")
|
|
return data
|
|
|
|
|
|
def published_matches(repository: str, tag: str, expected: list[dict], token: str) -> bool:
|
|
try:
|
|
assets = release_assets(repository, tag, token)
|
|
if set(assets) != {item["name"] for item in expected}:
|
|
return False
|
|
for item in expected:
|
|
data = download_verified(assets[item["name"]], token)
|
|
if sha256_bytes(data) != item["sha256"]:
|
|
return False
|
|
return True
|
|
except ReleaseError:
|
|
return False
|
|
|
|
|
|
def create_draft(repository: str, tag: str, body: str, target: str,
|
|
prerelease: bool, token: str) -> dict:
|
|
payload = {"tag_name": tag, "name": tag, "body": body, "draft": True,
|
|
"prerelease": prerelease, "target_commitish": target}
|
|
status, response, _ = api_request(
|
|
release_api(repository), token, method="POST", payload=payload)
|
|
require(status in (200, 201),
|
|
f"creating draft release {tag} returned HTTP {status}: {response[:200]!r}")
|
|
try:
|
|
release = json.loads(response)
|
|
except ValueError as error:
|
|
raise ReleaseError("draft release response is not JSON") from error
|
|
require(isinstance(release, dict) and type(release.get("id")) is int,
|
|
"draft release response is malformed")
|
|
return release
|
|
|
|
|
|
def patch_release(repository: str, release_id: int, payload: dict, token: str) -> dict:
|
|
status, response, _ = api_request(
|
|
f"{release_api(repository)}/{release_id}", token, method="PATCH", payload=payload)
|
|
require(status == 200, f"updating release {release_id} returned HTTP {status}")
|
|
try:
|
|
release = json.loads(response)
|
|
except ValueError as error:
|
|
raise ReleaseError("release update response is not JSON") from error
|
|
require(isinstance(release, dict), "release update response is malformed")
|
|
return release
|
|
|
|
|
|
def delete_release(repository: str, release_id: int, token: str) -> None:
|
|
status, response, _ = api_request(
|
|
f"{release_api(repository)}/{release_id}", token, method="DELETE")
|
|
require(status in (200, 204),
|
|
f"deleting draft release {release_id} returned HTTP {status}: {response[:200]!r}")
|
|
|
|
|
|
def upload_asset(repository: str, release_id: int, path: Path, token: str) -> dict:
|
|
name = path.name
|
|
require(path.stat().st_size <= MAX_ASSET_BYTES, f"asset {name} exceeds the size limit")
|
|
existing = read_json(f"{release_api(repository)}/{release_id}/assets", token)
|
|
require(isinstance(existing, list), "release asset listing is malformed")
|
|
for asset in existing:
|
|
if asset.get("name") == name:
|
|
raise ReleaseError(
|
|
f"asset {name} already exists on release {release_id}; refusing to overwrite")
|
|
boundary = f"----marqdo{uuid.uuid4().hex}"
|
|
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
body = bytearray()
|
|
body.extend(f"--{boundary}\r\n".encode())
|
|
body.extend(f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode())
|
|
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
|
|
body.extend(path.read_bytes())
|
|
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
|
status, response, _ = api_request(
|
|
f"{release_api(repository)}/{release_id}/assets?"
|
|
f"name={urllib.parse.quote(name, safe='')}",
|
|
token, method="POST", raw=bytes(body),
|
|
content_type=f"multipart/form-data; boundary={boundary}")
|
|
require(status in (200, 201),
|
|
f"uploading {name} returned HTTP {status}: {response[:200]!r}")
|
|
try:
|
|
asset = json.loads(response)
|
|
except ValueError as error:
|
|
raise ReleaseError(f"upload response for {name} is not JSON") from error
|
|
require(isinstance(asset, dict) and asset.get("name") == name,
|
|
f"upload response for {name} is malformed")
|
|
return asset
|
|
|
|
|
|
def publish_release(*, repository: str, tag: str, source_sha: str, body: str,
|
|
prerelease: bool, assets: list[Path], token: str,
|
|
reset_draft: bool = False) -> dict:
|
|
require(token, "GITEA_PUBLISH_TOKEN is required to publish")
|
|
require(assets, "no assets to publish")
|
|
index_assets = [path for path in assets if path.name == INDEX]
|
|
payload_assets = [path for path in assets if path.name != INDEX]
|
|
require(len(index_assets) == 1, "exactly one release-evidence.json is required")
|
|
ordered = payload_assets + index_assets
|
|
expected = [{"name": path.name, "size": path.stat().st_size,
|
|
"sha256": sha256_file(path)} for path in ordered]
|
|
|
|
existing = find_release(repository, tag, token)
|
|
if existing is not None and not existing.get("draft"):
|
|
require(existing.get("tag_name") == tag, f"tag {tag} does not identify its own release")
|
|
require(existing.get("prerelease") == prerelease,
|
|
f"published release {tag} has a different channel than the version string")
|
|
if published_matches(repository, tag, expected, token):
|
|
return {"status": "idempotent", "release_id": existing["id"], "tag": tag,
|
|
"url": existing.get("html_url"), "assets": expected}
|
|
raise ReleaseError(
|
|
f"published release {tag} already exists with different bytes; refusing to overwrite")
|
|
|
|
if existing is not None and existing.get("draft"):
|
|
if reset_draft:
|
|
delete_release(repository, int(existing["id"]), token)
|
|
existing = None
|
|
else:
|
|
for asset in existing.get("assets") or []:
|
|
if asset.get("name") in {path.name for path in ordered}:
|
|
raise ReleaseError(
|
|
f"draft release {tag} already carries {asset.get('name')}; "
|
|
"use --reset-draft to recreate the draft")
|
|
|
|
if existing is not None:
|
|
release = patch_release(repository, int(existing["id"]), {
|
|
"name": tag, "body": body, "draft": True,
|
|
"prerelease": prerelease, "target_commitish": source_sha}, token)
|
|
else:
|
|
release = create_draft(repository, tag, body, source_sha, prerelease, token)
|
|
|
|
release_id = int(release["id"])
|
|
remote = {asset.get("name") for asset in read_json(
|
|
f"{release_api(repository)}/{release_id}/assets", token)}
|
|
for path in ordered:
|
|
if path.name in remote:
|
|
continue
|
|
upload_asset(repository, release_id, path, token)
|
|
|
|
if not published_matches(repository, tag, expected, token):
|
|
raise ReleaseError("draft release assets did not round-trip byte for byte")
|
|
published = patch_release(repository, release_id, {
|
|
"draft": False, "prerelease": prerelease, "name": tag, "body": body}, token)
|
|
require(published.get("draft") is False, "release remained a draft after publishing")
|
|
if not published_matches(repository, tag, expected, token):
|
|
raise ReleaseError("published release assets did not round-trip byte for byte")
|
|
final = find_release(repository, tag, token)
|
|
require(final is not None and final.get("draft") is False,
|
|
"published release cannot be re-read")
|
|
return {"status": "published", "release_id": final["id"], "tag": tag,
|
|
"url": final.get("html_url"), "assets": expected}
|
|
|
|
|
|
def default_body(*, repository: str, component_id: str, kind: str, tag: str,
|
|
source_sha: str, ci: dict, assets: list[dict], dependencies: list[dict]) -> str:
|
|
lines = [
|
|
f"Independent {kind} component release for `{component_id}` (`{repository}`) `{tag}`.",
|
|
"",
|
|
f"- Component: `{component_id}` ({kind})",
|
|
f"- Source commit: `{source_sha}`",
|
|
f"- Same-SHA component CI: {ci['url']}",
|
|
"- Assets: " + ", ".join(
|
|
f"`{item['name']}` ({item['size']} bytes, sha256 `{item['sha256']}`)"
|
|
for item in assets),
|
|
"- Tested dependencies: " + (
|
|
", ".join(f"`{item['id']}@{item['source_sha'][:12]}`" for item in dependencies)
|
|
or "none"),
|
|
"",
|
|
"This is a component release. Root recommendation/acceptance and consumer "
|
|
"updates are separate facts tracked by the ecosystem reconcile flow; "
|
|
"installing it does not grant permissions or update any runtime.",
|
|
]
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# CLI
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def common_parser(parser: argparse.ArgumentParser) -> None:
|
|
parser.add_argument("--root", default=".", help="component repository root")
|
|
parser.add_argument("--repository", required=True, help="owner/name on the authoritative forge")
|
|
parser.add_argument("--component-id", required=True)
|
|
parser.add_argument("--kind", choices=sorted(KIND_SUFFIX), required=True)
|
|
parser.add_argument("--allow", action="append", default=[], required=True,
|
|
help="released path relative to the repository root (repeatable)")
|
|
parser.add_argument("--source-sha", default=None,
|
|
help="exact commit to release (default: HEAD)")
|
|
parser.add_argument("--out-dir", default=None,
|
|
help="output directory for the packaged assets")
|
|
|
|
|
|
def resolve_source(root: Path, args) -> str:
|
|
if args.source_sha:
|
|
require(SHA_RE.fullmatch(args.source_sha) is not None,
|
|
"source SHA must be 40 lowercase hex")
|
|
require(commit_exists(root, args.source_sha),
|
|
"source SHA is not a commit in this repository")
|
|
return args.source_sha
|
|
return resolved_head(root)
|
|
|
|
|
|
def command_check(args) -> int:
|
|
root = Path(args.root).resolve()
|
|
source_sha = resolve_source(root, args)
|
|
with tempfile.TemporaryDirectory(prefix="mq-release-check-") as temporary:
|
|
result = package_assets(root, source_sha, args.repository, args.component_id,
|
|
"0.0.0", args.kind, list(args.allow), Path(temporary))
|
|
payload = {
|
|
"status": "PASS",
|
|
"component_id": args.component_id,
|
|
"repository": args.repository,
|
|
"kind": args.kind,
|
|
"source_sha": source_sha,
|
|
"artifacts": [{key: artifact[key] for key in ("format", "name", "size", "sha256")}
|
|
for artifact in result["artifacts"]],
|
|
"files": result["files"],
|
|
"released_paths": sorted(args.allow),
|
|
}
|
|
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
return 0
|
|
|
|
|
|
def command_publish(args) -> int:
|
|
token = os.environ.get("GITEA_PUBLISH_TOKEN", "")
|
|
require(token, "GITEA_PUBLISH_TOKEN is required to publish")
|
|
require(args.tag, "publish requires --tag")
|
|
version = validate_version(args.tag)
|
|
prerelease = "-" in version
|
|
root = Path(args.root).resolve()
|
|
source_sha = resolve_source(root, args)
|
|
require(resolved_head(root) == source_sha,
|
|
"publish must run on the exact checked-out release commit")
|
|
local_tag = subprocess.run(
|
|
["git", "-C", str(root), "rev-parse", "-q", "--verify",
|
|
f"refs/tags/{args.tag}^{{commit}}"], capture_output=True)
|
|
if local_tag.returncode == 0:
|
|
require(local_tag.stdout.decode().strip() == source_sha,
|
|
f"local tag {args.tag} does not point at the released commit")
|
|
remote_sha = remote_tag_commit(args.repository, args.tag, token)
|
|
if remote_sha is not None:
|
|
require(remote_sha == source_sha,
|
|
f"remote tag {args.tag} points at {remote_sha}, not the released commit "
|
|
f"{source_sha}; refusing to publish a mismatched release")
|
|
dependencies = [parse_dependency(item) for item in args.dependency]
|
|
|
|
if args.out_dir:
|
|
out_dir = Path(args.out_dir)
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
return _publish(args, root, source_sha, version, prerelease, dependencies,
|
|
out_dir, token)
|
|
with tempfile.TemporaryDirectory(prefix="mq-release-") as temporary:
|
|
return _publish(args, root, source_sha, version, prerelease, dependencies,
|
|
Path(temporary), token)
|
|
|
|
|
|
def _publish(args, root, source_sha, version, prerelease, dependencies, out_dir, token) -> int:
|
|
payload = package_assets(root, source_sha, args.repository, args.component_id,
|
|
version, args.kind, list(args.allow), out_dir)
|
|
ci = discover_ci(args.repository, source_sha, WORKFLOW, token)
|
|
asset_records = []
|
|
publish_paths = []
|
|
for artifact in payload["artifacts"]:
|
|
asset_records.append({"name": artifact["name"], "size": artifact["size"],
|
|
"sha256": artifact["sha256"]})
|
|
asset_records.append({"name": artifact["checksum"].name,
|
|
"size": artifact["checksum"].stat().st_size,
|
|
"sha256": sha256_file(artifact["checksum"])})
|
|
publish_paths.extend([artifact["path"], artifact["checksum"]])
|
|
evidence = build_evidence(
|
|
repository=args.repository, component_id=args.component_id, tag=args.tag,
|
|
source_sha=source_sha, ci=ci, assets=asset_records,
|
|
dependencies=dependencies)
|
|
evidence_path = write_evidence(evidence, out_dir / INDEX)
|
|
body = args.body or default_body(
|
|
repository=args.repository, component_id=args.component_id, kind=args.kind,
|
|
tag=args.tag, source_sha=source_sha, ci=ci, assets=evidence["assets"],
|
|
dependencies=evidence["dependencies"])
|
|
if args.note:
|
|
body = body.rstrip("\n") + "\n\n" + "\n".join(f"- {note}" for note in args.note) + "\n"
|
|
result = publish_release(
|
|
repository=args.repository, tag=args.tag, source_sha=source_sha, body=body,
|
|
prerelease=prerelease,
|
|
assets=[*publish_paths, evidence_path], token=token,
|
|
reset_draft=args.reset_draft)
|
|
print(json.dumps({
|
|
"status": result["status"],
|
|
"repository": args.repository,
|
|
"component_id": args.component_id,
|
|
"tag": args.tag,
|
|
"version": version,
|
|
"channel": "prerelease" if prerelease else "stable",
|
|
"source_sha": source_sha,
|
|
"ci": ci,
|
|
"url": result.get("url"),
|
|
"assets": [{"name": item["name"], "size": item["size"],
|
|
"sha256": item["sha256"]} for item in result["assets"]],
|
|
"dependencies": evidence["dependencies"],
|
|
}, ensure_ascii=False, indent=2))
|
|
return 0
|
|
|
|
|
|
def command_archive_dir(args) -> int:
|
|
root = Path(args.input).resolve()
|
|
require(args.name != "" and "/" not in args.name, "invalid package name")
|
|
out_dir = Path(args.output_dir)
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
artifacts = package_directory(root, args.name, out_dir)
|
|
print(json.dumps({
|
|
"status": "PASS",
|
|
"prefix": args.name,
|
|
"files": len(directory_files(root)),
|
|
"artifacts": [{key: artifact[key] for key in ("format", "name", "size", "sha256")}
|
|
for artifact in artifacts],
|
|
}, ensure_ascii=False, indent=2))
|
|
return 0
|
|
|
|
|
|
def command_publish_assets(args) -> int:
|
|
token = os.environ.get("GITEA_PUBLISH_TOKEN", "")
|
|
require(token, "GITEA_PUBLISH_TOKEN is required to publish")
|
|
version = validate_version(args.tag)
|
|
prerelease = "-" in version
|
|
root = Path(args.root).resolve()
|
|
source_sha = resolved_head(root)
|
|
local_tag = subprocess.run(
|
|
["git", "-C", str(root), "rev-parse", "-q", "--verify",
|
|
f"refs/tags/{args.tag}^{{commit}}"], capture_output=True)
|
|
if local_tag.returncode == 0:
|
|
require(local_tag.stdout.decode().strip() == source_sha,
|
|
f"local tag {args.tag} does not point at the released commit")
|
|
remote = remote_tag_commit(args.repository, args.tag, token)
|
|
if remote is not None:
|
|
require(remote == source_sha,
|
|
f"remote tag {args.tag} points at {remote}, not {source_sha}")
|
|
assets = [Path(value) for value in args.asset]
|
|
require(assets, "publish-assets requires --asset")
|
|
for path in assets:
|
|
require(path.is_file(), f"missing release asset: {path}")
|
|
require(BASENAME_RE.fullmatch(path.name) is not None, f"unsafe asset name: {path.name}")
|
|
dependencies = [parse_dependency(value) for value in args.dependency]
|
|
with tempfile.TemporaryDirectory(prefix="mq-release-assets-") as temporary:
|
|
ci = discover_ci(args.repository, source_sha, WORKFLOW, token)
|
|
evidence = build_evidence(
|
|
repository=args.repository, component_id=args.component_id, tag=args.tag,
|
|
source_sha=source_sha, ci=ci,
|
|
assets=[{"name": path.name, "size": path.stat().st_size,
|
|
"sha256": sha256_file(path)} for path in assets],
|
|
dependencies=dependencies, target=args.target)
|
|
evidence_path = write_evidence(evidence, Path(temporary) / INDEX)
|
|
body = args.body or default_body(
|
|
repository=args.repository, component_id=args.component_id, kind=args.kind,
|
|
tag=args.tag, source_sha=source_sha, ci=ci, assets=evidence["assets"],
|
|
dependencies=evidence["dependencies"])
|
|
if args.note:
|
|
body = body.rstrip("\n") + "\n\n" + "\n".join(f"- {note}" for note in args.note) + "\n"
|
|
result = publish_release(
|
|
repository=args.repository, tag=args.tag, source_sha=source_sha, body=body,
|
|
prerelease=prerelease, assets=[*assets, evidence_path], token=token,
|
|
reset_draft=args.reset_draft)
|
|
print(json.dumps({
|
|
"status": result["status"],
|
|
"repository": args.repository,
|
|
"component_id": args.component_id,
|
|
"tag": args.tag,
|
|
"version": version,
|
|
"channel": "prerelease" if prerelease else "stable",
|
|
"source_sha": source_sha,
|
|
"ci": ci,
|
|
"url": result.get("url"),
|
|
"assets": [{"name": item["name"], "size": item["size"],
|
|
"sha256": item["sha256"]} for item in result["assets"]],
|
|
}, ensure_ascii=False, indent=2))
|
|
return 0
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
|
|
check = commands.add_parser(
|
|
"check", help="package the exact commit twice and verify the artifact in CI")
|
|
common_parser(check)
|
|
|
|
publish = commands.add_parser(
|
|
"publish", help="package, evidence and publish one immutable Gitea release")
|
|
common_parser(publish)
|
|
publish.add_argument("--tag", required=True, help="release tag, e.g. v0.1.0")
|
|
publish.add_argument("--dependency", action="append", default=[],
|
|
help="tested dependency: id=<id>,source_sha=<sha>[,asset_sha256=<digest>]")
|
|
publish.add_argument("--body", default="", help="release body (default: generated)")
|
|
publish.add_argument("--note", action="append", default=[],
|
|
help="extra fact appended to the generated release body (repeatable)")
|
|
publish.add_argument("--reset-draft", action="store_true",
|
|
help="delete an interrupted draft release before recreating it")
|
|
|
|
archive = commands.add_parser(
|
|
"archive-dir", help="package an already-built tool bundle as deterministic tar.gz + zip")
|
|
archive.add_argument("--input", required=True, help="package directory")
|
|
archive.add_argument("--name", required=True, help="archive prefix, e.g. repo-version-target")
|
|
archive.add_argument("--output-dir", required=True)
|
|
|
|
assets = commands.add_parser(
|
|
"publish-assets", help="publish already-built assets with release-evidence.json")
|
|
assets.add_argument("--root", default=".")
|
|
assets.add_argument("--repository", required=True)
|
|
assets.add_argument("--component-id", required=True)
|
|
assets.add_argument("--kind", choices=sorted(KIND_SUFFIX), default="extension")
|
|
assets.add_argument("--tag", required=True)
|
|
assets.add_argument("--asset", action="append", default=[],
|
|
help="release asset file (repeatable, includes sidecars)")
|
|
assets.add_argument("--target", default="x86_64-unknown-linux-gnu")
|
|
assets.add_argument("--dependency", action="append", default=[])
|
|
assets.add_argument("--body", default="")
|
|
assets.add_argument("--note", action="append", default=[])
|
|
assets.add_argument("--reset-draft", action="store_true")
|
|
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
if args.command == "check":
|
|
return command_check(args)
|
|
if args.command == "archive-dir":
|
|
return command_archive_dir(args)
|
|
if args.command == "publish-assets":
|
|
return command_publish_assets(args)
|
|
return command_publish(args)
|
|
except ReleaseError as error:
|
|
print(f"component-release: FAIL: {error}", file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main(sys.argv[1:]))
|