2014-05-10 10:19:47 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var spawn = require('child_process').spawn,
|
2014-12-03 21:24:00 +00:00
|
|
|
ParentCommand = require('./base').Command,
|
2014-12-04 20:22:14 +00:00
|
|
|
inherits = require('util').inherits,
|
|
|
|
utils = require('../utils');
|
2014-05-10 10:19:47 +00:00
|
|
|
|
|
|
|
function Command(params) {
|
|
|
|
params = params || {};
|
|
|
|
ParentCommand.call(this, params);
|
|
|
|
this.cwd = params.cwd;
|
|
|
|
}
|
|
|
|
|
2014-12-03 21:24:00 +00:00
|
|
|
exports.Command = Command;
|
2014-05-10 10:19:47 +00:00
|
|
|
|
|
|
|
inherits(Command, ParentCommand);
|
|
|
|
|
2014-12-02 21:09:05 +00:00
|
|
|
/**
|
|
|
|
* Executes `params.cmd` with `params.args` and `params.options`
|
|
|
|
*/
|
|
|
|
Command.prototype.run = function(params, callback) {
|
2014-05-10 10:19:47 +00:00
|
|
|
var self = this,
|
2014-12-14 20:04:00 +00:00
|
|
|
stdout = self.collectOut ? '' : null;
|
2015-05-03 21:53:11 +00:00
|
|
|
|
2014-12-02 21:09:05 +00:00
|
|
|
if (!params.cmd) return callback(new Error('`cmd` is not set'));
|
|
|
|
if (!params.args) return callback(new Error('`args` is not set'));
|
2014-12-04 20:22:14 +00:00
|
|
|
callback = utils.once(callback);
|
2014-12-02 21:09:05 +00:00
|
|
|
params.options = params.options || {};
|
|
|
|
params.options.cwd = params.options.cwd || this.cwd;
|
2015-05-03 21:53:11 +00:00
|
|
|
|
2014-12-02 21:09:05 +00:00
|
|
|
var cmd = spawn(params.cmd, params.args, params.options);
|
2015-05-03 21:53:11 +00:00
|
|
|
|
|
|
|
if (self.emitIn) {
|
|
|
|
self.emit('stdin', params.cmd + ' ' + params.args.join(' '));
|
|
|
|
}
|
|
|
|
|
2014-05-10 10:19:47 +00:00
|
|
|
cmd.stdout.on('data', function(data) {
|
2014-12-14 20:04:00 +00:00
|
|
|
if (self.emitOut) self.emit('stdout', data);
|
|
|
|
if (self.collectOut) stdout += data;
|
2014-05-10 10:19:47 +00:00
|
|
|
});
|
2015-05-03 21:53:11 +00:00
|
|
|
|
2014-05-10 10:19:47 +00:00
|
|
|
cmd.stderr.on('data', function(data) {
|
2014-12-04 20:09:43 +00:00
|
|
|
callback(new Error('Spawned command outputs to stderr: ' + data));
|
2014-05-10 10:19:47 +00:00
|
|
|
cmd.kill();
|
|
|
|
});
|
2015-05-03 21:53:11 +00:00
|
|
|
|
2014-12-04 20:09:43 +00:00
|
|
|
cmd.on('close', function(code) {
|
|
|
|
var err = null;
|
|
|
|
if (code !== 0) err = new Error(
|
|
|
|
'Spawned command exits with non-zero code: ' + code
|
|
|
|
);
|
|
|
|
callback(err, stdout);
|
2014-05-10 10:19:47 +00:00
|
|
|
});
|
2015-05-03 21:53:11 +00:00
|
|
|
|
2014-05-10 10:19:47 +00:00
|
|
|
return cmd;
|
|
|
|
};
|