‹ jan0sch.de

A git pre commit hook with scalafmt.

2022-03-23

It is nice if your CI/CD pipeline does also check for code format compliance but sometimes you may want to have feedback earlier or even prevent unformatted code to enter the repository.

In such a case the git DVCS offers hooks to the rescue. You can either dive into their documentation or simply use the script provided below. ;-)

#!/bin/sh
#
# A simple git pre-commit hook to check via scalafmt for code validity.

ROOT=$(git rev-parse --show-toplevel)
SCALAFMT_CONFIG="${ROOT}/.scalafmt.conf"

if [ ! -f "${SCALAFMT_CONFIG}" ]; then
  # Exit quietly if no scalafmt configuration is found.
  exit 0
else
  # Prefer the CLI version because it is faster.
  echo "Checking code format via scalafmt, please wait a minute."
  echo "The check can be skipped by using the --no-verify flag for git commit."
  $(command -v scalafmt >/dev/null 2>&1 && $(scalafmt --config "${SCALAFMT_CONFIG}" --exclude target --mode changed --non-interactive --quiet --test >/dev/null 2>&1) || $(sbt scalafmtCheckAll >/dev/null 2>&1))
  STATUS=$?
  if [ ! $STATUS -eq 0 ]; then
    echo ""
    echo "**Some files are not properly formatted, please run scalafmt!**"
    echo ""
  fi
  exit $STATUS
fi

To be able to work the script needs to be copied into the .git/hooks folder and be named pre-commit and it has to be executable of course. Since version 2.9 of git you can also put your hooks into a custom folder and set the configuration variable core.hooksPath to that folder.