Tuesday, March 23, 2021

Remove git orphan branches for *nix based OS.

I've already posted how to remove orphan branches if you develop on windows. This post is just a small addition but for those who develops on *nix based OSes. 

The problem is very simple, you develop something, you push it, you get your branch merged, then you need manually remove local branches. It can be easily automated, first we need to run

git branch -vv

and then remove all branches that have no remote branches.

git branch -D branch_name

It's possible to write a simple bash script that checks git branches and then just removes ones that no longer have remote branches. I'm not a huge fan os bash so I decided to go with python. It's more convenient, predictable and easier to use. Bellow is the script itself.

#!/usr/bin/env python
import subprocess

cmd_output = subprocess.check_output('git branch -vv', shell=True)

output_lines = cmd_output.split('\n')

to_remove = []

for line in output_lines:
    if line.startswith('*'): # skip current branch
        continue

    if 'gone' in line: # there is no remote branch
        line_segments = line.strip().split(' ')
        branch = line_segments[0]
        to_remove.append(branch)

if not to_remove:
    print('There is nothing to remove, consider running `git fetch` and `git remote prune origin`')

for branch in to_remove:
    subprocess.call('git branch -D ' + branch, shell=True)

Let's save this file as git-clean. Of cause you can use whatever name your want, but then please adjust the instructions bellow. 

In order to make it more convenient to use let's make it executable by running 

chmod +x git-clean

and add this executable to the PATH variable. Simply go to your home folder and find there the .bash_profile. Open it and add the path to the folder where your git-clean is located. In my case it's ~/projects/tools.

export PATH="~/projects/tools:$PATH"

Now restart your terminal and  git-clean should be globally available.

P.S. this script uses python 2.x. and with python 3.x is should be possible to achieve the same result easier.