Friday, March 18, 2016

Remove git branches locally after they have been removed from the remote repository

In the workflow we have at work, which is pretty common actually, a new branch is created for a bug fix, a new feature, etc.
This then allows to create a "pull request", that is, asking for the contents of the branch to be merged back into the master branch. After this has been done, the original branch is removed.

However, if you happened to have it in your local Git repository, it won't be deleted. And after a few months, you are going to have a lot of clutter there, that is, branches you will never use again.

Here is a script that deletes local branches that don't exist on the remote repository.
Make sure to understand it will also delete branches that you never actually pushed to that remote.

#/bin/bash

REMOTE=$(git remote) # usually origin

CMD_REMOTE_BRANCHES=$(git branch -r | sed "s/${REMOTE}\///g" | sed -r 's/^\s+//' | grep -E -v '^HEAD')

deleteIfNotOnRemote() {
    while read localBranch
    do
        found=false
        for remoteBranch in $CMD_REMOTE_BRANCHES; do
            if [ $remoteBranch = $localBranch ]; then
                found=true
                break
            fi
        done
        [ $found = false ] && git branch -d $localBranch 
    done
}

git branch | sed -r 's/^\s+//' | sed -r 's/^\* //' | deleteIfNotOnRemote

No comments:

Post a Comment