Skip to content

Instantly share code, notes, and snippets.

@toefel18
Last active January 23, 2022 21:01
Show Gist options
  • Save toefel18/23c8927e28b7e7cf600cb5cdd4d980e1 to your computer and use it in GitHub Desktop.
Save toefel18/23c8927e28b7e7cf600cb5cdd4d980e1 to your computer and use it in GitHub Desktop.
Git pre-commit hook that applies spotless and adds the files again
#!/bin/bash
set -e
# command taken from https://github.com/JLLeitschuh/ktlint-gradle task addKtlintFormatGitPreCommitHook
filesToFormat="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $2 ~ /\.kts|\.java|\.kt/ { print $NF}')"
echo "files to format $filesToFormat"
for sourceFilePath in $filesToFormat
do
./gradlew spotlessApply -PspotlessIdeHook="$(pwd)/$sourceFilePath"
git add $sourceFilePath
done;
#!/bin/sh
set -e
######## KTLINT-GRADLE HOOK START ########
CHANGED_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $2 ~ /\.kts|\.kt/ { print $NF}')"
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