upload_github_release_asset.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env bash
  2. #
  3. # Author: Stefan Buck
  4. # License: MIT
  5. # https://gist.github.com/stefanbuck/ce788fee19ab6eb0b4447a85fc99f447
  6. #
  7. #
  8. # This script accepts the following parameters:
  9. #
  10. # * owner
  11. # * repo
  12. # * tag
  13. # * filename
  14. # * github_api_token
  15. #
  16. # Script to upload a release asset using the GitHub API v3.
  17. #
  18. # Example:
  19. #
  20. # upload-github-release-asset.sh github_api_token=TOKEN owner=stefanbuck repo=playground tag=v0.1.0 filename=./build.zip
  21. #
  22. # Check dependencies.
  23. set -e
  24. xargs=$(which gxargs || which xargs)
  25. # Validate settings.
  26. [ "$TRACE" ] && set -x
  27. CONFIG=$@
  28. for line in $CONFIG; do
  29. eval "$line"
  30. done
  31. # Define variables.
  32. GH_API="https://api.github.com"
  33. GH_REPO="$GH_API/repos/$owner/$repo"
  34. GH_TAGS="$GH_REPO/releases/tags/$tag"
  35. AUTH="Authorization: token $github_api_token"
  36. WGET_ARGS="--content-disposition --auth-no-challenge --no-cookie"
  37. CURL_ARGS="-LJO#"
  38. if [[ "$tag" == 'LATEST' ]]; then
  39. GH_TAGS="$GH_REPO/releases/latest"
  40. fi
  41. # Validate token.
  42. curl -o /dev/null -sH "$AUTH" $GH_REPO || { echo "Error: Invalid repo, token or network issue!"; exit 1; }
  43. # Read asset tags.
  44. response=$(curl -sH "$AUTH" $GH_TAGS)
  45. # Get ID of the asset based on given filename.
  46. eval $(echo "$response" | grep -m 1 "id.:" | grep -w id | tr : = | tr -cd '[[:alnum:]]=')
  47. [ "$id" ] || { echo "Error: Failed to get release id for tag: $tag"; echo "$response" | awk 'length($0)<100' >&2; exit 1; }
  48. # Upload asset
  49. echo "Uploading asset... "
  50. # Construct url
  51. GH_ASSET="https://uploads.github.com/repos/$owner/$repo/releases/$id/assets?name=$(basename $filename)"
  52. curl "$GITHUB_OAUTH_BASIC" --data-binary @"$filename" -H "Authorization: token $github_api_token" -H "Content-Type: application/octet-stream" $GH_ASSET