#!/bin/sh
# Enable with: git config core.hooksPath hooks
# Skip a single commit with: git commit --no-verify

set -e

echo "pre-commit: cargo fmt --check"
cargo fmt --check

echo "pre-commit: cargo clippy"
cargo clippy --workspace --all-targets --all-features -- -D warnings

echo "pre-commit: cargo test --lib"
cargo test --workspace --lib --quiet

echo "pre-commit: US spelling"
staged=$(git diff --cached --name-only --diff-filter=ACM -- '*.rs' '*.md' '*.toml' '*.wgsl')
if [ -n "$staged" ]; then
    # shellcheck disable=SC2086
    hits=$(git grep -wniE -e 'metre|metres|kilometre|kilometres' \
        -e 'licence|defence|programme|catalogue|grey' \
        -e 'manoeuvre|manoeuvres|manoeuvred|manoeuvring' \
        -e 'normalise|normalised|normalises|normalising|normalisation' \
        -e 'stabilise|stabilised|stabilises|stabilising|stabilisation' \
        -e 'recognise|recognised|recognises|recognising' \
        -e 'serialise|serialised|serialises|serialising|serialisation' \
        -e 'behaviour|behaviours|colour|colours|centre|centres' \
        -e 'analyse|analysed|analyses|analysing' \
        -e 'organise|organised|organisation|optimise|optimised|optimisation' \
        -e 'initialise|initialised|initialisation|utilise|utilised' \
        -e 'rasterise|rasterised|rasterising|rasterisation' \
        -e 'modelling|modelled|labelled|cancelled|travelled' \
        -e 'favour|favours|honour|honours|neighbour|neighbours' \
        --cached -- $staged || true)
    if [ -n "$hits" ]; then
        echo "$hits"
        echo
        echo "pre-commit: British spellings found above. This project uses US English."
        exit 1
    fi
fi

echo "pre-commit: ok"
