Skip to content

Instantly share code, notes, and snippets.

@Barros9
Last active November 4, 2020 17:51
Show Gist options
  • Save Barros9/2294fb215650c1dbe365c32143c9d74b to your computer and use it in GitHub Desktop.
Save Barros9/2294fb215650c1dbe365c32143c9d74b to your computer and use it in GitHub Desktop.
GitHookKtLintTask
task installGitHook(type: Copy) {
def lintingConfigScript = new File(rootProject.rootDir, '.git/hooks/pre-commit')
if (!lintingConfigScript.exists()) {
from new File(rootProject.rootDir, '.githooks/pre-commit')
into { new File(rootProject.rootDir, '.git/hooks') }
fileMode 0777
}
}
tasks.getByPath('app:preBuild').dependsOn installGitHook
@Barros9
Copy link
Author

Barros9 commented Nov 4, 2020

Create git/hooks/pre-commit (without extensions) and add the following script

#!/bin/bash

# Stash the current index to be used in the event of failure
git stash -q --keep-index

echo "Running Ktlint before git commit is committed"

./gradlew ktlintFormat

RESULT=$?

git stash pop -q

# return 1 exit code if running checks fails
[ $RESULT -ne 0 ] && exit 1

######## KTLINT-GRADLE HOOK START ########

CHANGED_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$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