How to delete many Git repositories at once?

Brice Fotzo
3 min readApr 4, 2021
Pop-up to confirm repository deletion

Have you ever wanted to delete a Git repository? This process is easy, but not user friendly, especially if you want to delete many repositories. Perhaps you faced this situation because you often fork repositories for training or research work, or even just because you have many unused repositories.

Personally, I was in the second case and I solved my problem using Python and the Github API . I would like to share my little process, hoping it can help someone.

Before starting:

Once you get python and a token, you can start coding. You can find the entire code here. We’ll follow 2 steps:

  • List the repositories
  • Delete the repositories we want to get rid of

List the repositories

Let’s use the methods list repositories for the authenticated user. I created the function get_repos which takes 3 input parameters(github api url, your username, your token) and return the list of repositories. The 3rd parameter is the token that we generated previously.

The function get_repos to list repositories

We’ve used the requests package to call the github API method. We pass the api url and the authentication parameters to resquets.get.

Delete the repositories we want to get rid of

Let’s delete the repositories we want to get rid of using repos_dict.

We are going to use this dictionary to select the repos to delete. We use the requests.delete method where the inputs are the API url (https://api.github.com/repos/{username}/{repo_name}) and the authentication parameters. As those parameters are sensitive/private, I stored them into environment variables. In fact, in my local repository, I have a .env which is in the .gitgnore file so that it won’t be displayed on my Github public repository.

In the .env file I declared my authentication parameters GITHUB_USER(my username) and GITHUB_TOKEN (my personal access token). I also set the github API url as GITHUB_API as I use it many times in the process. I load those variable using load_dotenv().

Running delete.py, here is what happens.

CLI execution of the file delete.py
  • The repositories are listed.
  • A prompt request you to type the ids of repositories you want to delete.
  • Once repositories are deleted we list them to check that the deletion is done.

Conclusion

I hope this little tutorial will help you if you want to delete many github repositories at once. Don’t hesitate to fork or download the whole code through this link. I automated other github operations like create repository on github from CLI or even add, commit and push files in one action. I could post more content like this if it is helpful so please let me know if you’re interested.

--

--