#!/bin/sh # Attach one file to the release for $TAG, creating the release if needed. # # release-asset.sh [asset-name] # # Idempotent: a re-run replaces the asset, and jobs racing to create the same # release converge. Env: FORGEJO_API_URL, FORGEJO_TOKEN, REPO, TAG. set -eu api="${FORGEJO_API_URL:?FORGEJO_API_URL is not set}" repo="${REPO:?REPO is not set}" tag="${TAG:?TAG is not set}" token="${FORGEJO_TOKEN:?FORGEJO_TOKEN is not set}" case "$api" in http*) ;; *) # An unexpanded github.server_url leaves a bare "/api/v1"; fail loudly. echo "release-asset: FORGEJO_API_URL is not a URL: '$api'" >&2 echo " set github.server_url support or override the env var" >&2 exit 1 ;; esac file="$1" name="${2:-$(basename "$file")}" [ -f "$file" ] || { echo "release-asset: no such file: $file" >&2; exit 1; } auth="Authorization: token $token" get_rid() { curl -fsS -H "$auth" "$api/repos/$repo/releases/tags/$tag" | jq -r '.id // empty' } rid="$(get_rid || true)" if [ -z "$rid" ]; then echo "release-asset: creating release $tag" curl -sS -o /dev/null -H "$auth" -H 'Content-Type: application/json' \ -X POST "$api/repos/$repo/releases" \ --data "$(jq -nc --arg t "$tag" '{tag_name: $t, name: $t}')" || true # A parallel job may have created it between our GET and POST. i=0 while [ -z "$rid" ] && [ "$i" -lt 5 ]; do sleep 1 rid="$(get_rid || true)" i=$((i + 1)) done fi [ -n "$rid" ] || { echo "release-asset: cannot resolve release for $tag" >&2; exit 1; } # Replace a same-named asset so a re-run does not accumulate duplicates. old="$(curl -fsS -H "$auth" "$api/repos/$repo/releases/$rid/assets" \ | jq -r --arg n "$name" '.[] | select(.name == $n) | .id' | head -1)" if [ -n "$old" ]; then echo "release-asset: replacing existing asset $name" curl -fsS -o /dev/null -H "$auth" \ -X DELETE "$api/repos/$repo/releases/$rid/assets/$old" fi curl -fsS -H "$auth" -X POST \ "$api/repos/$repo/releases/$rid/assets?name=$name" \ -F "attachment=@$file" >/dev/null echo "release-asset: uploaded $name to $tag"