Tuesday, September 3, 2019

Remove git orphan branches

Quite often especially when you create a pull request for some short time you have a local branch and a corresponding remote one that you track. But after your pull request is merged and remote branch is removed you still have your local branch.

If you run command

git remote prune origin

It will check if branches that you track are still there, if not  then your local branches are orphans now.

If you run now

git branch -vv

Then you will get a nice info about each branch


Here we can see that branch_a is gone, git literally says it. This is our orphan branch. No we can run the following command to remove it.

git branch -D branch_a

But what if we have 5 or 10 branches that became orphans? It would be nice to have some helper function that automates this process.

If your working environment is windows you can easily add a helper function into your powershell profile. Just go to powershell console and run

notepad $profile

And add the code bellow at the end of your powershell profile.

function git-clean() {
 git branch -vv | Where {$_.Contains("gone")} | ForEach -Process { git branch -D $_.Split()[2] }
}

Now every time you open a powershell console it will scan your profile and import all functions declared there. Now you can simply run git-clean and it will do all magic.

As summary just run


git remote prune origin
git-clean

P.S. if you have just added this function you need first to restart you powershell console to make this function available.