What

When you are sending multiple packages to GitHub for your project and you don’t need the older ones, here is how to delete the extras. This can also be used to run any kind of script from a Linux cron job on a regular basis so you can focus on the work rather than maintaining the packages.

How

To do this you need the github auth token which has access to the github packages edit rights. and a linux system.

Script

Create the script in your system. /projects/cron/clean_packages.sh.

the code for the script is

#!/bin/sh

# Execute the curl command to get AtlPay Contracts
output=$(curl --location "https://api.github.com/graphql" \
  --header "Content-Type: application/json" \
  --header "Authorization: Bearer <<YOUR KEY HERE>>" \
  --data "{\"query\":\"query { repository(owner:\\\"owner-name\\\",name:\\\"Project-name\\\"){packages(first:100){nodes{packageType,name,id,versions(first:100){nodes{id,version,readme}}}}}}\",\"variables\":{}}")

# Check if the curl command was successful
if [ $? -ne 0 ]; then
    echo "Error executing curl command to get packages: $output"
    exit 1
fi

# Extract the IDs of the versions to delete, skipping the first one
idsToDeletePackages=$(echo "$output" | jq -r '.data.repository.packages.nodes[0].versions.nodes[1:][] | .id')

# Loop over the IDs and delete each one
for idToDelete in $idsToDeletePackages
do
    output=$(curl --location "https://api.github.com/graphql" \
      --header "Accept: application/vnd.github.package-deletes-preview+json" \
      --header "Content-Type: application/json" \
      --header "Authorization: Bearer <<YOUR KEY HERE>>" \
      --data "{\"query\":\"mutation{deletePackageVersion(input:{packageVersionId:\\\"$idToDelete\\\"}){success}}\",\"variables\":{}}")

    if [ $? -ne 0 ]; then
        echo "Error executing curl command to delete version with ID $idToDelete: $output"
    else
        echo "Successfully deleted version with ID $idToDelete"
    fi
done

In the script above, replace YOUR KEY HERE with your GitHub token, owner-name with the GitHub repo owner username, and Project-name with the project name you want to clean.

This will delete all the previous packages except for the latest one.

Permissions

Once the scripts are done change the permission so that this can be executed.

chmod +x clean_packages.sh

Cron Registration

To add this to cron, open crontab in edit mode

crontab -e

add the script to the crontab

0 11 * * * /bin/bash /projects/cron/clean_packages.sh

this cron will run every 11 AM server time.

to verify if this is done.

crontab -l

You should now see the registered cronjob on the terminal.