|
| 1 | +#!/usr/bin/env bash |
| 2 | +set -eo pipefail |
| 3 | + |
| 4 | +[[ "${CI}" ]] && [[ "${GITHUB_REPOSITORY}" ]] && [[ "${GITHUB_REF}" =~ ^refs/tags/ ]] && [[ "${RELEASES_API_KEY}" ]] || exit 1 |
| 5 | + |
| 6 | +ROOT=$(git rev-parse --show-toplevel 2>/dev/null || dirname "$(readlink -f "${0}")") |
| 7 | +FILES=("${@}") |
| 8 | + |
| 9 | +declare -A DEPS=( |
| 10 | + [curl]=curl |
| 11 | + [jq]=jq |
| 12 | +) |
| 13 | + |
| 14 | +# ---- |
| 15 | + |
| 16 | +SELF=$(basename "$(readlink -f "${0}")") |
| 17 | +log() { |
| 18 | + echo "[${SELF}] $@" |
| 19 | +} |
| 20 | +err() { |
| 21 | + log >&2 "$@" |
| 22 | + exit 1 |
| 23 | +} |
| 24 | + |
| 25 | +for dep in "${!DEPS[@]}"; do |
| 26 | + command -v "${dep}" 2>&1 >/dev/null || err "Missing dependency: ${DEPS["${dep}"]}" |
| 27 | +done |
| 28 | + |
| 29 | +[[ $# == 0 ]] && err "Missing file(s)" |
| 30 | + |
| 31 | +# ---- |
| 32 | + |
| 33 | +TAG="${GITHUB_REF/#refs\/tags\//}" |
| 34 | +CURL_OPTIONS=( |
| 35 | + -H "Accept: application/vnd.github.v3+json" |
| 36 | + -H "User-Agent: ${GITHUB_REPOSITORY}" |
| 37 | + -H "Authorization: token ${RELEASES_API_KEY}" |
| 38 | +) |
| 39 | +GH_API="https://api.github.com/repos/${GITHUB_REPOSITORY}" |
| 40 | +GH_UPLOAD="https://uploads.github.com/repos/${GITHUB_REPOSITORY}" |
| 41 | + |
| 42 | +get_release_id() { |
| 43 | + curl -fsSL \ |
| 44 | + -X GET \ |
| 45 | + "${CURL_OPTIONS[@]}" \ |
| 46 | + "${GH_API}/releases/tags/${TAG}" \ |
| 47 | + | jq -re ".id" |
| 48 | +} |
| 49 | + |
| 50 | +create_release() { |
| 51 | + curl -fsSL \ |
| 52 | + -X POST \ |
| 53 | + "${CURL_OPTIONS[@]}" \ |
| 54 | + -d "{\"tag_name\":\"${TAG}\",\"name\":\"${GITHUB_REPOSITORY} ${TAG}\",\"body\":\"\"}" \ |
| 55 | + "${GH_API}/releases" \ |
| 56 | + | jq -re ".id" |
| 57 | +} |
| 58 | + |
| 59 | +upload_assets() { |
| 60 | + local release_id="${1}" |
| 61 | + for path in "${FILES[@]}"; do |
| 62 | + local file=$(basename "${path}") |
| 63 | + log "Uploading ${file}" |
| 64 | + sha256sum "${path}" |
| 65 | + curl -fsSL \ |
| 66 | + -X POST \ |
| 67 | + "${CURL_OPTIONS[@]}" \ |
| 68 | + -H "Content-Type: application/octet-stream" \ |
| 69 | + --data-binary "@${path}" \ |
| 70 | + "${GH_UPLOAD}/releases/${release_id}/assets?name=${file}" \ |
| 71 | + >/dev/null |
| 72 | + done |
| 73 | +} |
| 74 | + |
| 75 | +deploy() { |
| 76 | + log "Getting release ID for tag ${TAG}" |
| 77 | + local release_id=$(get_release_id 2>/dev/null || true) |
| 78 | + |
| 79 | + if [[ -z "${release_id}" ]]; then |
| 80 | + log "Creating new release for tag ${TAG}" |
| 81 | + local release_id=$(create_release) |
| 82 | + fi |
| 83 | + |
| 84 | + if [[ -z "${release_id}" ]]; then |
| 85 | + err "Missing release ID" |
| 86 | + fi |
| 87 | + |
| 88 | + log "Uploading assets to release ${release_id}" |
| 89 | + upload_assets "${release_id}" |
| 90 | + |
| 91 | + log "Done" |
| 92 | +} |
| 93 | + |
| 94 | +deploy |
0 commit comments