#!/bin/sh
# The cheap checks, over the whole workspace. The expensive ones are in pre-push.
#
# Measured on a warm tree: under a second for all four. A cold target directory costs half
# a minute once and nothing after.
#
# Silent when everything passes. On a failure it names the check and prints what the tool
# said, which is what a commit from an editor needs in order to be diagnosable.
set -e

if ! command -v cargo >/dev/null 2>&1; then
    echo "pre-commit: cargo is not on PATH" >&2
    echo "pre-commit: PATH is $PATH" >&2
    exit 1
fi

check() {
    name=$1
    shift
    if ! output=$("$@" 2>&1); then
        echo "pre-commit: $name failed" >&2
        printf '%s\n' "$output" >&2
        exit 1
    fi
}

check "formatting" cargo fmt --all --check
check "clippy" cargo clippy --workspace --all-targets --all-features -- -D warnings
check "the library tests" cargo test --lib

# British spellings keep slipping into generated prose. This file is excluded because it
# holds the word list, which would otherwise match itself.
if git diff --cached -U0 -- . ':(exclude)hooks/pre-commit' |
    grep -nE '^\+.*\b(metre|metres|normalis|stabilis|recognis|licence|modelling|manoeuvre|behaviour|analyse|analysing|centre|colour)'; then
    echo "pre-commit: British spelling above; this project is US English" >&2
    exit 1
fi
