How to add a pre-commit git hook script using a Gradle task

A step by step guide on adding a pre-commit script to a git repo as part of a Gradle build to guarantee consistency across your team.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 06/08/2023 at 16:21
Last Updated on 06/16/2023 at 15:19
Two flowers that represent Kotlin and Android Studio. Beneath them sits the text "Add pre-commit git hook script during Gradle build."

A step by step guide on adding a pre-commit script to a git repo as part of a Gradle build to guarantee consistency across your team.

SubscribeDownload Open Source Kotlin Starter Project

Step One: Create a .scripts folder

A screenshot of Android Studio showing the newly created .scripts folder.

At the root of your Android Studio project, create a folder called .scripts.

Step Two: Add pre-commit script

A screenshot of Android Studio showing the pre-commit script in the .scripts folder. The code that is shown in the screenshot is available below.

In the newly created .scripts folder, create a new script called pre-commit and add any relevant code.

This script will be added to the githooks folder during the gradle build.

If you wish to use our recommended pre-commit script, please use the code below.

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

Step Three: Add the Task to Gradle

A screenshot of Android Studio highlighting the location of the project build.gradle.kts as well as the task, whose code is found below.

At the project level build.gradle.kts and the following task:

How to run a Gradle Kotlin DSL pre-build task in Android Studio

Step Four: Test

A screenshot of Android Studio showing how the Task's logs appear as successful during the Gradle build.

Sync the Gradles with your project and confirm that the script appears in your .git/hooks folder.

A screenshot of Finder showing the pre-commit script added to the .git/hooks folder.

Once it looks good, commit the changes to your git repo, so that your team can benefit from the script.

Looking to deny commits to specific branches ?

To learn how to block commits to specific branches, follow the tutorial below.

How to prevent commits to a branch using a pre-commit githook script

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe