Files
FinalToken/tools/gitea.sh
T
2026-10-14 18:43:27 +02:00

83 lines
2.8 KiB
Bash
Executable File

#!/usr/bin/env bash
# Usage: tools/gitea.sh <METHOD> <path under /api/v1> [body file | -]
set -euo pipefail
# Credentials must never appear in shell traces, even when called with bash -x.
set +x
usage() { echo 'Usage: tools/gitea.sh <METHOD> <path under /api/v1> [body file | -]' >&2; exit 2; }
[[ $# -ge 2 && $# -le 3 ]] || usage
method=$1 path=$2
[[ $method =~ ^[A-Z]+$ && $path == /* && $path != //* && $path != *$'\n'* && $path != *$'\r'* ]] || usage
scratch=$(mktemp -d)
trap 'rm -rf -- "$scratch"' EXIT
body=''
if [[ $# == 3 ]]; then
if [[ $3 == - ]]; then
cat > "$scratch/body"
body=$scratch/body
else
[[ -f $3 && -r $3 ]] || { echo "Body file '$3' is not readable" >&2; exit 2; }
body=$3
fi
fi
# Quote curl config values, including credentials containing quotes or backslashes.
config_quote() {
local value=$1
value=${value//\\/\\\\}
value=${value//\"/\\\"}
value=${value//$'\n'/\\n}
value=${value//$'\r'/\\r}
value=${value//$'\t'/\\t}
printf '"%s"' "$value"
}
if [[ -n ${GITEA_TOKEN:-} ]]; then
auth_key=header
auth_value="Authorization: token $GITEA_TOKEN"
else
credential=$(printf 'protocol=https\nhost=git.finalfactory.de\n\n' | GIT_TERMINAL_PROMPT=0 git credential fill) || {
echo 'No stored Gitea credential; set GITEA_TOKEN or configure a git credential helper' >&2
exit 1
}
username='' password=''
while IFS= read -r entry; do
case $entry in
username=*) username=${entry#username=} ;;
password=*) password=${entry#password=} ;;
esac
done <<< "$credential"
[[ -n $username && -n $password ]] || { echo 'Stored Gitea credential has no username or password' >&2; exit 1; }
auth_key=user
auth_value="$username:$password"
unset credential username password
fi
# Native Windows curl needs native paths when paths are supplied inside its config.
response=$scratch/response
if command -v cygpath >/dev/null 2>&1; then
response=$(cygpath -m "$response")
if [[ -n $body ]]; then body=$(cygpath -m "$body"); fi
fi
curl_config() {
printf '%s = ' "$auth_key"; config_quote "$auth_value"; printf '\n'
printf 'request = '; config_quote "$method"; printf '\n'
printf 'url = '; config_quote "https://git.finalfactory.de/api/v1$path"; printf '\n'
printf 'output = '; config_quote "$response"; printf '\n'
printf 'header = "Accept: application/json"\n'
if [[ -n $body ]]; then
printf 'header = "Content-Type: application/json"\n'
printf 'data-binary = '; config_quote "@$body"; printf '\n'
fi
}
status=$(curl_config | curl -q --silent --show-error --connect-timeout 15 --max-time 120 --write-out '%{http_code}' -K -) || {
echo 'Gitea request failed before receiving a successful response' >&2
exit 1
}
if [[ $status != 2?? ]]; then
echo "Gitea HTTP $status for $method $path" >&2
exit 1
fi
cat "$scratch/response"