Skip to content

Instantly share code, notes, and snippets.

@domenic
Created March 29, 2012 16:01
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save domenic/2238951 to your computer and use it in GitHub Desktop.
Save domenic/2238951 to your computer and use it in GitHub Desktop.
Cross-platform git hooks for Node.js

Here's how this works:

  • Include a git_hooks/ directory in your project, with these two files (plus other hooks if you want, written in a similar style).
  • Add "npm" to your devDependencies in package.json, so that the pre-commit hook can do its magic.
  • Add test and lint scripts to your package.json, e.g.
    "scripts": {
        "test": "mocha",
        "lint": "jshint ./lib --show-non-errors"
    }
  • Whenever you clone the repository, run node git_hooks/link.js to symlink the hooks stored in the repository, in git_hooks, to the hidden .git/hooks directory.
#!/usr/bin/env node
var npm = require("npm");
npm.load(function (err) {
if (err) {
throw err;
}
npm.commands.test(function (err) {
if (err) {
process.exit(1);
}
npm.commands["run-script"](["lint"], function (err) {
if (err) {
process.exit(1);
}
});
});
});
@isaacs
Copy link

isaacs commented Mar 29, 2012

Nifty! Should probably nest the "lint" command underneath the "test" command. This way, you don't exit in the middle of a test if lint fails, or vice-versa.

@domenic
Copy link
Author

domenic commented Mar 29, 2012

Thanks @isaacs; updated!

@rdrey
Copy link

rdrey commented Aug 7, 2012

Instead of running node git_hooks/link.js manually after each clone, how about making it a part of npm install?

@KKrisu
Copy link

KKrisu commented Jul 17, 2013

Does it work on windows?

@adius
Copy link

adius commented Oct 27, 2014

To test whether a file exists before doing something with it is now considered to be an anti-pattern!
http://nodejs.org/docs/latest/api/all.html#all_fs_exists_path_callback

@begin-again
Copy link

Instead of a symlink, since got very 2.9 you set hooksPath in local config. 'git config core.hooksPath ./git_hooks'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment