summaryrefslogtreecommitdiff
path: root/hooks/pre-commit
blob: 6e0b167da07e8ff787939590248436fbea952d44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/bin/bash

filesToAddAfterFormatting=()
containsSpotlessEnabledFormats=0

# Collect all files currently in staging area, and check if there are any spotless enabled format file
# We currently support only *.kt, *.gradle', '*.md', '.gitignore' files.
for entry in $(git status --porcelain | sed -r 's/[ \t]+/-/g'); do
  # entry can be for example:
  # MM-src/main/java/net/project/MyController.java
  # -M-src/main/java/net/project/AnotherController.java

  if [[ $entry == M* ]]; then
    filesToAddAfterFormatting+=(${entry:2}) # strips the prefix
  fi

  if [[ $entry == *.kt ]] || [[ $entry == *.gradle ]] || [[ $entry == *.md ]] || [[ $entry == .gitignore ]]; then
    containsSpotlessEnabledFormats=1
  fi
done

# If any java or kotlin files are found, run spotlessApply
if [ "$containsSpotlessEnabledFormats" == "1" ]; then
  echo '[git hook] executing gradle spotlessCheck before commit'
  ./gradlew spotlessCheck
  EXIT_CODE=$?
  if [ $EXIT_CODE -ne 0 ]; then
    echo "❌ [git hook] spotlessCheck failed, running spotlessApply for you..."

    ./gradlew spotlessApply

    echo "[git hook] Formatting done, please try your commit again! If the problem persists, apply fixes manually."
    exit $EXIT_CODE
  fi
  echo "✔️ [git hook] Spotless: Everything looks clean!"
else
  echo "[git hook] Not running spotless"
fi

# Add the files that were in the staging area
for file in "${filesToAddAfterFormatting[@]}"; do
  echo "re-adding $file after formatting"
  git add "$file"
done

exit 0