Because of our git workflow we end up with lots of branches in our repositories. Although these branches will not cause any harm, they do make your branch overview look cluttered when doing
git branch or viewing your repository in a visual tool like github or Codebase. Luckily, git offers some powerful tools to help you clean the mess.
Usually we clean up branches right after we’ve merged and deployed them, but sometimes you forget about that. When I was recently doing some maintenance on our repository and deleting some long forgotten branches, I came across some branches that refused to be deleted.
To get an overview of your branches you do
git branch for just your local branches,
git branch -r to see only remote branches or
git branch -a to see them both. Deleting branches then is easy, by doing
git branch -d branch_name for local branches and
git push origin :branch_name for remote branches (note the semi-colon in front of the branch name).
I ran into a branch that was in my remote branch list, but when I tried to delete it, git told me the branch actually wasn’t there anymore. Then why was it still in my remote branch list and how do I delete it from there? The solution was
git prune together with
git remote show origin.
The latter command shows a detailed status of what your local machines knows about the
origin, including so called stale branches, or branches that are in your local cache of the
origin but do not exist there anymore. Removing these stale branches is easy with
git remote prune origin (you can add the
-n flag to perform a dry-run first).
Additionally, it’s also wise to run
git gc every now and then which does just this, and more housekeeping tasks.