Git hooks are powerful tools that can automate various tasks in your development workflow. They are scripts that Git executes before or after events such as commit
, push
, and receive
. In this blog post, we’ll focus on how to set up hooks to run automatically before building a new compilation in a Kotlin-based Android project.
What are Git Hooks?
Git hooks are custom scripts that are triggered by specific Git events. For instance, a pre-commit
hook runs just before a commit is finalized, allowing developers to enforce code quality checks, run tests, or perform any other task that ensures the integrity of the codebase.
The Need for Automation
While Git hooks are incredibly useful, remembering to set them up for every new clone or repository can be tedious. Automating this process ensures that:
- Every developer on the team has the necessary hooks in place.
- The setup process is consistent and error-free.
- Code quality and other checks are always enforced before critical Git operations.
Setting Up Automated Git Hooks in Kotlin-based Android Project
Let’s dive into the code that automates the installation of Git hooks:
tasks {
val installGitHooks by registering(Copy::class) {
from(File(rootProject.rootDir, "scripts/pre-commit"))
into(File(rootProject.rootDir, ".git/hooks"))
fileMode = 0b000_111_101_101 // 0755 in binary
}
// Install hooks automatically before building a new compilation
getByPath(":app:preBuild").dependsOn(installGitHooks)
}
Here’s a step-by-step breakdown:
- Defining the Task: We start by defining a task named
installGitHooks
. This task is of typeCopy
, which means its primary function is to copy files from one location to another. - Source and Destination: We specify that the source of our copy operation is a
pre-commit
script located in thescripts
directory. This script contains the operations we want to run before a commit. The destination is the.git/hooks
directory, where Git looks for hooks to execute. - Setting Permissions: The line
fileMode = 0b000_111_101_101
sets the file permissions to0755
, making the script executable. This is crucial because, for Git to run the hook, it needs to be executable. - Hooking into the Build Process: The line
getByPath(":app:preBuild").dependsOn(installGitHooks)
ensures that ourinstallGitHooks
task runs before thepreBuild
task of theapp
module. This means that every time you try to build the app, the Git hooks will be installed automatically.
Conclusion
Automating the installation of Git hooks ensures a consistent development environment and enforces code quality checks seamlessly. By integrating this automation into the build process, developers can focus on writing code, confident that the necessary checks and balances are in place.
Reference
Sample Code: https://github.com/EzequielMessore/pokedex/blob/c1b727378d0767d156d9d6d38d1869818a669782/build.gradle.kts