|
| 1 | +#!/bin/bash |
| 2 | +set -e |
| 3 | + |
| 4 | +# https://github.com/diffplug/spotless/issues/623 |
| 5 | +# https://gist.github.com/bhaskarmelkani/8baff88980f9cd90f8c44e07e433eb73#file-spotlessapply-sh |
| 6 | + |
| 7 | +# A precommit hook that uses spotless to format only staged files |
| 8 | + |
| 9 | +# It also supports partially stage files using the following steps: |
| 10 | +# 1. It stashed all the unstaged changes and then runs spotlessApply |
| 11 | +# 2. After spotless apply is finished it applyes the stashed changes back on the code (that is also formatted/changed by spotless) |
| 12 | +# 3. All the files that have conflicts due to the stash apply, it merges the conflict with the changes that are coming from the stash to not loose any new changes that were not staged |
| 13 | + |
| 14 | +# stash any un staged changes |
| 15 | +STASHED_HASH=$(git stash create) |
| 16 | + |
| 17 | +if [ -n "$STASHED_HASH" ]; then |
| 18 | + git stash store $STASHED_HASH |
| 19 | + git checkout -- . |
| 20 | +fi |
| 21 | + |
| 22 | +filesToFormat="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $2 ~ /\.kts|\.java|\.kt/ { print $2}')" |
| 23 | + |
| 24 | +printf "\n~~~ Spotless Starting ~~~" |
| 25 | +printf "\nSpotless: Files to check" |
| 26 | + |
| 27 | +for filePath in $filesToFormat; do |
| 28 | + printf "\n* %s" "$filePath" |
| 29 | +done |
| 30 | + |
| 31 | +printf "\n\nSpotless: Starting to format dirty files\n\n" |
| 32 | +for sourceFilePath in $filesToFormat; do |
| 33 | + ./gradlew spotlessCheck -PspotlessIdeHook="$(pwd)/$sourceFilePath" |
| 34 | + git add "$sourceFilePath" |
| 35 | +done |
| 36 | + |
| 37 | +if [ -n "$STASHED_HASH" ]; then |
| 38 | + echo "$(git stash apply -q)" |
| 39 | + |
| 40 | + conflictedFiles="$(git diff --name-only --diff-filter=U)" |
| 41 | + |
| 42 | + for conflictedFile in $conflictedFiles; do |
| 43 | + git checkout --theirs "$(pwd)/$conflictedFile" |
| 44 | + git restore --staged "$(pwd)/$conflictedFile" |
| 45 | + done |
| 46 | + |
| 47 | + git stash drop -q |
| 48 | +fi |
| 49 | + |
| 50 | +printf "\n~~~ Spotless Finished ~~~\n" |
0 commit comments