Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@isaacs 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

This comment has been minimized.

Copy link
Owner Author

@domenic domenic commented Mar 29, 2012

Thanks @isaacs; updated!

@rdrey

This comment has been minimized.

Copy link

@rdrey 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

This comment has been minimized.

Copy link

@KKrisu KKrisu commented Jul 17, 2013

Does it work on windows?

@adius

This comment has been minimized.

Copy link

@adius 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

This comment has been minimized.

Copy link

@begin-again begin-again commented Mar 25, 2018

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
You can’t perform that action at this time.