CLI of the Week: clearing branches

2 minute read

One of the things that I end up doing all the time is clearing branches. After finishing some work, usually, I have some branches around that need to be removed. It is convenient to have a command that helps you with that tedious task. But there is a scenario in which that command comes in handy; during code reviews. I do a couple of hours a day of code review. In those sessions, I end up checking out several branches, so polluting y workspaces with branches to test on the device. There are better ways to do that, and I will explain them in other posts, but eventually, this will happen.

Whenever I need this kind of micro commands, I created one and added to my folder from where they will be loaded on launching the terminal. In this case, I will create the git clear branches command or gcb. This command will clear all the branches, including the current one (yes, heavy metal).

Here is the command file command-gab.bash:

printf ", gcb"

function gclearbranches () {
  read -p "This command will remove all uncommitted work, are you sure (y/n)? " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]
  then
    git fetch --prune origin
    git reset --hard
    git branch | egrep -v "(^\*)" | xargs git branch -D
    git branch | egrep "(^\*)" | sed 's/*//' | xargs git pull origin 
  fi
}

alias gcb='gclearbranches'

As you can see, in there, I create a function and alias to that function. On the first line, I have just a print to show that the scrip it loaded on launching the terminal. Then I create a function with the commands. This function is destructive, so it is always a good idea to inform the user about it. I ask for confirmation and do nothing if the user does not agree. In the first line in the then section, I will clean up the branches that were deleted on the remote, leaving my environment in sync with the server. The second line just cleans up my workspaces.

On the third line, interesting things happen. First, list the local branches with git branch. Then I filter them removing the one with an asterisk, which is the current one. And, the result, I pass one by one to the git branch -D that force deletes them. Finally, on the last line, I fetch the current branch. That way, I have no extra branches, and the current one is at the top of its changes, in par with the remote.

After running that command, I am ready to work on clean.

Tags: ,

Updated: