#!/bin/sh
# Before `git push`: the checks CI runs that are quick (flake8, isort, black and the tests),
# so a push does not turn CI red. Turn it on once per clone:
#
#     git config core.hooksPath .githooks
#
# Push anyway (e.g. work in progress on a branch): git push --no-verify

cd "$(git rev-parse --show-toplevel)" || exit 1

# flake8, isort and black come from the dependency group lint, in env/ or on the PATH
# the project's virtualenv if there is one, else whatever python is active
PYTHON=python3
[ -x env/bin/python ] && PYTHON=env/bin/python
# flake8: from that python, else a flake8 on the PATH (e.g. brew install flake8)
FLAKE8="$PYTHON -m flake8"
if ! $FLAKE8 --version > /dev/null 2>&1 && command -v flake8 > /dev/null; then
    FLAKE8=flake8
fi

fail() {
    echo
    echo "pre-push: $1; not pushed (git push --no-verify to push anyway)"
    exit 1
}

$FLAKE8 --version > /dev/null 2>&1 || fail "flake8 is missing: brew install flake8, or pip install --group lint"

echo "pre-push: flake8"
$FLAKE8 postduif || fail "flake8 found problems"

# isort: from that python, else an isort on the PATH
ISORT="$PYTHON -m isort"
if ! $ISORT --version > /dev/null 2>&1 && command -v isort > /dev/null; then
    ISORT=isort
fi
$ISORT --version > /dev/null 2>&1 || fail "isort is missing: brew install isort, or pip install --group lint"

echo "pre-push: isort"
$ISORT --check-only --diff postduif || fail "imports not sorted (isort postduif)"

echo "pre-push: black"
"$PYTHON" -m black --check -q postduif || fail "not formatted (black postduif)"

echo "pre-push: tests"
"$PYTHON" -m pytest -q postduif || fail "tests failed"
