Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change spotless to apply only on staged changes, unless everything is staged #11

Merged
merged 1 commit into from
Mar 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions .githooks/pre-commit.sh
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
#!/bin/sh
#!/bin/bash

everything_staged=$(git diff --name-only)
# `no_partial_stages` from https://github.com/evilmartians/lefthook/issues/140#issuecomment-1012967850
no_partial_stages=$(comm -12 <(git diff --name-only | sort) <(git diff --name-only --staged | sort))
format_only_staged=-DspotlessFiles="$(git diff --staged --name-only | sed 's/^/.*/' | paste -sd ',' -)"

if [ -n "$everything_staged" ]; then
# Don't commit because, after we reformat, the formatting will be unstaged, but it's too hard to determine (and maybe
# ambiguous) what are the formatting differences and what was originally unstaged.
mvn spotless:check || {
echo "*** ERROR ***"
echo "Detected a partial commit that doesn't have proper formatting."
echo "Run 'mvn spotless:apply', make sure every change you want to commit is added, and commit again."
if [ -n "$no_partial_stages" ]; then
# Format only staged changes. Don't commit if we change anything, because we can't partially format a file, and it's
# ambiguous what formatting changes should be staged and what shouldn't.
mvn spotless:check "$format_only_staged" || {
mvn spotless:apply "$format_only_staged"
echo "Reformatted a partially-staged file. Re-interactively-stage and commit again."
exit 1
}
git add -u
elif [ -n "$everything_staged" ]; then
# Format only staged changes. We must re-add them because the formats aren't committed.
mvn spotless:apply "$format_only_staged"
git diff --name-only --staged | tr \\n \\0 | xargs -0 git add -f
else
# It's not ambiguous, just format and re-add everything tracked
# Format everything because spotless caches. We must re-add everything because the formats aren't committed.
mvn spotless:apply
git add -u
fi
Loading