Skip to content

Instantly share code, notes, and snippets.

@fedesilva
Forked from cvogt/pre-commit-hook-install.sh
Created January 7, 2018 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedesilva/45aaf6959721be2dab6da13a2f4783db to your computer and use it in GitHub Desktop.
Save fedesilva/45aaf6959721be2dab6da13a2f4783db to your computer and use it in GitHub Desktop.
git pre-commit hook for Scala compile and format checking (put both in your git project root, needs to be installed in each clone)
#!/bin/sh
cd "$(dirname "$0")"
touch .git/hooks/pre-commit
rm .git/hooks/pre-commit
ln -s ../../pre-commit-hook.sh .git/hooks/pre-commit
#!/bin/sh
# checks if locally staged changes are
# formatted properly. Ignores non-staged
# changes.
# Intended as git pre-commit hook
_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
DIR=$( echo $_DIR | sed 's/\/.git\/hooks$//' )
echo ""
echo "Running pre-commit hook ... (you can omit this with --no-verify, but don't)"
git diff --quiet
hadNoNonStagedChanges=$?
if ! [ $hadNoNonStagedChanges -eq 0 ]
then
echo "* Stashing non-staged changes"
git stash --keep-index -u > /dev/null
fi
echo "* Compiling/formatting staged changes"
$DIR/sbt ";test:compile;format" > /dev/null
compiles=$?
echo "* Compiles?"
if [ $compiles -eq 0 ]
then
echo "* Yes!"
echo "* Properly formatted?"
git diff --quiet
formatted=$?
if [ $formatted -eq 0 ]
then
echo "* Yes!"
else
echo "* No!"
echo "The following files need formatting (in stage or commited):"
git diff --name-only
echo ""
fi
else
echo "* No!"
fi
echo "* Undoing formatting"
git stash --keep-index > /dev/null
git stash drop > /dev/null
if ! [ $hadNoNonStagedChanges -eq 0 ]
then
echo "* Scheduling stash pop of previously stashed non-staged changes for 1 second after commit"
sleep 1 && git stash pop --index > /dev/null & # sleep and & otherwise commit fails when this leads to a merge conflict
fi
if [ $compiles -eq 0 ] && [ $formatted -eq 0 ]
then
echo "... done. Proceeding with commit."
exit 0
elif [ $compiles -eq 0 ]
then
echo "... done."
echo "CANCELLING commit due to NON-FORMATTED CODE."
exit 1
else
echo "... done."
echo "CANCELLING commit due to COMPILE ERROR."
exit 2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment