(Inspired by https://medium.com/@icanhazedit/clean-up-unused-github-rpositories-c2549294ee45#.3hwv4nxv5 and https://gist.github.com/mrkpatchaa/63720cbf744a2bf59a3e9cfe73fc33b0) and a little help from ChatGPT.
with additional notes from me
- Open in a new tab all to-be-deleted github repositores (Use the mouse’s middle click or Ctrl + Click) https://github.com/username?tab=repositories
Note: in Chrome, you can group them all to make it a little easier
-
Use one tab https://chrome.google.com/webstore/detail/onetab/chphlpgkkbolifaimnlloiipkdnihall to shorten them to a list.
-
Save that list to some path
-
The list should be in the form of “ur_username\repo_name” per line.Use regex search (Sublime text could help). Search for\|.*
and replace by empty.
Notes:
List is actually in https://github.com/USERNAME/REPO format
If you use VS Code, use
\| (.+)
as your find string, be sure to turn on the regular expressions button (the one with the asterisk, or Alt-R)
-
Register a new personal access token with a 'delete_repo perm' https://github.com/settings/tokens/new
-
Copy the access_token and run the following line replacing xxx with your access token.
Copy-paste the following script into a .ps1
file, run it in powershell with ./scriptname.ps1
# Set your GitHub token, file path and username
# Generate token with delete_repo scope - https://github.com/settings/tokens/new
$token = "<personal access token with delete_repo scope>"
$filePath = "<path to text file>"
$errored = $False # to check if it worked, there is probably a better way to do this
# Read the file and iterate through each line
Get-Content $filePath | ForEach-Object {
$sourceUrl = $_
# Insert "api." before "github.com" and "repos" after it
$url = $sourceUrl -replace "https://github.com/", "https://api.github.com/repos/"
# Create custom headers
$headers = @{
"Accept" = "application/vnd.github+json"
"Authorization" = "Bearer $token"
"X-GitHub-Api-Version" = "2022-11-28"
}
try {
# Send the API call with Invoke-RestMethod
Invoke-RestMethod -Uri $url -Method Delete -Headers $headers
}
catch {
$errored = $True #stops success message if something went wrong
Write-Host "Failed to delete repository $url."
Write-Host "Exception Message: $($_.Exception.Message)"
if ($_.Exception.Response) {
$errorResponse = $_.Exception.Response.GetResponseStream()
$reader = [System.IO.StreamReader]::new($errorResponse)
$errorContent = $reader.ReadToEnd()
Write-Host "Response Content: $errorContent"
}
}
finally {
if ($errored -eq $False) {
Write-Host "Deleted repository at $sourceUrl"
}
}
}