Would you ask a group of people to write a one-page story with the hope that they would all do it in the same writing style? — I wouldn’t expect it! On the contrary, you would likely find many different writing styles. Furthermore, can you imagine being in charge of validating if there are no discrepancies between authors? The same can be said when it comes to code styling. Code reviewers shouldn’t waste time checking if braces are on the wrong line or if the space indentation is correct. In this post, you will learn how to automate Ktlint checks with a pre-commit Git hook in your Android project to run code-style checks before you commit your change-list.
Ktlint runs static code analysis. By using this tool, you place the importance of code clarity and community conventions over personal preferences. So, the following project will follow the official code style from kotlinlang.org and Android Kotlin Style Guide.
We will use the Ktlint Gradle plugin, which automatically creates Gradle tasks for your project that run ktlint checks or do code auto format.
1. Add the following code snippets to the “build.gradle”
2. Once the plugin is implemented, check if the ktlint tasks have been added.
Creating pre-commit Git hook
At this point, we should be able to run the ktlint check and format tasks, but we are aiming to run these tasks automatically before we commit our change list. For this purpose, we are going to create a Git hook.
Note: Git hooks are simple scripts that run when a particular event occurs in a Git repository
1. Create a “scripts” folder in the root of the project, then add a new file and call it “pre-commit.”
2. Add the following script in the “pre-commit” file:
Installing our Git hook
Git looks for possible scripts that need to be run into the “.git/hooks” folder. We need to place our pre-commit hook into it.
The problem is that these scripts remain in our local environment. So, to ensure all members of the team will benefit, we can create a simple Gradle task that automatically places the script into the “.git/hooks” folder.
1. Add the following task in the app module “build.gradle” file:
build.gradle project level
2. Build your project and check the “.git/hooks” folder. Our script should be placed there:
Try it out
Before running our test, how many code style violations can you spot in the following code?
Let’s try to commit these changes and see what happens.
Having this kind of setup can improve our team’s workflow and code cleanliness. At the same time, allows developers to focus on what really matters for the business instead of checking code style violations in every code review.
Let’s make code reviewers’ lives easier and write cleaner code! I hope you find this post useful.