#!/bin/bash
# Install with:
#   git config core.hooksPath hooks

# Executes tests against the code about to be submitted.  It makes a copy of
# the worktree using "git worktree", then patches in the *staged* changes
# (either those manually staged via "git add" or those generated by a
# standalone "git commit").  Then it runs the tests.

# If this crashes, it will cause git to leak worktrees, but that should not
# really be a problem.  Eventually the tempdir will be cleaned, and eventually
# git will detect the directories and clean up the worktree entries as well.

# If you need to manually clean up, something like the following works well:

# git worktree prune -n  # To see what would be pruned
# git worktree prune -v  # To see what was pruned
# git worktree list  # To see what is left
# git worktree list |
#   awk '/tmp.tmp/ {print $1}' |
#   while read wt; do
#     echo $wt
#     git worktree remove -f $wt
#   done

set -u

export PAGER=cat

branch=$(git branch --show-current)
if [[ ${branch} == scratch ]]; then
  echo "Ignoring branch: ${branch}"
  exit
fi

patchfile=$(mktemp)
git diff --patch --cached > "${patchfile}"

# In this particular script, we no longer want these environment variables
# set.
readarray -t env_vars < <(git rev-parse --local-env-vars)
unset "${env_vars[@]}"

dir=$(mktemp -d)
git worktree add --force "${dir}" "${branch}"
pushd "${dir}" > /dev/null || exit
git apply --allow-empty "${patchfile}"
git diff --stat

hooks/checks
rc=$?

# Clean up.
popd > /dev/null || exit
git worktree remove --force "${dir}"
rm "${patchfile}"

exit "${rc}"
