Skip to content

Instantly share code, notes, and snippets.

@rafaroca
Last active April 18, 2024 14:34
Show Gist options
  • Save rafaroca/f6e8650e4a51fd240fa8aafff8dc32d1 to your computer and use it in GitHub Desktop.
Save rafaroca/f6e8650e4a51fd240fa8aafff8dc32d1 to your computer and use it in GitHub Desktop.
git pre-commit hook to run the gradle ktlint plugin and add changed files to the git index.
#!/bin/sh
set -e
######## KTLINT-GRADLE HOOK START ########
CHANGED_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 ~ /^R/ {print $3}; $1 != "D" && $2 ~ /\.kts|\.kt/ {print $2}')"
if [ -z "$CHANGED_FILES" ]; then
echo "No Kotlin staged files."
exit 0
fi;
echo "Running ktlint over these files:"
echo "$CHANGED_FILES"
./gradlew --quiet ktlintFormat -PinternalKtlintGitFilter="$CHANGED_FILES"
echo "Completed ktlint run."
echo "$CHANGED_FILES" | while read -r file; do
if [ -f "$file" ]; then
git add "$file"
fi
done
echo "Completed ktlint hook."
######## KTLINT-GRADLE HOOK END ########
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment