Introduction
Like many other version control systems, Git has a way to execute custom scripts when certain important actions occur. One of the good thing to do is to automatically valid the code before you commit it to repository. Even, if you are doing it manually frequently you may forget to do that just before commit and this means that you’ll send invalid code. For example you may run just your unit test and forget to run unit tests for whole project. To prevent from it we can use Git pre-commit
hook. What this does:
The pre-commit hook is run first, before you even type in a commit message. It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code. Exiting non-zero from this hook aborts the commit[…]
Source: Customizing Git – Git Hooks
Create pre-commit
hook
Follow below steps to create pre-commit
hook for your project:
- Go to the folder YOUR_PROJECT\.git\hooks\
- Find the file
pre-commit.sample
and rename it just topre-commit
. If it doesn’t exists then create the filepre-commit
(without any extension). - Edit file
pre-commit
with the following example content (do not include line numbers):#!/bin/sh echo "Executing pre-commit" grunt validate
That’s it. grunt validate
is just an example. This could be your Grunt task that validates the code: JavaScript lint, unit tests, etc.
How it works
In above pre-commit
hook we just executing Grunt task named validate
and if that task return code 0 then it will allow you to commit the code to the repository. Otherwise it will fail.
Leave a Reply