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:

  1. Go to the folder YOUR_PROJECT\.git\hooks\
  2. Find the file pre-commit.sample and rename it just to pre-commit. If it doesn’t exists then create the file pre-commit (without any extension).
  3. Edit file pre-commit with the following example content (do not include line numbers):
    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.


You can leave a response, or trackback from your own site.

Before you add comment see for rules.

Leave a Reply

Your email address will not be published. Required fields are marked *