![]() |
Git hooks enable us to execute our custom scripts in response to specific git lifecycle events, like merging, committing, pushing, etc. This means that with the help of the scripts we can fire off certain events every time a git event occurs. For example, if you want to make a commit that follows specific criteria or anything special you want when that commitment is made, you can do that with those custom scripts. Hooks can be present on the local repos or server-side repos. Exploring Git HooksI will be using git bash to interact with git on my system, make sure you have basic knowledge of Linux commands such as ls, PWD, etc. Let’s create a sample directory and initialize a git repository there.
The above commands create an empty directory named mydir and a git repo is initialized there. ![]()
When you type the “ls -a” you will see the hidden files as well as the .git folder. Git hooks are present in the .git folder.
![]()
![]()
Now let’s go into the hooks directory and look at the contents. ![]()
Inside the hooks directory, you can see that the files have an extension of “sample” which means that they are not yet usable. The pre and post-before file names suggest the timing when the scripts will be executed. For example, a pre-commit hook will work before we try to commit something and a post-commit hook will work after the work has been committed. To install a hook we just have to get rid of the .sample extension and give it permission to be executable. The top 5 most popular hooks are:
Let’s try to install a hook and get practical experience. We will be installing a hook named pre-commit hook. First, we have to remove the .sample extension to make it usable and then make it executable.
![]()
Now that we have enabled this hook, we will use it to check whether the user email that we are using for committing is valid or not. If they are not correct then this hook will throw an error message. Open the pre-commit file with vi-editor and write this piece of code,
![]()
This piece of code ensures that the email address that you type must be correct, exit 1 at the end of the code means that we exited with some error. Now create a sample file GFG.txt. ![]()
Now let’s try to commit this file, for committing I am using a sample email “[email protected]”. To unset your email use the command below and log in again with another command.
![]()
Since the email is a different one, we are getting an error that we wrote in the pre-commit file. So this is how we learned to install a hook and also learned to practically use it. Similarly, you can use the other hooks by removing the .sample extension and writing your custom scripts. |
Reffered: https://www.geeksforgeeks.org
How To |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |