Skip to content

Instantly share code, notes, and snippets.

@RoganDawes
Last active May 7, 2019 08:18
Show Gist options
  • Save RoganDawes/d275311ffed50d7750b18bf34a55f463 to your computer and use it in GitHub Desktop.
Save RoganDawes/d275311ffed50d7750b18bf34a55f463 to your computer and use it in GitHub Desktop.
Run maven on a clean directory, reflecting ONLY what will be in the commit, and excluding any other files in the working directory that might affect the build
#!/bin/bash
echo "running pre-commit hooks"
STAGED_FILES_CMD=`git diff --cached --name-only | grep -E "(\.java$)|(pom.xml)"`
# Determine if a file list is passed
echo "INPUT: $#"
if [ "$#" -eq 1 ] ; then
oIFS=$IFS
IFS='
'
SFILES="$1"
IFS=$oIFS
fi
SFILES=${SFILES:-$STAGED_FILES_CMD}
echo "STAGED_FILES_CMD: $STAGED_FILES_CMD, SFILES: $SFILES"
# Determine whether need run maven java test
if [ "$SFILES" == "" ] ; then
echo "no need to run maven test";
exit 0;
fi
echo "Running 'maven test' for errors"
# retrieving current working directory, if don't want to call this hook, run git commit --no-verify
CWD=`pwd`
MAIN_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# go to main project dir
cd $MAIN_DIR/../../
mkdir -p ${MAIN_DIR}/logs/
# Check out a copy of the index
tmpdir=$(mktemp -d) # or your other chosen method
trap "rm -rf $tmpdir" 0 1 2 3 15 # do something different in other languages
GIT_WORK_TREE=$tmpdir git checkout-index --all
cd $tmpdir
set -o pipefail
mvn test package | tee ${MAIN_DIR}/logs/mvn.log
RESULT=$?
# clean up
rm -rf $tmpdir
# go back to current working dir
cd $CWD
if [ $RESULT -ne 0 ] ; then
echo "Error while testing the code, commit aborted"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment