How to keep precondition for code

Eric Lee
2 min readSep 6, 2020

Have you ever heard git hooks?
If you use it, you can run a custom script when actions occurred in git.

I already post about ktlint in this post. This time I’ll set a hook to run ./gradlew ktlint to check if the code committed kept the style well or not.

It’s quite simple to set up but it’s useful to keep code style for cooperation.

The overall process is the following.

  1. create pre-commit file and make a script you want to run.
  2. create some gradle file to move pre-commit you created into .git/hooks folder. I made this file as install-git-hooks.gradle.
  3. add apply from: rootProject.file('install-git-hooks.gradle) in your build.gradle file wherever you need to declare.

That’s all we’ve to do.

I made a pre-commit script like the following.

#!/bin/sh
# From gist at https://gist.github.com/chadmaughan/5889802
echo '[git hook] executing ktlint before commit'# run ktlint with the gradle wrapper
./gradlew ktlint --daemon
RESULT=$?# return 1 exit code if running checks fails
[ $RESULT -ne 0 ] && exit 1
exit 0

I recommend you to use --daemon for performance. If you want to know further details, check The Gradle Daemon.

Then I added install-git-hooks.gradle to copy pre-commit file into .git/hooks folder.

task installGitHooks(type: Copy) {    
from new File(rootProject.rootDir, 'pre-commit')
into { new File(rootProject.rootDir, '.git/hooks') }
fileMode 0777
}
build.dependsOn installGitHooks

All done!

From now on, you can see the option of Run Git hooks whenever I try to commit code in Android studio.

All steps you can check through this commit.

Reference

--

--