9

Is there a way to run a gruntjs task as precommit hook. For example I want do prevent commits with failing tests or jshint issues. I've also think about to run a code beautifier for every commit.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297

3 Answers3

9

Git hooks are just scripts executed when you do an action like commit. They can contain whatever programming language you'd like.

Example of triggering grunt:

#!/bin/sh
grunt

Save this in the file: .git/hooks/pre-commit

If grunt exits with an error code higher than 0, which it does if any task fail, it will prevent the commit:

Exiting non-zero from this hook aborts the commit


Reading material: Tips for using a git pre-commit hook

And the git docs: 8.3 Customizing Git - Git Hooks

Like many other Version Control Systems, Git has a way to fire off custom scripts when certain important actions occur.

Edgar
  • 6,022
  • 8
  • 33
  • 66
Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232
5

I recently had the same issue and detailed a more comprehensive Grunt solution on http://viget.com/extend/grunt-getting-started-with-git-hooks

chrisM
  • 338
  • 1
  • 4
  • 9
  • You can also do this really easily now (sans Grunt, if you like) using Husky: https://github.com/typicode/husky – chrisM Mar 20 '15 at 19:58
2

I think you should check out grunt-githooks, a nice Grunt plugin that does all the magic for you and lets you easily register Grunt tasks for certain hooks from within your Gruntfile.js, such as:

grunt.initConfig({
  githooks: {
    all: {
      // Will run the jshint and test:unit tasks at every commit
      'pre-commit': 'jshint test:unit',
    }
  }
});

(Taken from the docs at https://github.com/wecodemore/grunt-githooks#defining-a-few-hooks)

Find the module on npm here.

kaiser
  • 21,817
  • 17
  • 90
  • 110
Golo Roden
  • 140,679
  • 96
  • 298
  • 425