Sunday, January 24, 2016

Cleanup Merged Github Branches

For big projects with multiple contributors where nobody is really cracking the whip on Github maintenance, there is a tendency for the branch count to just keep climbing.  I have seen cases where it tops 100 branches, and it becomes quite painful to clean up.  In cases like that, I have developed the following method for handling it:

First, you need local copies of all the remote branches.  This is not as easy as just doing a fetch origin, as that just pulls over an underlying awareness of the fact that the branches exist.  You do not actually create local copies of all those branches.

So we run the following command:

for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done

This creates local copies of all the branches including one called HEAD, which is not a real branch and is dangerous.  So let’s get rid of that by renaming it  to something else and then deleting it.

git branch -m HEAD bogusBranch
git branch –D bogusBranch

We now want to delete all the branches that are already merged.  We can get a list of them by running:

git branch --merged master | grep -v master

If we like the list, we now delete them from the origin:

git branch --merged master | grep -v master |  xargs -n 1 git push --delete origin

And we now delete the same list locally:

git branch --merged master | grep -v master |  xargs -n 1 git branch -D 

And we have now cleaned up our repository by removing everything that has already been merged to master. 

If something is not on the merged list, and we want to know what changes are not merged, we get a list of un-merged commits from that branch:

git cherry -v master <unmergedBranchName>

Now we checkout that local branch:

git checkout unmergedBranchName

And we do a whatchanged to see what the difference is:

git whatchanged -m -n 1 -p <SHA of target commit>


No comments:

Post a Comment