So I was working on an old, crusty veteran of a git repo and I noticed it had ~300 branches on remote. This rubbed me the wrong way so I spent some time cleaning up all of those branches. Here’s what I learned:

Finding Branches

git fetch will pull down all the remote refs

git remote prune your_remote will remove any remote refs you have locally that have been removed from your remote

git branch will show all of your local branches

git branch -a will show all of your local/remote branches

git branch -a --merged will show you all of the branches that have been merged into your current branch.

git branch -a --no-merged will show you all of the branches that haven’t been merged into your current branch.

Deleting Branches

git branch -d branch_name will delete the given branch locally

git push your_remote :branch_name will delete the given branch on your remote.

Putting it together

So, deleting those excess branches might look something like:

git checkout develop
git fetch
git remote prune your_remote # Don't show branches that have already been deleted
git branch -a --merged # This will show all branches that have been merged into develop

Then, once you have your branch names to delete

git branch -d branch_name
git push your_remote :branch_name

Automating the Process

You can easily write a bash script (or ruby, or whatever) that goes through (maybe as a cron job) and deletes merged branches.

I elected not to do this for now because I have a strong aversion to the combination of ‘automatic’ and ‘hard-delete’ .

One thing to keep in mind here is that if you have a master branch and a develop branch (like in git flow) running the command git branch --merged will likely list develop from the master branch.

Keeping it clean

For the first ~290 branches I had sitting around, I copy and pasted all of the branch names into a new textmate window and used the bulk line update to prepend git push your_remote : to each line, then I ran that file as a shell script.

Moving forward, I just ensure that any time a feature branch is merged into develop I delete that branch locally and remotely. That way the repo is always nice and slim.