|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +create_stash() { |
| 4 | + # Stash unstaged changes, if any |
| 5 | + previous_stash=$(git rev-parse -q --verify refs/stash) |
| 6 | + git stash push -q |
| 7 | + new_stash=$(git rev-parse -q --verify refs/stash) |
| 8 | +} |
| 9 | + |
| 10 | +pop_stash() { |
| 11 | + # Restore unstaged changes, if any |
| 12 | + if [ "$previous_stash" != "$new_stash" ]; then |
| 13 | + git stash apply -q && git stash drop -q |
| 14 | + fi |
| 15 | +} |
| 16 | + |
| 17 | +echo "****Running pre-commit hooks****" |
| 18 | +# We want to apply spotless on all staged files. Therefore, we have to first draft a |
| 19 | +# WIP-commit for the staged changes and put the unstaged changes aside using stash |
| 20 | +# (otherwise spotless would apply on them as well, see https://github.com/diffplug/spotless/issues/623). |
| 21 | +# There are a few edge cases to handle here; for example if there are no unstaged changes, stash would not create a stash. |
| 22 | +# Hence, the following pop of the stash must be guarded (see https://stackoverflow.com/a/20480591/2411243). |
| 23 | + |
| 24 | +# Mini commit for staged changes, so that we can stash away unstaged in the next step (bypass hook with "no-verify" to avoid recursion) |
| 25 | +git commit --no-verify --message "WIP" |
| 26 | +commitExitCode=$? |
| 27 | +if [ "$commitExitCode" -ne 0 ]; then |
| 28 | + # Commit failed (for example if there is nothing staged), early-out |
| 29 | + exit "$commitExitCode" |
| 30 | +fi |
| 31 | + |
| 32 | +# Put unstaged away |
| 33 | +create_stash |
| 34 | +# Get back staged changes |
| 35 | +git reset --soft HEAD^ |
| 36 | + |
| 37 | +# Apply spotless on the staged changes only (rest has been put away) |
| 38 | +echo "**Applying spotless**" |
| 39 | +./gradlew spotlessApply |
| 40 | +spotlessExitCode=$? |
| 41 | +if [ "$spotlessExitCode" -ne 0 ]; then |
| 42 | + # Spotless failed, restore unstaged |
| 43 | + pop_stash |
| 44 | + exit "$spotlessExitCode" |
| 45 | +fi |
| 46 | + |
| 47 | +# Spotless possibly found changes, apply them |
| 48 | +git add -A |
| 49 | + |
| 50 | +# Restore back the unstaged changes |
| 51 | +pop_stash |
| 52 | +echo "****Done pre-commit hooks****" |
0 commit comments