Last active
November 16, 2024 14:59
-
-
Save scottyab/a96cd316ebee25b7a68427b86be86f1e to your computer and use it in GitHub Desktop.
Git precommit hook deigned to run Gradle based static analysis checks for Ktlint and Detekt. Crated for Android Kotlin projects and is compatable with Windows/Mac. Requires Detekt and Ktlint Gradle plugins configured and installed on the project.
This file contains 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 | |
echo "Running git pre-commit hook..." | |
echo "Checking if any kotlin files have changed..." | |
# Determine the platform | |
UNAME=$(uname) | |
# Exit early if no Kotlin files have changed. | |
if [ "$UNAME" = "Darwin" ]; then | |
# Mac specific code | |
FILES=$(git diff --name-only --cached --relative | grep '\.kt[s"]\?$') | |
[ -z "$FILES" ] && echo "No Kotlin files have changed, skipping pre-commit checks." && exit 0 | |
else | |
# Windows specific code | |
diff_output=$(git diff --name-only --cached --relative) | |
for line in $diff_output; do | |
if [[ $line =~ \.kt$ || $line =~ \.kts$ ]]; then | |
continue | |
fi | |
echo "No Kotlin files have changed, skipping pre-commit checks." | |
exit 0 | |
done | |
fi | |
# https://github.com/pinterest/ktlint pre-commit hook | |
echo "Running ktlint check..." | |
OUTPUT="/tmp/ktlint-$(date + %s)" | |
./gradlew ktlintCheck --continue >"$OUTPUT" | |
EXIT_CODE=$? | |
if [ $EXIT_CODE -ne 0 ]; then | |
cat "$OUTPUT" | |
rm "$OUTPUT" | |
echo "***********************************************" | |
echo " ktlint failed " | |
echo " Please fix the above issues before committing " | |
echo "***********************************************" | |
exit $EXIT_CODE | |
fi | |
# https://detekt.github.io/detekt/git-pre-commit-hook.html pre-commit hook | |
echo "Running detekt check..." | |
OUTPUT="/tmp/detekt-$(date + %s)" | |
./gradlew detekt > "$OUTPUT" | |
EXIT_CODE=$? | |
if [ $EXIT_CODE -ne 0 ]; then | |
cat "$OUTPUT" | |
rm "$OUTPUT" | |
echo "***********************************************" | |
echo " Detekt failed " | |
echo " Please fix the above issues before committing " | |
echo "***********************************************" | |
exit $EXIT_CODE | |
fi | |
rm "$OUTPUT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment