Skip to content

Instantly share code, notes, and snippets.

@mklabs
Created September 28, 2011 01:25
Show Gist options
  • Save mklabs/1246769 to your computer and use it in GitHub Desktop.
Save mklabs/1246769 to your computer and use it in GitHub Desktop.
npm test as git/hg hooks

Run npm test, and prevent commits if tests fail.

git

replace .git/hooks/pre-commit hook by these lines. It'll run npm test and prevent commits on test fail

To enable this hook, make this file executable by chmod +x .git/hooks/pre-commit.

http://progit.org/book/ch7-3.html

git init
curl https://raw.github.com/gist/1246769/pre-commit >> .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
git commit

hg

http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html#sec:hook:simple

hg init
mkdir .hg/hooks
curl https://raw.github.com/gist/1246769/pre-commit >> .hg/hooks/pre-commit
chmod +x .hg/hooks/pre-commit

echo '[hooks]' >> .hg/hgrc
echo 'pre-commit = ./.hg/pre-commit' >> .hg/hgrc
cat .hg/hgrc

hg commit

note: the hg hook for precommit is actually pre-commit, not precommit.

todo: the same for jshint. NO COMMIT IF NO LINT FREE.

#!/usr/bin/env node
var npm = nrequire('npm');
if (npm) return npm.load(function(e, n) {
this.commands.test(function(e) {
process.exit(e ? 1 : 0);
});
});
// npm not installed locally, spawn process instead.
// basically the same, but less pretty.
var spawn = require('child_process').spawn,
ch = spawn('npm', ['test']);
ch.stdout.pipe(process.stdout, {end: false});
ch.stderr.pipe(process.stderr);
ch.on('exit', function (code) {
process.exit(code ? 1 : 0);
});
function nrequire(m) {
var n;
try { n = require(m); }
catch(e) { console.log('please, install ' + m + ' locally to be able to use it programmatically. will spawn process instead. \n'); }
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment