Git housekeeping

TL;DR

When working in an enterprise environment, you may end up with lots of Git branches. And some of those branches will be forgotten and just live forever.

Unless you do something about it.

That’s why I’m going to give you one of my Git aliases, which I call: git housekeep

for branch in `git branch -r | grep -v HEAD`; do if [ `git rev-list --right-only --count origin/dev..$branch` -eq 0 ]; then echo -e `git show --format='%ci %cr %an' $branch | head -n 1` $branch; fi; done | sort -r"

Breakdown

So, let’s break down this alias. What does it actually do?

for branch in `git branch -r | grep -v HEAD`; do if [ `git rev-list --right-only --count origin/dev..$branch` -eq 0 ]; then echo -e `git show --format='%ci %cr %an' $branch | head -n 1` $branch; fi; done | sort -r"

The script begins with
for branch in `git branch -r | grep -v HEAD`; do [...]
which just is a loop (for) over all remote branches (git branch -r), except the HEAD branch (grep -v HEAD).

So, for each remote branch, we do something.
The first thing we do is to compare the branch to our base development branch, in my script origin/dev. (You want to rename this in your alias if yours is not called dev.)

The command
git rev-list --right-only --count origin/dev..$branch
outputs a number, which represents the number of commits the given branch is ahead of the base branch (origin/dev).
If this command outputs zero (0), that means that no commits are done in this branch, compared to the base branch.

Only if this is true
if [ `git rev-list --right-only --count origin/dev..$branch` -eq 0 ]; then [...]
we go ahead and print the branch to the output.

We print the branch using
echo -e `git show --format='%ci %cr %an' $branch | head -n 1` $branch
which just does a git show on the branch using a custom format.
We pipe this to head -n 1 to only use the first line of the output (since we’re not interested in the files changed in the associated commit or anything).

Wrap it

For git to be able to run this multiple command alias, it needs to be wrapped in
"!f() { [...] }; f"

The entire alias is:
housekeep = "!f() { for branch in `git branch -r | grep -v HEAD`; do if [ `git rev-list --right-only --count origin/dev..$branch` -eq 0 ]; then echo -e `git show --format='%ci %cr %an' $branch | head -n 1` $branch; fi; done | sort -r; }; f"

You’re welcome

Leave a Reply

Your email address will not be published. Required fields are marked *