Pre-commit hook for Spring Boot Gradle application
When you are working with a codebase that has a series of checks before the code is merged into the master. While working on some feature, if your build is failed after pushing all the changes then you need to fix issues that caused the build to fail and then you will have to do something like git commit -m "Build fixes"
and push this extra commit in order to fix the build.
What if we can avoid these unnecessary build-fix commits in git history? This can be achieved by adding a pre-commit hook to the repository. The pre-commit hook checks if a build is successful before making a commit. If the build is failing pre-commit hook throws an error and doesn't allow the developer to make a commit.
We can set the pre-commit hook using the following steps
- We need to create a script that will run the build command before the commit is made. create a file with the name
pre-commit
in the root directory
#!/bin/shecho "*****Running build and tests******"git stash -q --keep-index./gradlew clean buildstatus=$?git stash pop -qecho "*****Done with build and tests******"exit $status
2. Create a Gradle file pre-commit-hook.gradle
inside gradle
folder. This task will have the responsibility to copy the above script to .git/hooks
folder.
task preCommitHook(type: Copy) {
println '================================================'
println 'Executing gradle precommit hook command'
println '================================================'
from new File(rootProject.rootDir, 'pre-commit')
into { new File(rootProject.rootDir, '.git/hooks') }
fileMode 0775
}test.dependsOn preCommitHook
3. Add this line to build.gradle
file
apply from: 'gradle/pre-commit-hook.gradle'
4. Now when you run ./gradlew test
pre-commit and hook will have been set up. You can verify this by running
cat ./git/hooks/pre-commit
If the content .git/hooks/pre-commit
is the same as our script then the setup is successful
Now ./gradlew clean build
command will run before every commit, And a commit will be made iff the build is successful.
You can use git commit --no-verify -m "commit message"
to skip the build step before committing.