Using Lint pre-commit hook in Android project
If you work in a team you will surely have felt the pain of not being all on the same page when it comes to code style and formatting. Code style and formatting are important for many reasons..
In this post, you will learn how to automate Ktlint and Detekt checks with a pre-commit Git hook in your Android project to run code-style checks before you commit your change list..
Using pre-commit hooks in your Android project can be beneficial as they help maintain code quality, enforce coding standards, and prevent common mistakes from being committed..
For example, you can use pre-commit hooks to run code formatting checks, static code analysis, unit tests, or any other custom validations that you deem necessary for your project..
There are several Kotlin linters available for Android projects. Some of the popular ones but in our example we are going to use Ktlint and Detekt..
In general Android projects case, Once the pre-commit hook is set up, it will execute the ktlint and detekt tasks when you try to make a commit..
If there are any code style or quality issues identified by the linter, the commit will be aborted, and an error message will be displayed. You will need to fix the issues indicated by the linter before you can successfully commit your changes..
Now navigate to the root directory of your Android project repository. And create directories as scripts and sub-directory under scripts/pre-commit..
Also, create a shell script file named pre-commit (without any file extension) intoscripts/pre-commit the directory. Here is the shell script file content:. If you have any doubts or issues, see the final created directory with file content in the working example on the below link:.
:shared:preBuild : example project module task that will start after installGitHooks task completed..
Once the pre-commit hook is in place, it will be executed automatically before each commit. If the hook script exits with a non-zero status, the commit will be aborted, allowing you to fix any issues before proceeding. Let's see how in the next section!. To verify if a Git hook is successfully validating code using ktlint in the Git console, you can follow these steps now:. Now, there are a couple of possible outcomes:.
If you need to check more about git hook, please check my GitHub repo..
Congratulations…. That was pretty cool, right? This is all the stuff you need to know about integrated Kotlin linting tools using git hooks in your Android project.. Before wrapping up, I want to take a moment to tell thank you for reading this article. Your continued support, comments, and engagement have been truly inspiring..
Don’t forget to clap👏/recommend as much as you can and also share📤 with your friends. It means a lot to me..
Linting tools:. Git hook docs:.