It was time to clean up some old git branches at TaskRabbit today. It turned out that we had hundreds of branches that were “old,” and could be removed. What do I mean by old? As with many things, coming up with the proper definition is half the battle. At the end of the day, old means: “I have been merged into master, and contain no un-merged code” (where master is your integration branch).
When phrased this way, there are some systematic and simple ways to due some git pruning. Here’s a simple rake task:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
The trick here is
git fetch -r –merged command which does exactly what we want: tell me about the remote branches which have all been merged into my current branch, master. We simply collect those branches, and delete them locally (if they exist) and on origin.
The logic goes like this:
- Ensure I am in the master branch
- git fetch –prune (clean up my local branch list according to remote’s list)
- git fetch -r –merged (show me the branches which have been merged into the integration branch)
- loop through those branches and delete them locally and remotely
Two other points of note:
- It’s very likely that you will have some staging, test, and production branches which are either equivalent to or slightly behind your integration branch. You probably want to explicitly ignore those.
- If you have more than one remote branch setup (perhaps heroku for deployment or tddium for testing), you want to be sure to ignore any branch which isn’t from “origin.”