soft-fork-tools/api.sh

88 lines
2.1 KiB
Bash

#!/usr/bin/env bash
: ${FORGEJO_SCHEME:=https}
: ${FORGEJO_INSTANCE:=codeberg.org}
: ${OWNER:=dachary}
: ${NAME:=forgejo}
: ${REPO:=$OWNER/$NAME}
function api_check_token() {
if test -z "$FORGEJO_TOKEN"; then
echo "Missing FORGEJO_TOKEN environment variable"
return 1
fi
}
function api() {
local method=$1
shift
local path=$1
shift
local dry_run=$DRY_RUN
if test "$method" = "GET"; then
dry_run=
fi
api_check_token
$dry_run curl --fail -X $method -sS -H "Content-Type: application/json" -H "Authorization: token $FORGEJO_TOKEN" "$@" $FORGEJO_SCHEME://$FORGEJO_INSTANCE/api/v1/$path
}
function _api_pr_info() {
local base=$1
shift
local head=$1
shift
curl -H "Content-Type: application/json" -H "Authorization: token $FORGEJO_TOKEN" -s "$@" $FORGEJO_SCHEME://$FORGEJO_INSTANCE/api/v1/repos/$REPO/pulls --data-raw '{"base":"'$base'","head":"'$head'","title":"fake","milestone":1000000}'
}
function api_pr_exists() {
local base=$1
local head=$2
test "$(_api_pr_info $base $head -o /dev/null -w "%{http_code}\n")" = 409
}
function api_pr_id() {
local base=$1
local head=$2
_api_pr_info $base $head | sed -Ee 's/.*issue_id: ([0-9]+).*/\1/'
}
function api_pr_close() {
local id=$1
if test "$(api_pr_get $id | jq --raw-output .state)" = "open"; then
api PATCH repos/$REPO/pulls/$id --data-raw '{"state":"closed"}'
fi
}
function api_pr_get() {
local id=$1
api GET repos/$REPO/pulls/$id
}
function api_pr_create() {
local base=$1
local head=$2
local title=$3
local body=$4
if ! api_pr_exists $base $head ; then
api POST repos/$REPO/pulls --data-raw '{"base":"'$base'","head":"'$head'","title": "'"$title"'","body":"'"$body"'"}'
fi
}
function api_check_status() {
local sha=$1
api GET repos/$REPO/commits/$sha/status | jq --raw-output .state
}
function api_set_status() {
local sha=$1
local state=$2
api POST repos/$REPO/statuses/$sha --data-raw '{"state": "'$state'", "context": "Soft fork tool", "description": "Rebase", "target_url": "https://codeberg.org/forgejo-contrib/soft-fork-tools"}'
}