Files
laravel-manager/.gitea/scripts/release.py
T

101 lines
3.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Release step of the `Release` workflow: tag what was just merged into production.
A push to production is a release when it is the merge of a `release/vX.Y.Z` pull request. This
finds that version (from the pull request Gitea knows for the commit, or from the merge message),
and makes the release `vX.Y.Z` on that commit, with the changelog section as its text. Gitea
makes the tag; Packagist picks the tag up in the next step.
Runs again on the same commit without harm: a tag that is already there on that commit is fine.
A push that is not a release merge (a hotfix pushed by an admin, say) makes no release and says so.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create releases), COMMIT_HASH.
Standard library + git only.
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
COMMIT = os.environ.get("COMMIT_HASH", "").strip()
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def release_branch_of(commit):
"""The release branch whose pull request made this commit, or None."""
pull = api("GET", f"commits/{commit}/pull", allow=(404,))
head = ((pull or {}).get("head") or {}).get("ref", "")
if semver.release_version(head):
return head
# Gitea's own merge message: "Merge pull request 'title' (#7) from release/v1.2.0 into production".
message = subprocess.run(["git", "log", "-1", "--pretty=%s", commit], capture_output=True, text=True).stdout
found = re.search(r"from (release/v\d+\.\d+\.\d+) into production", message)
return found.group(1) if found else None
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
if not re.fullmatch(r"[0-9a-f]{40}", COMMIT):
sys.exit("COMMIT_HASH must be the full commit hash.")
branch = release_branch_of(COMMIT)
if branch is None:
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z pull request: no release made.")
return
version = semver.release_version(branch)
tag = f"v{semver.text(version)}"
existing = api("GET", f"releases/tags/{tag}", allow=(404,))
if existing:
print(f"{tag} already exists: nothing to do.")
return
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else ""
notes = semver.changelog_section(changelog, version)
if notes is None:
sys.exit(f"CHANGELOG.md has no section for {tag}: the release pull request should have been stopped by PR CI.")
api("POST", "releases", {
"tag_name": tag,
"target_commitish": COMMIT,
"name": tag,
"body": notes,
"draft": False,
"prerelease": False,
})
print(f"Released {tag} on {COMMIT[:8]}.")
if __name__ == "__main__":
main()