An Interest In:
Web News this Week
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
- March 22, 2024
Git pre-hook: pre-commit with Gradle task
There are various Git pre-hooks that 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 a linting before you commit or running unit tests before push or commit.
Whenever a Git repository is initialized, Git creates sample hooks inside
.git/hooks
directory in the project directory. E.g..git/hooks/pre-commit.sample
Below are steps on how to configure pre-hook for a Gradle project:
1. Create a pre-hook script, let's create pre-commit
file inside a new scripts
directory, and we want to run unit tests before code commit.
#!/bin/shecho"*****Running unit tests******"git stash -q --keep-index./gradlew teststatus=$?git unstash pop -qexit $status
Above command stash 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 been configured for pre-commit, changes must have been staged, make sense?)
2. Next, create Gradle task to install the pre-commit script. Why do we need it? because, we want this to run on all developers' machine, not just on our machine, we all love consistency and wants to put the 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 project root directory
scripts
Above Gradle task will run wherever someone takes the build and assuming that developer who is making changes will run build task at least once and I hope I'm right.
Once pre-commit script is copied to .git/hooks/
directory, we're all set.
Next time, whenever someone will run git commit
, it will first run the ./gradlew test
task.
git commit -m "update code"-- Output*****Running unit tests******...
The way
./gradlew test
is configured, in the same way, any other task can be executed. And of course for other tasks stash and unstash won't compulsory.
If you have reached here, then I did a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections. Happy Coding!
Original Link: https://dev.to/an1meshk/git-pre-hook-pre-commit-with-gradle-task-134m
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To