#!/usr/bin/env sh
#
# git-quickfix - open Vim with Git changes as quickfix entries
#
# Useful for stepping through changes in one or more commits, or quickly
# picking back up where you left off after a WIP commit. The full diff for each
# quickfix entry is visible in the quickfix window.
#
# Usage:
#
#     # Open current commit (HEAD)
#     git quickfix
#
#     # Open single commit three back in history.
#     git quickfix HEAD~3
#
#     # Open range of commits starting from three back to current.
#     git quickfix HEAD~3..
#
#     # Open range of outgoing commits (upstream tracking).
#     git quickfix @{u}..
#
#     # Open only unstaged changes.
#     git quickfix -m modified
#
#     # Open only staged changes.
#     git quickfix -m staged
#
#     # Open single commit, or range of commits, that modify specific file.
#     git quickfix abcdef -- path/to/file.foo
#
#     # Open current commit but ignore whitespace changes.
#     git quickfix -- -w
#
#     # Redirect quickfix list to text file instead of opening Vim.
#     git quickfix @{u}.. > Quickfix.txt

NAME=$(basename "$0")
TEMP="${TMPDIR-/tmp}/${NAME}.${$}.$(awk \
  'BEGIN { srand(); printf "%d\n", rand() * 10^10 }')"

QFLIST="${TEMP}/quickfix.txt"

# shellcheck disable=SC2154
trap '
  excode=$?; trap - EXIT;
  rm -rf -- '"$TEMP"'
  exit $excode
' INT TERM EXIT

mode='commit'
# shellcheck disable=SC2220
while getopts 'hm:x' opt; do
  case ${opt} in
    m) mode="${OPTARG}" ;;
    h)
      awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
      exit 0
      ;;
    x) set -x ;;
  esac
done
shift "$((OPTIND - 1))"

umask 077
mkdir -p "${TEMP}"

{
  if [ "${mode}" = "modified" ]; then
    git diff -p -U0 --diff-filter=AM "$@"
  elif [ "${mode}" = "staged" ]; then
    git diff --cached -p -U0 --diff-filter=AM "$@"
  else
    if [ "$#" -gt 0 ]; then
      ref="$1"
      shift 1
    else
      ref='HEAD'
    fi

    case "${ref}" in
      *..*) git diff -p -U0 --diff-filter=AM -r "${ref}" "$@" ;;
      *) git show --first-parent -m -p -U0 --diff-filter=AM "${ref}" "$@" ;;
    esac

  fi
} | diff-to-quickfix >"${QFLIST}"

if [ ! -s "${QFLIST}" ]; then
  printf 'No %s changes.\n' "${mode}" 1>&2
  exit 1
fi

# open with Vim if outputting to a tty, otherwise just output directly.
if [ -t 1 ]; then
  # bd1 deletes the initial "[No Name]" buffer.
  ${EDITOR:-vi} +bd1 -q "${QFLIST}"
else
  cat "${QFLIST}"
fi

# \
#   | exec awk '
#     /^diff/ {
#         in_hunk=0
#     }
#     /^\+\+\+ / {
#         fname=substr($2, 2)
#     }
#
#     /^@@ / {
#         in_hunk=1
#         nr=substr($3, 2)
#         sub(/,.*/, "", nr)
#         printf(".%s:%s:%s\n", fname, nr, $0)
#         next
#     }
#
#     in_hunk {
#         printf("%s\n", $0)
#     }
# ' >"${QFLIST}"
