Skip to content

stash files before running pre-commit hook to avoid false positives; closes #4 #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 119 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ var spawn = require('cross-spawn')
, which = require('which')
, path = require('path')
, util = require('util')
, tty = require('tty');
, tty = require('tty')
, async = require('async');

/**
* Representation of a hook runner.
Expand Down Expand Up @@ -80,7 +81,7 @@ Hook.prototype.parse = function parse() {
var pre = this.json['pre-commit'] || this.json.precommit
, config = !Array.isArray(pre) && 'object' === typeof pre ? pre : {};

['silent', 'colors', 'template'].forEach(function each(flag) {
['silent', 'colors', 'template', 'stash'].forEach(function each(flag) {
var value;

if (flag in config) value = config[flag];
Expand Down Expand Up @@ -204,37 +205,130 @@ Hook.prototype.initialize = function initialize() {
if (!this.config.run) return this.log(Hook.log.run, 0);
};

/**
* Stashes unstaged changes.
*
* @param {Function} done Callback
* @api private
*/
Hook.prototype._stash = function stash(done) {
var hooked = this;

spawn(hooked.git, ['stash', '--keep-index', '--include-untracked'], {
env: process.env,
cwd: hooked.root,
stdio: [0, 1, 2]
}).once('close', function() {
// a nonzero here may be that there are no unstaged changes.
done();
});
};

/**
* Unstashes changes ostensibly stashed by {@link Hook#_stash}.
*
* @param {Function} done Callback
* @api private
*/
Hook.prototype._unstash = function unstash(done) {
var hooked = this;

spawn(hooked.git, ['stash', 'pop'], {
env: process.env,
cwd: hooked.root,
stdio: [0, 1, 2]
}).once('close', function(code) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might as well supply the done method here directly to eliminate this function call.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not exactly sure what you mean. will rebase in a sec anyway

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have .once('close, function (code) { if (code) done(code); done() }) Couldn't you just write it as

.once('close', done);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe? I'm not sure if async would interpret 0 as an error.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left it this way to be safe

if (code) done(code);
done();
});
};

/**
* Runs a hook script.
*
* @param {string} script Script name (as in package.json)
* @param {Function} done Callback
* @api private
*/
Hook.prototype._runScript = function runScript(script, done) {
var hooked = this;

// There's a reason on why we're using an async `spawn` here instead of the
// `shelljs.exec`. The sync `exec` is a hack that writes writes a file to
// disk and they poll with sync fs calls to see for results. The problem is
// that the way they capture the output which us using input redirection and
// this doesn't have the required `isAtty` information that libraries use to
// output colors resulting in script output that doesn't have any color.
//
spawn(hooked.npm, ['run', script, '--silent'], {
env: process.env,
cwd: hooked.root,
stdio: [0, 1, 2]
}).once('close', function closed(code) {
// failures return an object with message referencing script which failed
// plus its exit code. its exit code will be used to exit this program.
if (code) return done({message: script, code: code});
done();
});
};

/**
* Run the specified hooks.
*
* @api public
*/
Hook.prototype.run = function runner() {
var hooked = this;
var scripts = hooked.config.run.slice(0);

if (!scripts.length) return hooked.exit(0);

function error(msg, code) {
return hooked.log(hooked.format(Hook.log.failure, msg, code));
}

function cleanup(errObj) {
var errObjs = [];
// keep error for reporting
if (errObj) errObjs.push(errObj);

// cleanup; unstash changes before exiting.
if (hooked.config.stash === false) {
done(errObjs);
} else {
hooked._unstash(function(code) {
if (code) errObjs.unshift({
message: '"git stash pop" failed',
code: code
});

done(errObjs);
});
}
}

function done(errObjs) {
// exit with the code of the failed script, or if all scripts exited with
// codes of 0 and "git stash pop" failed, then use its exit code.
if (errObjs.length) return error(errObjs.map(function(err) {
return err.message;
}).join('\n'), errObjs[errObjs.length - 1].code);

(function again(scripts) {
if (!scripts.length) return hooked.exit(0);

var script = scripts.shift();

//
// There's a reason on why we're using an async `spawn` here instead of the
// `shelljs.exec`. The sync `exec` is a hack that writes writes a file to
// disk and they poll with sync fs calls to see for results. The problem is
// that the way they capture the output which us using input redirection and
// this doesn't have the required `isAtty` information that libraries use to
// output colors resulting in script output that doesn't have any color.
//
spawn(hooked.npm, ['run', script, '--silent'], {
env: process.env,
cwd: hooked.root,
stdio: [0, 1, 2]
}).once('close', function closed(code) {
if (code) return hooked.log(hooked.format(Hook.log.failure, script, code));

again(scripts);
});
})(hooked.config.run.slice(0));
hooked.exit(0);
}

function runScripts() {
// run each script in series. upon completion or nonzero exit code,
// the callback is executed
async.eachSeries(scripts, hooked._runScript.bind(hooked), cleanup);
}

if (this.config.stash === false) {
runScripts();
} else {
// attempt to stash changes not on stage
hooked._stash(runScripts);
}
};

/**
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"coverage": "istanbul cover ./node_modules/.bin/_mocha -- test.js",
"example-fail": "echo \"This is the example hook, I exit with 1\" && exit 1",
"example-pass": "echo \"This is the example hook, I exit with 0\" && exit 0",
"example-stash": "echo \"This is the stash hook, I exit with 1 if .stash exists\" && test ! -e .stash && exit 0",
"install": "node install.js",
"test": "mocha test.js",
"test-travis": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- test.js",
Expand All @@ -30,6 +31,7 @@
"homepage": "https://github.com/observing/pre-commit",
"license": "MIT",
"dependencies": {
"async": "1.4.x",
"cross-spawn": "2.0.x",
"which": "1.1.x"
},
Expand Down
18 changes: 18 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,5 +253,23 @@ describe('pre-commit', function () {
hook.config.run = ['example-fail'];
hook.run();
});

it('should stash successfully', function(next) {
// if file ".stash" exists, the test will fail.
var fs = require('fs');
fs.writeFileSync('.stash', '', 'utf8');

var hook = new Hook(function (code, lines) {
fs.unlinkSync('.stash');

assume(code).equals(0);
assume(lines).is.undefined();

next();
}, { ignorestatus: true });

hook.config.run = ['example-stash'];
hook.run();
});
});
});