From d18db76441293df64eb9a7542d430b19ff75c710 Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Fri, 9 Oct 2026 20:30:00 +0200 Subject: [PATCH] fix(ci): delegate Gitea release asset publishing to standalone python script --- .gitea/workflows/release.yml | 70 ++------------------- packaging/publish_release.py | 116 +++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 66 deletions(-) create mode 100644 packaging/publish_release.py diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index b438aff..38d1650 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -40,16 +40,6 @@ jobs: echo "[INFO] Building .tar.gz, .deb, and .rpm distribution packages..." rm -rf dist python3 packaging/build_packages.py --all --out-dir dist - - TAR_FILE=$(find dist -maxdepth 1 -name "*.tar.gz" | head -n 1) - DEB_FILE=$(find dist -maxdepth 1 -name "*.deb" | head -n 1) - RPM_FILE=$(find dist -maxdepth 1 -name "*.rpm" | head -n 1) - - echo "TAR_FILE=$TAR_FILE" >> $GITHUB_ENV - echo "DEB_FILE=$DEB_FILE" >> $GITHUB_ENV - echo "RPM_FILE=$RPM_FILE" >> $GITHUB_ENV - - echo "[INFO] Generated packages:" ls -lh dist/ - name: Publish to Gitea Package Registry @@ -61,26 +51,25 @@ jobs: REPO="${{ github.event.repository.name }}" SERVER="${{ github.server_url }}" - # Upload RPM + RPM_FILE=$(find dist -maxdepth 1 -name "*.rpm" | head -n 1) + DEB_FILE=$(find dist -maxdepth 1 -name "*.deb" | head -n 1) + if [[ -f "$RPM_FILE" ]]; then echo "[INFO] Publishing RPM to registry..." curl -k -s -f -X PUT -u "${{ github.actor }}:${PKG_TOKEN}" \ --upload-file "$RPM_FILE" \ "${SERVER}/api/packages/${OWNER}/rpm/upload" || echo "[WARNING] RPM upload returned non-zero (may already exist)" - # Link package to repository curl -k -s -X POST -H "Authorization: token ${PKG_TOKEN}" \ "${SERVER}/api/v1/packages/${OWNER}/rpm/linux-backuper/-/link/${REPO}" || true fi - # Upload Debian if [[ -f "$DEB_FILE" ]]; then echo "[INFO] Publishing Debian to registry..." curl -k -s -f -X PUT -u "${{ github.actor }}:${PKG_TOKEN}" \ --upload-file "$DEB_FILE" \ "${SERVER}/api/packages/${OWNER}/debian/pool/stable/main/upload" || echo "[WARNING] DEB upload returned non-zero (may already exist)" - # Link package to repository curl -k -s -X POST -H "Authorization: token ${PKG_TOKEN}" \ "${SERVER}/api/v1/packages/${OWNER}/debian/linux-backuper/-/link/${REPO}" || true fi @@ -90,55 +79,4 @@ jobs: env: GITEA_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }} run: | - TAG_NAME="${GITHUB_REF#refs/tags/}" - OWNER="${{ github.repository_owner }}" - REPO="${{ github.event.repository.name }}" - API_URL="${{ github.server_url }}/api/v1/repos/${OWNER}/${REPO}" - - echo "[INFO] Ensuring Gitea Release exists for tag ${TAG_NAME}..." - REL_INFO=$(curl -k -s -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/tags/${TAG_NAME}") - REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$REL_INFO" 2>/dev/null || true) - - if [[ -z "$REL_ID" || "$REL_ID" == "null" ]]; then - echo "[INFO] Creating release for tag ${TAG_NAME}..." - CREATE_PAYLOAD=$(cat </dev/null || true) - fi - - echo "[INFO] Release ID: ${REL_ID}" - - # Idempotently upload assets - for FPATH in "$TAR_FILE" "$DEB_FILE" "$RPM_FILE"; do - if [[ -f "$FPATH" ]]; then - FNAME=$(basename "$FPATH") - echo "[INFO] Uploading asset: ${FNAME}..." - - # Delete existing asset with same name if present - EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/${REL_ID}/assets" || echo "[]") - ASSET_ID=$(python3 -c "import sys, json; assets=json.loads(sys.argv[1]) if sys.argv[1] else []; fname=sys.argv[2]; print(next((str(a['id']) for a in assets if isinstance(a, dict) and a.get('name') == fname), ''))" "$EXISTING_ASSETS" "$FNAME" 2>/dev/null || true) - if [[ -n "$ASSET_ID" ]]; then - echo "[INFO] Deleting existing asset ${FNAME} (ID: ${ASSET_ID})..." - curl -k -s -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/${REL_ID}/assets/${ASSET_ID}" || true - fi - - # Upload asset - curl -k -s -X POST -H "Authorization: token ${GITEA_TOKEN}" \ - -H "Content-Type: application/octet-stream" \ - --data-binary @"$FPATH" \ - "${API_URL}/releases/${REL_ID}/assets?name=${FNAME}" - fi - done - echo "[SUCCESS] Release publishing complete." + python3 packaging/publish_release.py diff --git a/packaging/publish_release.py b/packaging/publish_release.py new file mode 100644 index 0000000..ce2c790 --- /dev/null +++ b/packaging/publish_release.py @@ -0,0 +1,116 @@ +#!/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())