Step-by-Step Guide to Implementing Git Pre-Commit Hooks
Let's start with what are Git Hooks? So, Git Hooks are scripts which are written in Bash/Ruby/Python/Perl and can be executed after some event in git. These events can be after checkout to a new branch or after a commit.
Some of the commonly used git hooks
In this composition we will be usingpre-commit
Scenario 1
Let’s revisit the moment when we have mistakenly pushed a syntax error and after all the process of deployment we found that our build contains an error and the process repeats. So do you know how important time we've wasted then? It might not be a frequent issue but it can break the process.
Scenario 2
Consider a situation where feature1 is indirectly dependent on feature2, and we have received a change request (CR1) for feature1. The inventor modifies the law to address the new request and tests it. Following this, Scenario 1 occurs, and the developer makes additional changes to resolve the issue. While fixing the issues, some changes unintentionally get mixed into CR1, and the developer commits and pushes the code. After deployment, the user discovers that there were some scenarios where the code failed in QA testing.
‘’’To prevent the above scenario(s) what we can do is we can set up a task which checks our code before we commit. There comes git hooks and in this scenario we can use a pre-commit hook which will run every time before we commit and if any error comes in between running the script it will abort the commit.’’’
In this composition we've used Spring Boot with nut as an illustration. Let’s start setting up pre-commit hook
STEP 1: produce a directory at root where we will be storing hooks in our design. It can named anything according to our usage, for example we have used .githooks
STEP 2: Change the hooks path to the directory we have created in STEP 1
STEP 3: Create a file named exactly pre-commit . This is the train that will be executed before every commit.
领英推荐
STEP 4: Adding maven-surefire-plugin to pom.xml file, which will help in failing the build immediately in case any of the test fails.
STEP 5: Now try to commit and it will run the test first and then commit if build passes.
Troubleshoot Steps
‘’’Also, keep in mind every time a user clones the repository they have to manually make the changes for setting the hooks. It will be a one time task but the user has to do it.’’’
Written By: Mitul Gautam