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 ########
@toefel18
Copy link
Author

Thanks, will try it out :)

@toefel18
Copy link
Author

@timtebeek I looked up your comment, so NF is the number of fields in the awk record, so NF will select the last item.

Verified the output of the git diff to check, seems work!:

R100	README.MD	Blaat.md
M	service/src/main/kotlin/net/..../Config.kt

Thanks for the suggestion.

Btw if you use kotlin and ktlint via gradle plugin 'org.jlleitschuh.gradle.ktlint', it comes with a build-in pre-commit hook you can install as follows:

./gradlew addKtlintFormatGitPreCommitHook

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment