Formatting Android code with Ktlint and Git Hooks

Barros
2 min readApr 30, 2022
Photo by Oskar Yildiz on Unsplash

How many times did it bother you to see unformatted code during a code review? Or how many times did you ask your colleagues to respect the same guideline when they are coding to make the review easier?

It is a solution for this problem, with ktlint and git hooks we can check if code is correctly formatted and avoid discrepancies between authors.

Ktlint

It is a plugin that fix all style violations, so all developers will follow same style convention. To integrate it, we use the gradle plugin from JLLeitschuh repository.

Add the plugin to build.gradle:

plugins {
id("org.jlleitschuh.gradle.ktlint") version "<current_version>"
}

repositories {
// Required to download KtLint
mavenCentral()
}

Now, you can manually run ./gradlew ktlintCheck to check if it works.

Git Hook

Next step, we want to run these tasks automatically before any commit. So, we create a Git Hook.

  1. Create a folder in the root project called githook
  2. Add a new file in the folder called pre-commit
  3. Add the following script in pre-commit file

--

--