I ❤️ FZF. Use it for all sorts of things like jumping around directories, code projects, and so on.
Today while trying to change git branches I got really annoyed that I didn’t have anything like it for git.
So I found something and modified it to work a bit more in the way I like.
# FGIT - fuzzy checkout git branch (including remote branches)
FGIT_HISTORY=~/.cache/FGIT_history
fgit() {
local cmd="(git branch --sort=-committerdate; git branch --sort=-committerdate --remote) | grep -v HEAD | sed 's/^[ \*]*//'"
local preview_width=80
local preview_name_width=50
if [ "$1" != "" ]; then
local initial_query="-q $1"
fi
local default_branch=$(git symbolic-ref HEAD | cut -d'/' -f3)
local branch=$(eval $cmd | fzf \
--filepath-word \
--bind='ctrl-t:next-history'\
--bind='ctrl-r:previous-history'\
--bind='ctrl-n:down' \
--bind='ctrl-p:up' \
--layout='reverse-list' \
--tiebreak='end,length,index' \
--bind='change:first' \
--header='Press F5 to reload' \
--bind="f5:reload(${cmd})"\
--preview-window "right:$preview_width" \
--preview="git diff --stat=${preview_width},${preview_name_width} --merge-base master --color=always {}" \
--preview="git log -1; echo '\n---\n'; git diff --stat=${preview_width},${preview_name_width} --color=always {} --merge-base ${default_branch}" \
--history=$FGIT_HISTORY $initial_query)
git checkout $(echo "$branch" | sed "s/.* //" | sed "s#remotes/[^/]*/##")
}
The code is written for zsh
, but should be compatible with bash
with
limited to no changes.