Jenkins/resources/com/cadoles/gitea/gitea-package-delete.sh

124 lines
3.2 KiB
Bash
Executable File

#!/bin/bash
set -eo pipefail
GITEA_PACKAGE_ORG=${GITEA_PACKAGE_ORG}
GITEA_PACKAGE_BASE_URL=${GITEA_BASE_URL:-https://forge.cadoles.com}
GITEA_PACKAGE_USERNAME=${GITEA_PACKAGE_USERNAME}
GITEA_PACKAGE_PASSWORD=${GITEA_PACKAGE_PASSWORD}
GITEA_PACKAGE_CURL_MAX_RETRY=${GITEA_PACKAGE_CURL_MAX_RETRY:-3}
GITEA_PACKAGE_NAME_FILTER=${GITEA_PACKAGE_NAME_FILTER}
GITEA_PACKAGE_TYPE_FILTER=${GITEA_PACKAGE_TYPE_FILTER}
function check_dependencies {
assert_command_available 'curl'
assert_command_available 'jq'
}
function assert_command_available {
local command=$1
local command_path=$(which $command)
if [ -z "$command_path" ]; then
echo "The '$command' command could not be found. Please install it before using this script." 1>&2
exit 1
fi
}
function check_environment {
assert_environment GITEA_PACKAGE_ORG
assert_environment GITEA_PACKAGE_BASE_URL
}
function source_env_file {
if [ ! -f '.env' ]; then
return 0
fi
set -o allexport
source .env
set +o allexport
}
function assert_environment {
local name=$1
local value=${!name}
if [ -z "$value" ]; then
echo "The $"$name" environment variable is empty." 1>&2
exit 1
fi
}
function ask_credentials {
if [ -z "$GITEA_PACKAGE_USERNAME" ]; then
echo -n "Username: "
read GITEA_PACKAGE_USERNAME
fi
if [ -z "$GITEA_PACKAGE_PASSWORD" ]; then
echo -n "Password: "
stty -echo
read GITEA_PACKAGE_PASSWORD
stty echo
echo
fi
}
function gitea_api {
local path=$1
local args=${@:2}
curl -L \
--fail \
--ipv4 \
--progress-bar \
--retry "$GITEA_PACKAGE_CURL_MAX_RETRY" \
-u "$GITEA_PACKAGE_USERNAME:$GITEA_PACKAGE_PASSWORD" \
$GITEA_PACKAGE_CURL_ARGS \
${args} \
"$GITEA_PACKAGE_BASE_URL$path"
}
function delete_packages {
local page=1
local limit=100
while true; do
local result=$(gitea_api "/api/v1/packages/$GITEA_PACKAGE_ORG?page=$page&limit=$limit&type=all" -X GET -H 'accept:application/json')
local total_items=$(echo $result | jq -r '. | length')
for (( i = 0; i < $total_items; i++ )); do
local item=$(echo $result | jq --argjson index $i '.[$index]')
local package_name=$(echo $item | jq -r '.name')
local package_version=$(echo $item | jq -r '.version')
local package_type=$(echo $item | jq -r '.type')
if [ ! -z "$GITEA_PACKAGE_TYPE_FILTER" ]; then
[[ "$package_type" =~ $GITEA_PACKAGE_TYPE_FILTER ]] || continue
fi
if [ ! -z "$GITEA_PACKAGE_NAME_FILTER" ]; then
[[ "$package_name" =~ $GITEA_PACKAGE_NAME_FILTER ]] || continue
fi
echo "Deleting package $package_name (version: $package_version, type: $package_type)..."
gitea_api "/api/v1/packages/$GITEA_PACKAGE_ORG/$package_type/$package_name/$package_version" -X DELETE
done
if [[ "$total_items" == "0" ]]; then
break
fi
page=$(( $page + 1 ))
done
}
function main {
check_dependencies
source_env_file
check_environment
ask_credentials
delete_packages
}
main