149 lines
5.8 KiB
Python
149 lines
5.8 KiB
Python
"""Create the next immutable version tag for a successfully validated merged PR."""
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
|
|
VERSION = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
|
|
ASSESSMENT = re.compile(
|
|
r"(?im)^\s*Release assessment:\s*(none|patch|minor|major)\s*—\s*(.*?)\s*$"
|
|
)
|
|
SHA = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$", re.IGNORECASE)
|
|
|
|
|
|
def fail(message):
|
|
raise SystemExit(message)
|
|
|
|
|
|
server = os.environ.get("BUILD_SERVER_URL", "").rstrip("/")
|
|
repository = os.environ.get("BUILD_REPOSITORY", "")
|
|
sha = os.environ.get("CURRENT_SHA", "").lower()
|
|
token = os.environ.get("GITEA_TOKEN", "")
|
|
if not server.startswith("https://"):
|
|
fail("BUILD_SERVER_URL must use HTTPS")
|
|
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
|
|
fail("BUILD_REPOSITORY is not a valid owner/repository")
|
|
if not SHA.fullmatch(sha):
|
|
fail("CURRENT_SHA is not a full Git commit SHA")
|
|
if not token:
|
|
fail("GITEA_TOKEN is unavailable to the release-tag job")
|
|
|
|
api = f"{server}/api/v1/repos/{repository}"
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status):
|
|
self.status = status
|
|
|
|
|
|
def request(path, method="GET", body=None, allow_missing=False):
|
|
payload = json.dumps(body).encode("utf-8") if body is not None else None
|
|
headers = {"Authorization": "token " + token, "Accept": "application/json"}
|
|
if payload is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(api + path, data=payload, method=method, headers=headers)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as response:
|
|
data = response.read()
|
|
return json.loads(data) if data else None
|
|
except urllib.error.HTTPError as error:
|
|
if allow_missing and error.code == 404:
|
|
return None
|
|
raise ApiError(error.code) from None
|
|
except (urllib.error.URLError, TimeoutError):
|
|
fail("Gitea API request failed due to a network or TLS error")
|
|
|
|
|
|
def verify_tag(tag_name, expected_sha):
|
|
existing = request("/tags/" + urllib.parse.quote(tag_name, safe=""), allow_missing=True)
|
|
if existing is None:
|
|
return False
|
|
actual_sha = (existing.get("commit") or {}).get("sha", "").lower()
|
|
if actual_sha != expected_sha:
|
|
fail(f"Refusing to overwrite existing tag {tag_name} at a different commit")
|
|
print(f"Version tag already points to this commit: {tag_name}")
|
|
return True
|
|
|
|
|
|
try:
|
|
subprocess.run(["git", "cat-file", "-e", f"{sha}^{{commit}}"], check=True,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
except (subprocess.CalledProcessError, FileNotFoundError):
|
|
fail("The pushed commit is missing from the checked-out Git history")
|
|
|
|
try:
|
|
pull = request(f"/commits/{sha}/pull", allow_missing=True)
|
|
except ApiError as error:
|
|
fail(f"Could not inspect the merged pull request (Gitea HTTP {error.status})")
|
|
|
|
if pull is None:
|
|
print("No pull request is associated with this main push; no version tag created")
|
|
sys.exit(0)
|
|
if not pull.get("merged") or pull.get("state") != "closed":
|
|
print("The associated pull request is not merged; no version tag created")
|
|
sys.exit(0)
|
|
if (pull.get("base") or {}).get("ref") != "main":
|
|
print("The associated pull request did not target main; no version tag created")
|
|
sys.exit(0)
|
|
if (pull.get("merge_commit_sha") or "").lower() != sha:
|
|
fail("The pull request merge SHA does not match the main push SHA")
|
|
|
|
body = pull.get("body") or ""
|
|
assessment_lines = [line for line in body.splitlines()
|
|
if re.match(r"^\s*Release assessment:", line, re.IGNORECASE)]
|
|
matches = [ASSESSMENT.fullmatch(line) for line in assessment_lines]
|
|
if len(matches) != 1 or matches[0] is None:
|
|
fail("Merged PR must contain exactly one machine-readable 'Release assessment: <none|patch|minor|major> — <rationale>' line")
|
|
assessment, rationale = matches[0].groups()
|
|
if not rationale.strip() or rationale.strip().lower() in {"rationale", "reason", "<rationale>"}:
|
|
fail("Merged PR release assessment must include a concrete rationale")
|
|
if assessment == "none":
|
|
print("Merged PR is explicitly assessed as no release; no version tag created")
|
|
sys.exit(0)
|
|
|
|
try:
|
|
tags = subprocess.run(["git", "tag", "--merged", sha, "--sort=-version:refname"],
|
|
check=True, capture_output=True, text=True).stdout.splitlines()
|
|
except (subprocess.CalledProcessError, FileNotFoundError):
|
|
fail("Could not read reachable version tags from the checked-out Git history")
|
|
|
|
versions = []
|
|
for name in tags:
|
|
match = VERSION.fullmatch(name)
|
|
if match:
|
|
versions.append((tuple(int(part) for part in match.groups()), name))
|
|
if not versions:
|
|
fail("No reachable stable MAJOR.MINOR.PATCH tag was found; refusing to guess a version")
|
|
|
|
(major, minor, patch), previous = max(versions, key=lambda version: version[0])
|
|
if assessment == "major":
|
|
major, minor, patch = major + 1, 0, 0
|
|
elif assessment == "minor":
|
|
major, minor, patch = major, minor + 1, 0
|
|
else:
|
|
major, minor, patch = major, minor, patch + 1
|
|
tag_name = f"{major}.{minor}.{patch}"
|
|
|
|
try:
|
|
if verify_tag(tag_name, sha):
|
|
sys.exit(0)
|
|
created = request("/tags", method="POST", body={
|
|
"tag_name": tag_name,
|
|
"target": sha,
|
|
"message": f"Heimdall {tag_name}",
|
|
})
|
|
except ApiError as error:
|
|
if error.status in (409, 422) and verify_tag(tag_name, sha):
|
|
sys.exit(0)
|
|
fail(f"Could not create version tag {tag_name} (Gitea HTTP {error.status})")
|
|
|
|
created_sha = (created.get("commit") or {}).get("sha", "").lower()
|
|
if created.get("name") != tag_name or created_sha != sha:
|
|
fail("Gitea tag creation response did not confirm the requested immutable target")
|
|
print(f"Created {tag_name} from {assessment} impact after CI policy passed; previous stable tag: {previous}; target commit: {sha}")
|