#!/usr/bin/env node // requires var exec = require('child_process').exec; var path = require('path'); var fs = require('fs'); // some status strings var fail = '\x1B[31mfailed!\x1B[39m'; var ok = '\x1B[32mok\x1B[39m'; var notfound = '\x1B[33mn/a\x1B[39m (no script found)'; var skipped = '\x1B[33mn/a\x1B[39m (skipped)'; // config var projectRoot = '{{projectRoot}}'; // lame templating so this gets populated correctly var config = require(path.join(projectRoot, 'package.json')); var myconfig = config.config && config.config.precommit ? config.config.precommit : undefined; // set up environment var pathKey; var pathSep = process.platform === 'win32' ? ';' : ':'; var env = {}; for (var key in process.env) { if (key.toLowerCase() === 'path') { pathKey = key; } env[key] = process.env[key]; } env[pathKey] = path.join(projectRoot, 'node_modules', '.bin') + pathSep + env[pathKey]; // run the command for the given property function runCmd(prop, done) { var skip = myconfig ? !myconfig[prop] : false; var cmd = config.scripts && config.scripts[prop] ? config.scripts[prop] : prop === 'lint' ? 'jshint .' : undefined; var pad = ''; for (var i = 0; i < (8 - prop.length); i++) { pad += ' '; } process.stdout.write('running ' + prop + ': ' + pad); if (skip) { console.log(skipped); return done(); } if (!cmd) { console.log(notfound); return done(); } cmd = (process.platform === 'win32' ? 'cmd /c ' : 'sh -c ') + '\"' + cmd + '\"'; exec(cmd, { cwd: projectRoot, env: env }, function (err, stdout, stderr) { if (err) { console.log(fail); console.log(stdout); console.log(stderr); exit(err.code, process.exit); } else { console.log(ok); exit(0, done); } }); } // this method shamelessly adapted from https://github.com/cowbody/node-exit function exit(code, callback) { var streams = [process.stdout, process.stderr]; var drainCount = 0; function tryToExit() { if (drainCount === streams.length) { callback(code); } } streams.forEach(function (stream) { if (stream.bufferSize === 0) { drainCount++; } else { stream.write('', 'utf-8', function () { drainCount++; tryToExit(); }); stream.write = function () {}; } }); tryToExit(); } console.log('running pre-commit checks...'); runCmd('lint', function () { runCmd('validate', function () { runCmd('test', process.exit); }); });