How to run Spotless and ktlint in a pre-commit git hook
A step by step guide on adding a pre-commit git script that runs Spotless and ktlint formatting before committing code to an Android Studio project.
Please note that this tutorial assumes that you have setup your project to run with Spotless and ktlint. If you do not, please complete the tutorial below before proceeding.
Step One: Duplicate the pre-commit.sample script
Open your Finder and duplicate the pre-commit.sample script found under .git/hooks/pre-commit.sample.
You can duplicate the script by pressing cmd + d on a Mac.
Step Two: Rename the pre-commit script
Rename the duplicated pre-commit.sample script to pre-commit.
Step Three: Replace code
Open the pre-commit script in text edit and replace the code with the one below.
This code:
- Gathers the staged files - to make sure that only changes from Spotless from these files are saved to the git repository.
- Runs Spotless Apply
- In the event that Spotless succeeded, the script adds any changes to the staged files to the git repository.
Step Four: Test
Please note that the projectsEvaluated Tasks are custom tasks that we have added.
Add some innocent tab spacing and commit code.
You will see that the script runs and that the code is fixed within the commit.
Curious how to run tasks during the Gradle build phase ?
To learn how to run custom tasks during the Gradle build phase, consult the tutorials below.
Want to make this script consistent across your team?
We recommend following the tutorial below to learn how to add this script to your githooks folder during a Gradle build, enabling code consistency across teams.