#!/usr/bin/env bash
# This script validates the staged changes in Haskell files using fourmolu and hlint, and
# in cabal files using cabal-gild. It returns non-zero code when there are linting
# or style issues.
#
# To set this script as your pre-commit hook, use the following command:
#
# ln -s $(git-root)/scripts/githooks/haskell-style-lint $(git rev-parse --git-dir)/hooks/pre-commit
#

hlint_rc="0"

for x in $(git diff --staged --name-only --diff-filter=ACM "*.hs" | tr '\n' ' '); do
  if grep -qE '^#' "$x"; then
    echo "$x contains CPP.  Skipping."
  else
    "$(git rev-parse --show-toplevel)/scripts/devshell/prettify" "$x"
  fi
  hlint "$x" || hlint_rc="1"
done

for x in $(git diff --staged --name-only --diff-filter=ACM "*.cabal" | tr '\n' ' '); do
  cabal-gild -i "$x" -o "$x"
done

# fail if there are style issues
git --no-pager diff --exit-code || exit 1
# if there are no style issue, there could be hlint issues:
exit $hlint_rc
