Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aviflax/c7757a651682f2acb61fb682ac49eed4 to your computer and use it in GitHub Desktop.
Save aviflax/c7757a651682f2acb61fb682ac49eed4 to your computer and use it in GitHub Desktop.
Script to delete matching NuGet packages from an organization’s GitHub Packages repository

Prerequisites

  • gh installed
  • gh authenticated with gh auth login --scopes write:packages,delete:packages
    • If you already have gh installed and authenticated you can use refresh instead of login
#!/bin/bash
# This is a lightly modified version of the original source:
# https://skarlso.github.io/2024/12/10/quickly-delete-all-packages-from-github-registry/
set -e
# Variables
OWNER=$1 # Replace with your GitHub username or organization name
PACKAGE_TYPE=$2 # Must be one of: npm, maven, rubygems, docker, nuget, container
PACKAGE_GLOB=$3 # Glob pattern for package names passed as an argument (e.g., "package*" to match all)
# makes sure that important packages are not removed by accident
contains() {
found=1
array=(place-very-important-packages-here-to-make-sure-they-are-not-deleted)
for v in "${array[@]}"
do
if [[ "$1" == "$v" ]]; then
echo "$v found not deleting"
found=0
break
fi
done
}
# Function to delete a package version
delete_package_version() {
contains "$1"
# echo "found: $found"
if [[ $found -eq 1 ]]; then
name=${1//\//%2F}
echo "deleting package with name: $name"
gh api -X DELETE "/orgs/$OWNER/packages/$PACKAGE_TYPE/$name" --silent
fi
}
# Fetch the list of all available packages for the user/organization
echo "Fetching packages matching the glob pattern '$PACKAGE_GLOB'..."
# Fetch all package names and filter with globbing
# Change `/users/` to `organization` if you are looking at organization packages.
ALL_PACKAGES=$(gh api "/users/$OWNER/packages?package_type=$PACKAGE_TYPE" --jq '.[].name' --paginate)
MATCHED_PACKAGES=$(echo "$ALL_PACKAGES" | grep "$PACKAGE_GLOB")
if [[ -z "$MATCHED_PACKAGES" ]]; then
echo "No packages found matching the pattern '$PACKAGE_GLOB'."
exit 1
fi
echo "Deleting the following packages: ${MATCHED_PACKAGES}"
# Loop through matched packages and delete them
SAVEIFS=$IFS # Save current IFS (Internal Field Separator)
IFS=$'\n' # Change IFS to newline char
packages=($MATCHED_PACKAGES) # split the `names` string into an array by the same name
IFS=$SAVEIFS # Restore original IFS
for (( i=0; i<${#packages[@]}; i++ ))
do
delete_package_version "${packages[$i]}"
done
echo "All matching packages deleted!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment