unixorn/git-extra-commands

View on GitHub
bin/git-checkout-preview

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash
#
# Based on fzf wiki
#
# Copyright 2021, Joe Block <jpb@unixorn.net>

set -o pipefail
if [[ -n "$DEBUG" ]]; then
  set -x
fi

# fco_preview - checkout git branch/tag, with a preview showing the commits between the tag/branch and HEAD
fco_preview() {
  local tags branches target
  branches=$(
    git --no-pager branch --all \
      --format="%(if)%(HEAD)%(then)%(else)%(if:equals=HEAD)%(refname:strip=3)%(then)%(else)%1B[0;34;1mbranch%09%1B[m%(refname:short)%(end)%(end)" \
    | sed '/^$/d') || return
  tags=$(
    git --no-pager tag | awk '{print "\x1b[35;1mtag\x1b[m\t" $1}') || return
  target=$(
    (echo "$branches"; echo "$tags") |
    fzf --no-hscroll --no-multi -n 2 \
        --ansi --preview="git --no-pager log -150 --pretty=format:%s '..{2}'") || return
  # shellcheck disable=SC2046
  exec git checkout $(awk '{print $2}' <<<"$target" )
}

fco_preview