Introduction
Various Git pre-hooks are quite helpful for several essential tasks we want to execute before commit or push, or rebase, etc. Basically, there are various use cases, like running linting before you commit or running unit tests before pushing or committing.
Whenever a Git repository is initialized, Git creates sample hooks inside the
.git/hooksdirectory in the project directory. E.g..git/hooks/pre-commit.sample
Getting Started
Below are the steps on how to configure a pre-hook for a Gradle project:
1. Create a pre-hook script
Let's create a pre-commit file inside a new scripts directory, and we want to run unit tests before code commit.
#!/bin/sh
echo "*****Running unit tests******"
stash_commit="$(git stash create)"
git reset β-hard
./gradlew test
status=$?
if [[ -n "${stash_commit}" ]]
then git stash apply "${stash_commit}"
fi
echo "*****Done with unit tests******"
exit $status
The above command stashes the working directory changes before running the unit tests, and unstash back. This makes sure we're running unit tests only in the clean working directory. (as this is configured for pre-commit, changes must have been staged, make sense?π)
2. Create Gradle Task
Next, create a Gradle task in the build.gradle file to install the pre-commit script. Why do we need it? Because we want this to run on all developers' machines, not just on our machine, we all love consistency and want to put constraints.
task installLocalGitHook(type: Copy){
from new File(rootProject.rootDir, 'scripts/pre-commit')
into { new File(rootProject.rootDir, '.git/hooks')}
fileMode 0775
}
build.dependsOn installLocalGitHook
Here pre-commit file was created inside the project root directory, i.e.,
scripts
The above Gradle task will run whenever someone takes the build, and assuming that the developer who is making changes will run the Gradle build task at least once, and I hope I'm rightπ.
Once the pre-commit script is copied to the .git/hooks/ directory, we're all set. We can verify its content as follows:
cat .git/hooks/pre-commit
Now, next time, whenever someone runs git commit, it will first run the ./gradlew test task.
E.g.
ak@--mac git-pre-commit % git commit -am "update"
-- Output
*****Running unit tests******
BUILD SUCCESSFUL in 1s
4 actionable tasks: 4 up-to-date
[main ed41136] update
1 file changed, 13 insertions(+), 1 deletion(-)
Final Thoughts
- The way
./gradlew testis configured, in the same way, any other tasks can be executed. And of course, for other tasks, stash and unstash won't be compulsory. - And similarly, other pre-hooks can be configured
Sample GitHub Code
Here is the GitHub repo with an example.
If you have reached here, then I have made a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections. Happy Coding!
Top comments (0)