Files
linux-backuper/packaging/publish_release.py
T
soda64 d18db76441
Build and Publish Release / test-and-release (push) Successful in 42s
fix(ci): delegate Gitea release asset publishing to standalone python script
2026-10-09 20:30:00 +02:00

117 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Helper script to create Gitea release and upload package assets.
Uses only Python standard library (urllib, json, os, sys).
"""
import json
import os
import sys
import urllib.error
import urllib.request
def make_request(url: str, method: str = "GET", data: bytes = None, headers: dict = None):
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
try:
with urllib.request.urlopen(req) as resp:
content = resp.read()
return resp.status, content
except urllib.error.HTTPError as e:
return e.code, e.read()
def main():
server_url = os.environ.get("GITHUB_SERVER_URL", "").rstrip("/")
owner = os.environ.get("GITHUB_REPOSITORY_OWNER", "")
repo = os.environ.get("GITHUB_REPOSITORY", "").split("/")[-1]
token = os.environ.get("GITEA_TOKEN", "")
ref = os.environ.get("GITHUB_REF", "")
if not ref.startswith("refs/tags/v"):
print(f"[INFO] Ref '{ref}' is not a release tag (refs/tags/v*). Skipping release publishing.")
return 0
tag_name = ref.replace("refs/tags/", "")
api_url = f"{server_url}/api/v1/repos/{owner}/{repo}"
auth_headers = {"Authorization": f"token {token}"}
print(f"[INFO] Publishing release for tag '{tag_name}' to {api_url}")
# 1. Get or create release
status, body = make_request(f"{api_url}/releases/tags/{tag_name}", headers=auth_headers)
rel_id = None
if status == 200:
data = json.loads(body.decode("utf-8"))
rel_id = data.get("id")
print(f"[INFO] Existing release found (ID: {rel_id})")
else:
print(f"[INFO] Creating new release for tag {tag_name}...")
payload = json.dumps({
"tag_name": tag_name,
"name": f"linux-backuper {tag_name}",
"body": f"Automated release of linux-backuper {tag_name}.\n\nArtifacts:\n- Native Debian package (.deb)\n- Native Red Hat / Fedora package (.rpm)\n- Universal standalone archive (.tar.gz)",
"draft": False,
"prerelease": False,
}).encode("utf-8")
headers = dict(auth_headers)
headers["Content-Type"] = "application/json"
status, body = make_request(f"{api_url}/releases", method="POST", data=payload, headers=headers)
if status in (200, 201):
data = json.loads(body.decode("utf-8"))
rel_id = data.get("id")
print(f"[SUCCESS] Created release (ID: {rel_id})")
else:
print(f"[ERROR] Failed to create release: HTTP {status} - {body.decode('utf-8', errors='replace')}", file=sys.stderr)
return 1
# 2. Get existing assets
status, body = make_request(f"{api_url}/releases/{rel_id}/assets", headers=auth_headers)
existing_assets = {}
if status == 200:
for a in json.loads(body.decode("utf-8")):
existing_assets[a.get("name")] = a.get("id")
# 3. Upload assets from dist directory
dist_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "dist")
if not os.path.isdir(dist_dir):
print(f"[ERROR] Dist directory not found at {dist_dir}", file=sys.stderr)
return 1
asset_files = [f for f in os.listdir(dist_dir) if f.endswith((".tar.gz", ".deb", ".rpm")) and not f.startswith(".")]
for fname in sorted(asset_files):
fpath = os.path.join(dist_dir, fname)
if not os.path.isfile(fpath):
continue
# If asset exists, delete old one first
if fname in existing_assets:
asset_id = existing_assets[fname]
print(f"[INFO] Deleting existing asset {fname} (ID: {asset_id})...")
make_request(f"{api_url}/releases/{rel_id}/assets/{asset_id}", method="DELETE", headers=auth_headers)
print(f"[INFO] Uploading asset: {fname} ({os.path.getsize(fpath)} bytes)...")
with open(fpath, "rb") as f:
data = f.read()
headers = dict(auth_headers)
headers["Content-Type"] = "application/octet-stream"
status, body = make_request(
f"{api_url}/releases/{rel_id}/assets?name={fname}",
method="POST",
data=data,
headers=headers
)
if status in (200, 201):
print(f"[SUCCESS] Uploaded {fname}")
else:
print(f"[ERROR] Failed to upload {fname}: HTTP {status} - {body.decode('utf-8', errors='replace')}", file=sys.stderr)
return 1
print("[SUCCESS] All release assets uploaded successfully.")
return 0
if __name__ == "__main__":
sys.exit(main())