Skip to content

Instantly share code, notes, and snippets.

@cgmartin
Forked from domenic/README.md
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgmartin/fe9eaeadd023a52b37c5 to your computer and use it in GitHub Desktop.
Save cgmartin/fe9eaeadd023a52b37c5 to your computer and use it in GitHub Desktop.
Node git pre-commit hook

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).
  • Ensure the files under the git-hooks/ directory are executable: chmod 755 git-hooks/*
  • Add test script to your package.json, e.g.
    "scripts": {
        "test": "mocha"
    }
  • Whenever you clone the repository, run git-hooks/install-hooks to symlink the hooks stored in the repository, in git-hooks, to the hidden .git/hooks directory.
#!/usr/bin/env node
var fs = require("fs");
var path = require("path");
var gitHookDir = path.resolve(__dirname, '..', '.git', 'hooks');
["applypatch-msg", "commit-msg", "post-commit", "post-receive", "post-update", "pre-applypatch", "pre-commit",
"prepare-commit-msg", "pre-rebase", "update"].forEach(function (hook) {
var hookInSourceControl = path.resolve(__dirname, hook);
if (fs.existsSync(hookInSourceControl)) {
var hookInHiddenDirectory = path.resolve(gitHookDir, hook);
if (fs.existsSync(hookInHiddenDirectory)) {
fs.unlinkSync(hookInHiddenDirectory);
}
fs.symlinkSync(path.relative(gitHookDir, hookInSourceControl), hookInHiddenDirectory);
}
});
#!/usr/bin/env node
var npm = require('npm');
npm.load(function (err) {
if (err) throw err;
// run `npm test`
npm.commands.test(function(err) {
if (err) failed('test', err);
// Chain additional commands...
//npm.commands['run-script'](['foo'], function(err) {
// if (err) failed('foo', err);
//});
});
});
function failed(msg, err) {
console.error('\npre-commit failure:', msg, err);
process.exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment