Git history search with fzf

fzf is one of my favorite shell tools. I have a ton of scripts where I use it for selection. Here's one for searching git history. git log -Gpattern allows you to search for commits that contain pattern in the patch text. Combine it with fzf and you get a pretty decent history search tool.

I have this saved as ~/bin/git-search-log, so I can invoke it as git search-log pattern or git search-log pattern branch:

#!/bin/bash

set -euo pipefail

# Ensure compatibility with fish etc by ensuring fzf uses bash for the preview command
export SHELL=/bin/bash

git log -G$@ --oneline | fzf \
    --preview-window=bottom,80% \
    --preview "echo {} | sed 's/ .*//g' | xargs git show --color" \
    --bind 'enter:execute(commit=$(echo {} | sed "s/ .*//g") && git diff-tree --no-commit-id --name-only $commit -r | fzf --preview-window=bottom,80% --preview "git show --color $commit -- $(git rev-parse --show-toplevel)/\{}")'

When you run it you get an selection of matching commits, one per line, with a preview window showing the patch. If you hit enter on a commit, you get another fzf screen, this time allowing you to select files modified in that commit. Hit enter again and you're back in the first one.

© Juri Pakaste 2024