#!/bin/sh
# Runs the spec and document checks of the fast gate (tools/Invoke-Validation.ps1) before a commit,
# so a spec problem fails here instead of in CI. Enable once per clone with:
#   git config core.hooksPath .githooks
# The checks run on what is being committed: the index (GIT_INDEX_FILE during a partial commit) is
# copied to a temporary directory, so unstaged edits and untracked files neither hide a problem
# nor block a clean commit. GIT_DIR and GIT_WORK_TREE keep the checks' git calls (the deleted-ID
# comparison) on this repository.
set -e
if ! command -v node >/dev/null 2>&1; then
  echo "pre-commit: node is not on the path, so the spec checks were skipped; CI runs them." >&2
  exit 0
fi
git_dir=$(git rev-parse --absolute-git-dir)
# The checker is installed in the working tree's node_modules (pnpm install at the root), which the
# staged copy does not hold. A linked worktree without its own install uses the main checkout's;
# check-documentation.mjs refuses an install of another version than package.json pins.
STANDARD_CHECKER_ROOT=$(git rev-parse --show-toplevel)
if [ ! -d "$STANDARD_CHECKER_ROOT/node_modules/@scientific-method/standard-checker" ]; then
  main_checkout=$(cd "$(git rev-parse --git-common-dir)/.." && pwd)
  if [ -d "$main_checkout/node_modules/@scientific-method/standard-checker" ]; then
    STANDARD_CHECKER_ROOT=$main_checkout
  fi
fi
export STANDARD_CHECKER_ROOT
# A separate step, so a failed mktemp stops the hook instead of leaving $staged empty.
staged=$(mktemp -d)
trap 'rm -rf "$staged"' EXIT
trap 'exit 1' HUP INT TERM
git checkout-index --all --prefix="$staged/"
export GIT_DIR="$git_dir" GIT_WORK_TREE="$staged"
# A test file of a validated row can only be recorded in validation/ once it is committed and its
# tests ran against the original's files, so a missing or stale record does not block the commit.
node "$staged/tools/check-documentation.mjs" --check --no-ksy --allow-unrecorded-validation
# Computes the function index without writing the local report docs/FUNCTION-INDEX.md.
node "$staged/tools/spec-coverage.mjs" --check
node "$staged/tools/update-doc-indexes.mjs" --check
