Last active
January 23, 2022 21:01
-
-
Save toefel18/23c8927e28b7e7cf600cb5cdd4d980e1 to your computer and use it in GitHub Desktop.
Git pre-commit hook that applies spotless and adds the files again
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/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; |
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 | |
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 ######## |
Thanks, will try it out :)
@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
If you replace
print $2
withprint $NF
formatting will also correctly handle renamed files.cc @stefankreitmayer