Files
Echoion/scripts/prepare-component-release.py
T
faumaray 4f8a46b0c4
Modular container CI / release-build (push) Has been cancelled
Release: exclude pinned tools checkout from source dirtiness
2026-07-30 04:06:27 +03:00

268 lines
9.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Validate and derive one component's independent release identity."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import subprocess
import sys
from typing import Any, NoReturn
SEMVER = re.compile(
r"^(?P<major>0|[1-9][0-9]*)\."
r"(?P<minor>0|[1-9][0-9]*)\."
r"(?P<patch>0|[1-9][0-9]*)$"
)
RELEASE_VERSION = re.compile(
r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
)
def fail(message: str) -> NoReturn:
raise SystemExit(f"prepare-component-release: {message}")
def canonical(value: Any) -> bytes:
return (
json.dumps(
value,
ensure_ascii=False,
allow_nan=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
+ b"\n"
)
def load_object(path: Path, label: str) -> dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as error:
fail(f"cannot read {label} {path}: {error}")
if not isinstance(value, dict):
fail(f"{label} must be a JSON object")
return value
def git(repository: Path, *arguments: str) -> str:
try:
return subprocess.check_output(
["git", "-C", str(repository), *arguments],
text=True,
stderr=subprocess.STDOUT,
).strip()
except (OSError, subprocess.CalledProcessError) as error:
detail = getattr(error, "output", "") or str(error)
fail(f"git {' '.join(arguments)} failed: {detail.strip()}")
def read_contract(repository: Path, revision: str, relative: str) -> Any:
raw = git(repository, "show", f"{revision}:{relative}")
try:
value = json.loads(raw)
except json.JSONDecodeError as error:
fail(f"{relative} at {revision} is invalid JSON: {error}")
if not isinstance(value, dict) or value.get("schemaVersion") != 1:
fail(f"{relative} at {revision} has an unsupported ABI schema")
return value
def compatible_append(old: Any, new: Any) -> bool:
if type(old) is not type(new):
return False
if isinstance(old, dict):
return all(
key in new and compatible_append(value, new[key])
for key, value in old.items()
)
if isinstance(old, list):
return len(new) >= len(old) and all(
compatible_append(value, new[index])
for index, value in enumerate(old)
)
return old == new
def change_classification(old: Any, new: Any) -> str:
if canonical(old) == canonical(new):
return "patch"
return "minor" if compatible_append(old, new) else "major"
def bump(version: str, change: str) -> str:
match = SEMVER.fullmatch(version)
if match is None:
fail(f"previous stable version is invalid: {version!r}")
major = int(match.group("major"))
minor = int(match.group("minor"))
patch = int(match.group("patch"))
if change == "patch":
return f"{major}.{minor}.{patch + 1}"
if change == "minor":
return f"{major}.{minor + 1}.0"
if change == "major":
return f"{major + 1}.0.0"
raise AssertionError(change)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--registry", type=Path, required=True)
parser.add_argument("--configuration", type=Path, required=True)
parser.add_argument("--repository", type=Path, required=True)
parser.add_argument("--feed-root", type=Path, required=True)
parser.add_argument(
"--channel", choices=("stable", "beta", "nightly"), required=True
)
parser.add_argument("--requested-version")
parser.add_argument("--nightly-sequence")
parser.add_argument("--output", type=Path)
arguments = parser.parse_args()
registry = load_object(arguments.registry, "component registry")
configuration = load_object(
arguments.configuration, "component release configuration"
)
definitions = registry.get("components")
if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict):
fail("unsupported component registry schema")
if configuration.get("schemaVersion") != 1:
fail("unsupported component release configuration schema")
component_id = configuration.get("componentId")
definition = definitions.get(component_id)
if not isinstance(component_id, str) or not isinstance(definition, dict):
fail("configured component is not present in the registry")
compatibility = configuration.get("productCompatibility")
if not isinstance(compatibility, str) or not compatibility:
fail("productCompatibility is required")
if not isinstance(configuration.get("cmakeOptions"), dict):
fail("cmakeOptions must be an object")
repository = arguments.repository.resolve(strict=True)
if git(
repository,
"status",
"--porcelain",
"--untracked-files=all",
"--",
".",
":(exclude).echoion-release-tools",
":(exclude).echoion-release-tools/**",
):
fail("component repository must be clean")
source_sha = git(repository, "rev-parse", "HEAD")
source_tree = git(repository, "rev-parse", "HEAD^{tree}")
state_path = (
arguments.feed_root
/ "state"
/ "components"
/ f"{component_id}.json"
)
state = (
load_object(state_path, "component state")
if state_path.exists()
else {}
)
channels = state.get("channels", {})
if not isinstance(channels, dict):
fail("component state channels must be an object")
channel_state = channels.get(arguments.channel, {})
if not isinstance(channel_state, dict):
fail("component channel state must be an object")
if channel_state.get("sourceSha") == source_sha:
if arguments.channel == "nightly":
print("component source is already published in nightly")
return 3
fail(f"component source is already published in {arguments.channel}")
previous_version = state.get("semVer")
previous_sha = state.get("lastSourceSha")
contract_path = definition.get("abiContract")
abi_hash = None
if contract_path is not None:
if not isinstance(contract_path, str) or not contract_path:
fail("registered ABI contract path is invalid")
current_contract = read_contract(repository, source_sha, contract_path)
abi_hash = "sha256:" + hashlib.sha256(
canonical(current_contract)
).hexdigest()
else:
current_contract = None
if previous_version is None:
expected_stable = "2.0.0"
change = "initial"
else:
if not isinstance(previous_sha, str) or not re.fullmatch(
r"[0-9a-f]{40}", previous_sha
):
fail("stable component state has no valid source SHA")
if previous_sha == source_sha:
fail("unchanged source cannot produce another release")
if current_contract is None:
change = "patch"
else:
previous_contract = read_contract(
repository, previous_sha, contract_path
)
change = change_classification(
previous_contract, current_contract
)
expected_stable = bump(str(previous_version), change)
if arguments.channel == "nightly":
if not arguments.nightly_sequence or not re.fullmatch(
r"[0-9]+", arguments.nightly_sequence
):
fail("--nightly-sequence must be a positive integer")
version = f"{expected_stable}-nightly.{arguments.nightly_sequence}"
else:
requested = arguments.requested_version
if not isinstance(requested, str) or not RELEASE_VERSION.fullmatch(
requested
):
fail("--requested-version must be canonical SemVer")
requested_base = requested.split("-", 1)[0]
if requested_base != expected_stable:
fail(
f"{change} change requires version {expected_stable}; "
f"received {requested}"
)
if arguments.channel == "stable" and "-" in requested:
fail("stable release version must not have a prerelease suffix")
if arguments.channel == "beta" and "-" not in requested:
fail("beta release version must have a prerelease suffix")
version = requested
result = {
"schemaVersion": 1,
"componentId": component_id,
"channel": arguments.channel,
"componentVersion": version,
"productCompatibility": compatibility,
"sourceSha": source_sha,
"sourceTreeHash": f"git-sha1:{source_tree}",
"abiHash": abi_hash,
"change": change,
}
encoded = canonical(result)
if arguments.output is None:
sys.stdout.buffer.write(encoded)
else:
temporary = arguments.output.with_name(arguments.output.name + ".tmp")
temporary.write_bytes(encoded)
temporary.replace(arguments.output)
return 0
if __name__ == "__main__":
raise SystemExit(main())