Git

May 24, 2019

Git: Local Branch Cleanup On Easy Mode

Preamble

If you are like me and are constantly creating new local feature branches, you will notice that they really start stacking up (especially on long-running projects). Perhaps this is an artifact of fast-paced agile development process, mixed with general untidiness, but needless to say, I have this problem, and it disturbs me. You might say this could be mitigated by having one local branch that all of your development occurs in, however, this has a number of drawbacks, namely having to rebase every time a commit is made to the target, as well as meaningless branch names. These are both rather undesirable, the latter especially if you are running some flavour of Git Flow. Enter the Git local branch cleanup!

[Side-rant]: The best way to use Git!

The following will specifically target Git users who interact with the Git CLI in PowerShell. I recently discovered a PowerShell plugin called posh-git which has changed my life. Not only are you blessed with tab-completion, but you can also see at a glance which branch you’re on, as well as how many adds, modifications, deletes and conflicts, as can be seen below

git local branch cleanup posh-git

I digress. You’re most likely here to find out the quick and easy way to remove local branches. In the example below, we will delete every branch NOT named ‘maste

The Actual Command

git branch | %{ $_.Trim() } | ?{ $_ -ne 'master' } | %{ git branch -D $_ }

And that’s it! To break this command down, we’ll look at it in sections, broken down by each pipe

git branch

This should be familiar to most of us already. If not, fear not. It just lists all local branches.

%{ $_.Trim() }

Simply trim each result from the previous call that lists our branches.

?{ $_ -ne 'master' }

Filter the list, removing the specified entry. In this case, ‘master’. This is so that we don’t remove our master branch.

%{ git branch -D $_ }

Finally, we take the list we’ve been manipulating, and run a git branch delete command on it. Easy!

You may also like...

Leave a Reply