Skip to content

Commit

Permalink
Add support for shebangs.
Browse files Browse the repository at this point in the history
  • Loading branch information
satazor committed Aug 28, 2014
1 parent 126bc26 commit e240daa
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
26 changes: 26 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
var fs = require('fs');
var cp = require('child_process');

var isWin = process.platform === 'win32';
Expand Down Expand Up @@ -36,8 +37,26 @@ function escapeCommand(command) {
return command;
}

function readShebang(command) {
var buffer = new Buffer(150);
var fd;
var match;

try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, 150, 0);
} catch (e) {
return null;
}

match = buffer.toString().trim().match(/\#\!\/usr\/bin\/env ([^\r\n]+)/i);

return match && match[1];
}

function spawn(command, args, options) {
var applyQuotes;
var shebang;

// Use node's spawn if not on windows
if (!isWin) {
Expand All @@ -51,6 +70,13 @@ function spawn(command, args, options) {
return escapeArg(arg, applyQuotes);
});

// Detect & add support for shebangs in windows
shebang = readShebang(command);
if (shebang) {
args.unshift(command);
command = shebang;
}

// Use cmd.exe
args = ['/s', '/c', '"' + command + (args.length ? ' ' + args.join(' ') : '') + '"'];
command = 'cmd';
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/shebang
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

process.stdout.write('shebang works!');
10 changes: 10 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ var expect = require('expect.js');
var isWin = process.platform === 'win32';

describe('cross-spawn', function () {
it('should support shebang in executables', function (next) {
buffered(__dirname + '/fixtures/shebang', function (err, data, code) {
expect(err).to.not.be.ok();
expect(code).to.be(0);
expect(data).to.equal('shebang works!');

next();
});
});

it('should expand using PATHEXT properly', function (next) {
if (!isWin) {
return next();
Expand Down

0 comments on commit e240daa

Please sign in to comment.