Created
November 3, 2025 16:19
-
-
Save agentbellnorm/13e76efd30d70ed760fb06cc682336dd to your computer and use it in GitHub Desktop.
Format staged files on commit, include any formatting changes in the same commit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/sh | |
| #### | |
| # The goal of this file is to make sure no code that would fail the style check in CI is committed. | |
| #### | |
| # exit early if there are no staged changes | |
| if git diff --cached --quiet; then | |
| echo "[pre-commit] no staged changes - not doing anything" | |
| exit 0 | |
| fi | |
| # temporarily commit everything that was staged by dev | |
| git commit -m "temp" --no-verify --quiet | |
| STASHED=false | |
| CHANGES=$(git status --porcelain) | |
| # if there were unstaged changes | |
| if [ ! -z "$CHANGES" ]; then | |
| # stash away everything that was not staged by dev | |
| git stash --quiet --include-untracked | |
| STASHED=true | |
| fi | |
| # uncommit the temp commit. | |
| git reset --soft HEAD~ | |
| echo "[pre-commit] formatting staged changes" | |
| # format everything | |
| mvn spotless:apply --quiet | |
| # save spotless exit code | |
| RESULT=$? | |
| # stage any additional changes made by spotless | |
| git add --update | |
| if [ "$STASHED" = true ]; then | |
| # restore everything that was not staged by developer. It will still be unstaged | |
| git stash pop --quiet | |
| fi | |
| # exit with the code from spotless | |
| exit $RESULT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment