How to run Spotless and ktlint in a pre-commit git hook

Oscar de la Hera Gomez
Two flowers that represent Kotlin and Android Studio. Beneath them sits the text "Run Spotless and ktlint in pre-commit git script."

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

A screenshot of Finder highlighting the location of the pre-commit.sample git hooks 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

A screenshot of Finder showing the pre-commit script after being renamed.

Rename the duplicated pre-commit.sample script to pre-commit.

Step Three: Replace code

A screenshot of textedit showing the code provided below within the pre-commit script.

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

A screenshot of Sourcetree showing the pre-commit script being ran during a commit.

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.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details