#!/usr/bin/env sh
#
# git-pagediffs - paginate individual Git commits as separate files in $PAGER
#
# Git outputs a range of commits all together which makes scrolling to the top
# or bottom of a single commit troublesome since you have to manually look or
# search for the commit separators. This script opens each commit separately so
# you can scroll to the top or bottom of a diff with `g` or `G`, and move back
# and forth between individual commits with `:n` and `:p`.
#
# Examples:
#
# Show diffs for all outgoing changes not yet pushed to origin:
#
#    git pagediffs @{u}..
#
# Show diffs for all changes not yet present on the current branch, excluding
# merges, and ignoring a specific branch:
#
#     git pagediffs ..origin/somebranch --no-merges --not uninteresting_branch

# shellcheck disable=SC2249
while getopts ':h' opt; do
  case "${opt}" in
    h)
      awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
      exit 0
      ;;
    \?)
      printf "%s: Unrecognized option '-%c'\n" "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

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

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

mkdir -p "${temp}"

git sh --reverse --color=always --color-moved "$@" \
  | csplit -s -n 4 -f "${temp}/xx" - '/^\[33mcommit /' '{*}'

rm -f -- "${temp}/xx0000"
${PAGER:-"less -F"} -R "${temp}/xx"*
