Skip to content

Instantly share code, notes, and snippets.

@jackson-57
Last active July 1, 2023 21:43
Show Gist options
  • Save jackson-57/4a0b34488c38fa753d4fc6e058051aa3 to your computer and use it in GitHub Desktop.
Save jackson-57/4a0b34488c38fa753d4fc6e058051aa3 to your computer and use it in GitHub Desktop.
Python script to delete all GitHub Packages for a user
# Generated by ChatGPT, with human assistance. https://chat.openai.com/share/04da796e-fff7-402f-8608-a2439027395a
import requests
def list_packages(username, token):
packages = []
page = 1
per_page = 100 # Adjust as needed, maximum is 100
while True:
# Change `package_type` to fetch types of packages other than NuGet. Also change in `delete_packages`.
url = f"https://api.github.com/users/{username}/packages?package_type=nuget&page={page}&per_page={per_page}"
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": f"Bearer {token}"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
page_packages = response.json()
if not page_packages:
break
packages.extend(page_packages)
page += 1
else:
print(f"Failed to retrieve packages. Status code: {response.status_code}")
print(response.text)
break
return packages
def delete_packages(username, token, packages):
if not packages:
return
for package in packages:
package_name = package["name"]
url = f"https://api.github.com/user/packages/nuget/{package_name}"
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": f"Bearer {token}"
}
response = requests.delete(url, headers=headers)
if response.status_code == 204:
print(f"Deleted package: {package_name}")
else:
print(f"Failed to delete package: {package_name}")
print(response.text)
# Replace with your GitHub username and personal access token
username = "your_username"
token = "your_personal_access_token"
# List all NuGet packages
packages = list_packages(username, token)
# Delete NuGet packages
delete_packages(username, token, packages)
@jackson-57
Copy link
Author

jackson-57 commented Jul 1, 2023

I had forked a repository that used GitHub Actions as a CI. Enabling and running the Actions resulted in ~300 NuGet packages being added to my account to be used as a cache for further runs. Deleting the fork did not delete the packages, and I'm unaware of an easier way to bulk delete packages.

I used ChatGPT as an experiment, to see if asking it to write a script for me was quicker than writing it myself. It took me around 30 minutes to get the script working, which I suspect is around the same amount of time it would have taken me to do it myself. I still think it's an interesting outcome, nevertheless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment