Skip to content

Instantly share code, notes, and snippets.

@LLCampos
Last active April 20, 2020 07:25
Show Gist options
  • Save LLCampos/02eb8682084a56059507bd82b27a89db to your computer and use it in GitHub Desktop.
Save LLCampos/02eb8682084a56059507bd82b27a89db to your computer and use it in GitHub Desktop.
pre-commit hook for Maven multi-project repositories - Build and run tests for each Maven project for which there are staged files
#!/bin/bash
# Install with:
# ln -s ../../pre-commit.sh .git/hooks/pre-commit
# Inspired by:
# https://gist.github.com/arnobroekhof/9454645
function pop_stash {
STASHES=($(git stash list))
for stash in "${STASHES[@]}"
do
if [[ $stash == "$1" ]]; then
git stash pop -q
fi
done
}
echo "Build and run tests for each project for which there are staged files"
STASH_NAME="pre-commit-$(date +%s)"
git stash save -q --keep-index "$STASH_NAME"
CWD=$(pwd)
PARENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/../.. && pwd )"
cd "$PARENT_DIR"
PROJECTS=($(ls -d ./*/))
for project in "${PROJECTS[@]}"
do
changed_files=($(git diff --cached --name-only "$project"))
changed_files_number=${#changed_files[@]}
if [ "$changed_files_number" -gt 0 ]; then
cd "$project"
mvn clean install
if [ $? -ne 0 ]; then
echo "Error while building $project"
cd "$CWD"
pop_stash "$STASH_NAME"
exit 1
fi
cd "$PARENT_DIR"
fi
done
pop_stash "$STASH_NAME"
cd "$CWD"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment