git 🤝 fzf


When I’m working in smaller organisations, I often find myself zipping about between branches and commits. I try to keep things nicely packaged up into branches so that I can take full benefit of all of the PR-related tools that GitHub/GitLab/Pick-your-git-server-flavour offer. Whilst that’s great for organisation, it can really lead me into some keyboard acrobatics when I’m switching between different branches, or more likely before I’ve even figured out what the name of the branch I want to switch to is called in the first place.

Today’s note-to-self is all about making that easier with a few git aliases.

git aliases

git offers users an alias function to make it possible to achieve more with fewer keystrokes.

Here’s how you might create a simple alias, one that I use all the time:

# in ~/.gitconfig
[alias]
  co = "checkout"

This is maybe the simplest an alias can be, a remapping of git checkout to git co. All of the options are still supported so it’s a pretty 1-for-1 replacement keyword.

fzf

fzf is a very well-known tool and you will probably have encountered it as a way to browse for files by searching; that is, at least, one of the default uses they suggest in the setup notes. However, fzf is more generically a “fuzzy finder”. You give it a list of things and some pattern and it will show you the best fuzzy matches. You can apply this to anything, all it takes is to pipe the input into the fzf command and you’ll get a beautiful, interactive finder/picker. Try it out with this obnoxious command.

# Choose a word to uppercase
echo "hello\nworld\n" | fzf | tr '[:lower:]' '[:upper:]'

git & fzf

These aliases are more powerful than they might seem at first glance because you’re not limited to executing git commands inside those aliases; you can also call other unix tools. So this got me thinking… can we put these together for benefit? Of course we can!

One my most beloved aliases is git cor, or “git checkout recent”. Here it is

[alias]
  co = "checkout"
  cor = "!git checkout $(git recent-branches | fzf)"
  recent-branches = "!git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)' | head -n 10"

Let’s break it down.

We’ll start at git recent-branches; this alias first sorts branches by their creation time and chooses the first ten.

Next, we make use of that in git cor; we call checkout on the result of choosing from the recent-branch alias.

Putting it together, we:

  1. list the branches with most recent first
  2. choose the first ten
  3. pass their names to fzf to prompt us to search and select one
  4. pass the selected branch name to checkout

Simple, effective, fantastically unix-y!