#!/usr/bin/env bash
## Use fzf(https//github.com/junegunn/fzf) to browse the repository's git reflog list that can be filtered by entering a fuzzy term at the prompt. Navigation up and down the hash list will preview the changes of each hash.
## Source: git-extra-commands

#
# Original source: https://bluz71.github.io/2018/11/26/fuzzy-finding-in-bash-with-fzf.html

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

fail() {
  printf '%s\n' "$1" >&2  ## Send message to stderr. Exclude >&2 if you don't want it that way.
  exit "${2-1}"  ## Return a code specified by $2 or 1 by default.
}

git-fzf-reflog-browser() {
  selection=$(
    git reflog --color=always "$@" |
      fzf --no-multi --ansi --no-sort --no-height \
          --preview "git show --color=always {1}"
    )
  if [[ -n "$selection" ]]; then
    # shellcheck disable=SC2086
    git show "$(echo $selection | cut -d' ' -f1)"
  fi
}

if ! has fzf; then
  fail "You need fzf (https://github.com/junegunn/fzf) to use this script. "
fi

# shellcheck disable=SC2068
git-fzf-reflog-browser $@