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.

New to staff augmentation? Download this partner checklist.

 

The available client side hooks are:

  • applypatch-msg
  • commit-msg
  • hooks.txt
  • post-commit
  • post-receive
  • post-update
  • pre-applypatch
  • pre-commit
  • pre-rebase
  • prepare-commit-msg
  • update
SETTING UP GIT HOOKS - 1 - Available Git Hooks - Axelerant

Available Git Hooks

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.

SETTING UP GIT HOOKS - 2 - Creating a pre-commit Git hook running Grunt tasks and Mocha test suite - Axelerant

Creating a pre-commit Git hook running Grunt tasks and Mocha test suite

  • 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.
SETTING UP GIT HOOKS - 3 - Duplicating the pre-commit.sample file - Axelerant

Duplicating the pre-commit.sample file

  • 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.
SETTING UP GIT HOOKS - 4 - Remove the example script and add the Grunt and Mocha commands. - Axelerant

Remove the example script and add the Grunt and Mocha commands.

  • Now whenever we run the git commit command 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.

Want Axelerant to grow your team? Learn More

  • kawal

    can you please tell me how to access gruntfile in githooks file. I m getting error when i replavced the pre-commit script with my tasks.