From aa8168c07b39441957cf50a00c71613c3cd4f071 Mon Sep 17 00:00:00 2001 From: jakobeha Date: Thu, 7 Mar 2024 14:50:04 -0500 Subject: [PATCH] change spotless to apply only on staged changes, unless everything is staged will not commit if a partially-staged file was reformatted, because it's ambiguous what to add to the commit --- .githooks/pre-commit.sh | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/.githooks/pre-commit.sh b/.githooks/pre-commit.sh index 4aec57173..fc62e47f9 100755 --- a/.githooks/pre-commit.sh +++ b/.githooks/pre-commit.sh @@ -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