#!/bin/bash

# Install this file as a pre-commit hook,
# If this script exits with a non-zero status, commit will not proceed.

# This script is run OUTSIDE OF DOCKER.
# Install dependencies on the dev machine:
#
#     python3 -m pip install -U ruff


set -e

thisfile="${BASH_SOURCE[0]}"
thisdir="$(cd "$(dirname "${thisfile}")"; pwd)"
if [[ "$(basename "${thisdir}")" != .githooks ]]; then
    # In this case, this script is not being executed directly;
    # rather, it is being "sourced" from another repo. The sourcing
    # script should have ensured that `pwd` is the repo's root directory.
    rootdir="$(pwd)"
else
    # In this case, the script is in folder `.githooks/`, so we go
    # one level up into the root directory of the repo.
    rootdir="$(dirname "${thisdir}")"
fi


# Infer package name, assuming a single directory exists under `src/`.
rm -rf "${rootdir}/src/*egg-info"
pkg="$(ls "${rootdir}/src/")"
if [[ "${pkg}" == *' '* ]]; then
    >&2 echo "unable to infer package name"
    exit 1
fi
pkg="${pkg%/}"


SRC="${rootdir}/src/${pkg}"
TESTS="${rootdir}/tests"

status=0



# `black -S`: do not change between single/double quotes; leave them as is.
# changed=$(python3 -m black --check -q -S "${SRC}" "${TESTS}"; echo $?)
changed=$(python3 -m ruff format --check -q "${SRC}" "${TESTS}" >/dev/null 2>&1; echo $?)
# See https://stackoverflow.com/a/876242 for redirection.
if [[ "${changed}" != 0 ]]; then
    echo ==\> -\> -\> Formatting code by \`ruff\` ...
    python3 -m ruff format "${SRC}" "${TESTS}"
    echo
    echo Please add the reformatted files and commit again.
    echo
    status=1
    # We do not commit the changes here by `git add -u`.
    # It's hard to take care of all scenarios, e.g. there may be a file
    # that was changed (unrelated to formatting) but was intentionally not added to the commit,
    # while `git add -u` would add it to the commit.
fi


# User should configure what to check/ignore by `ruff` in section `[tool.ruff]`
# in `pyproject.toml`.
changed=0
python3 -m ruff check --no-cache -q "${SRC}" "${TESTS}" || changed=1
if [[ "${changed}" == 1 ]]; then
    echo ==\> -\> -\> Fixing some issues by \`ruff --fix\` ...
    python3 -m ruff check --no-cache --fix "${SRC}" "${TESTS}"
    echo
    echo Please examine the issues reported/fixed by \`ruff\`\; if all is good, please add them and commit again.
    echo
    status=1
fi



# echo
# echo --- running mypy ---
# echo
# # python -m mypy --show-error-codes --disable-error-code import ${SRC} || true
# python3 -m mypy ${SRC} || true  # MyPy errors do not halt this script



exit "${status}"


