Skip to content
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

solve #306, and bin in $PATH make sense now #307

Closed
wants to merge 15 commits into from
Closed
20 changes: 17 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ var spawn = require('child_process').spawn;
var path = require('path');
var dirname = path.dirname;
var basename = path.basename;
var fs = require('fs');

/**
* Expose the root command.
Expand Down Expand Up @@ -460,13 +461,26 @@ Command.prototype.executeSubCommand = function(argv, args, unknown) {
var dir = dirname(argv[1]);
var bin = basename(argv[1], '.js') + '-' + args[0];

// check for ./<bin> first
// prefer local `./<bin>` to bin in the $PATH
var local = path.join(dir, bin);
try {
// for versions before node v0.8 when there weren't `fs.existsSync`
if (fs.statSync(local).isFile()) {
bin = local;
}
} catch (e) {}

// run it
args = args.slice(1);
args.unshift(local);
var proc = spawn('node', args, { stdio: 'inherit', customFds: [0, 1, 2] });

var proc;
if (process.platform !== 'win32') {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

With the commit, bin file must have shebang itself

proc = spawn(bin, args, { stdio: 'inherit'});
} else {
args.unshift(local);
proc = spawn(process.execPath, args, { stdio: 'inherit'});
}

proc.on('error', function(err) {
if (err.code == "ENOENT") {
console.error('\n %s(1) does not exist, try --help\n', bin);
Expand Down
20 changes: 20 additions & 0 deletions test/test.command.executableSubcommand.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var program = require('../')
, util = require('util')
, should = require('should');

var oldError = console.error;
var err = '';
console.error = function (tpl, s) {
err = util.format(tpl, s);
};
program
.command('exec [options]', 'this is my command');

program.parse('node test exec a'.split(' '));

program.runningCommand.on('error', function() {
err.should.equal('\n test-exec(1) does not exist, try --help\n');
});

// @todo test `EACCES` error