Skip to content

Instantly share code, notes, and snippets.

@dylanwatsonsoftware
Last active February 17, 2025 17:58
Show Gist options
  • Save dylanwatsonsoftware/1c2148e03eb688a8c8e15e799c176386 to your computer and use it in GitHub Desktop.
Save dylanwatsonsoftware/1c2148e03eb688a8c8e15e799c176386 to your computer and use it in GitHub Desktop.
mvn spotless pre-commit
#!/bin/bash
# Pops the stash created by the pre-commit hook
# This seems to avoid most merge-conflicts created by partially staged files
git stash pop
#!/bin/bash
#
# Git pre-commit hook to format code before it is committed via `mvn spotless:apply`
#
# Basically, this hook:
# - Formats any partially-staged files (to avoid conflicts later)
# - Stashes the unstaged changes
# - Formats the staged changes
# - Add any formatting changes to the commit
# - Pops back the unstaged changes.
#
set -e
if [ "$(cat .git/MERGE_HEAD 2> /dev/null)" != '' ]; then
echo "Detected we are in the middle of a merge, skip formatting"
exit 0
fi
# Calculate the list of comma-separated, staged files
PWD=$(pwd | sed 's;/;\\\/;g')
PARTIALLY_STAGES_FILES_LINES=$(comm -12 <(git diff --name-only) <(git diff --staged --name-only))
PARTIALLY_STAGES_FILES=$(echo "$PARTIALLY_STAGES_FILES_LINES" | sed "s/^/$PWD\//" | xargs | sed -e 's/ /,/g')
if [ "$PARTIALLY_STAGES_FILES_LINES" != '' ]; then
echo "Found partially-staged changes. Running an initial spotless:apply to avoid merge conflicts."
echo "Files to format:"
echo "$PARTIALLY_STAGES_FILES_LINES"
./mvnw spotless:apply -DspotlessFiles="$PARTIALLY_STAGES_FILES"
fi
echo "Stashing unstaged changes"
git stash -q --keep-index
# Run the formatter
STAGED_FILES_LINES=$(git diff --staged --name-only)
STAGED_FILES=$(echo "$STAGED_FILES_LINES" | sed "s/^/$PWD\//" | xargs | sed -e 's/ /,/g')
echo "Running spotless:apply on the staged changes"
echo "Files to format:"
echo "$STAGED_FILES_LINES"
./mvnw spotless:apply -DspotlessFiles="$STAGED_FILES"
# Add any formatted files to the commit
if [ "$(git update-index --refresh && git diff-index --quiet HEAD --)" != '' ]; then
git add .
echo "Spotless added some formatting changes to your commit"
fi
@dylanwatsonsoftware
Copy link
Author

Pair this with a maven plugin that installs the git hooks on build... That way you can commit these hooks to the repo.

https://github.com/rudikershaw/git-build-hook

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment