Git hooks are custom scripts that executes when you run a particular Git command. There are two variations of Git hooks:
- Client Side Hooks
- Server Side Hooks
We will be discussing the client side hooks in this post. The Git hooks can be run before or after a particular command, like the pre-commit or post-commit; these run before or after a commit is made. One of the simpler use cases for these Git hooks can be code linting, which can be used to initiate the test-runner to run the test in the repository whenever we make a commit. However, we can run some highly advanced custom scripts that can run multiple tasks using these Git hooks.
The available client side hooks are:
These Git hooks can be found in the
.git/hooks directory. All these hooks are predefined in this directory and post-fixed with
.sample. To create a custom hook, copy the file to the same directory while removing the
.sample part from the file name. Now edit the file and add the script/commands that you will want to run after a particular Git command.
To demonstrate we will create a pre-commit hook that will run some Grunt tasks and Mocha test suite whenever we make a commit. These tasks are defined in the
Gruntfile.js and in a test directory containing all the unit tests.
- We will start by duplicating the pre-commit.sample file in the same directory with the name pre-commit. The pre-commit file will already be populated with an example script.
- Next we will open the file in the text editor of choice, remove the example script and add the Grunt and Mocha commands we want to run. Save the file. Time to test the hooks.
- Now whenever we run the
git commitcommand the grunt and mocha task will run before we can type in the commit message.
This saves us a lot of time and roots out the pain of running the same tasks over and over again. We will be diving into more advanced hooks for both Client and Sever side in future.