Funky world of Juha

Bizarre and funky world of Juha

Git hooks: Pre commit & grunt January 28, 2013

Filed under: Frontend,git — juhq @ 4:07 pm

I’ve found the powers of git hooks recently. There are multiple hooks, for local client and for server. These will save you a lot of time and money when used properly.

 

In this article, I’m going to talk a bit about pre commit hook, which I’ve found to be the most important for my work.

Pre commit hook will run any command you want, before each commit. You can automate tests, do validation, building etc.

This should usually prevent you from pushing bad code to the server.

 

Hooks can also be set to the server, for example pre-receive hook, which you can command to run the same grunt for each push. This has the downside of not preventing bad code from being pushed to the server.

 

 

But let’s talk a bit about pre commit with grunt.

 

First, you’re going to need to install grunt

$ npm install grunt

Then set up your git hook

$ nano .git/hooks/pre-commit

To run grunt against your project on each commit, simply copy&paste the following code.

#!/bin/sh
grunt
if [ $? -ne 0 ]; then
 echo "Grunt failed, please fix code and recommit"
 exit 1
fi
exit 0

Now add grunt.js file to project root folder, with the following basic configuration.

module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    lint: {
      all: [
        'grunt.js',
        '**/*.js'
      ]
    }
  });
  // Default task.
  grunt.registerTask('default', 'lint');
};

On each commit, git will now automatically run grunt against your codebase. For this example, I’m only using jslint to catch coding errors.

Grunt is a powerful tool which has over 300 different plugins, you can run automated tests, build your project, minify/uglify codebase, deploy your code to Amazon S3 and much, much more.

If your code is fine, the commit will continue as normal, but if your code has some issues, the hook will prevent you from committing bad code, which could break your project.

If your code passes, you should see something like this

Grunt ok

If your code has issues, you should see something like this

Grunt fail

More about hooks: Git hooks

Get grunt: Grunt