diff --git a/git.js b/git.js index 9651d88..7fedf87 100644 --- a/git.js +++ b/git.js @@ -1,7 +1,5 @@ // imports -var fs = require('fs'); -var path = require('path'); -var exec = require('child_process').exec; +var spawn = require('child_process').spawn; // Class Git var Git = module.exports = function (options) { @@ -12,7 +10,7 @@ var Git = module.exports = function (options) { this.cwd = options.cwd || process.cwd(); delete options.cwd; - this.args = Git.optionsToString(options); + this.args = Git.optionsToArray(options); }; // git.exec(command [[, options], args ], callback) @@ -24,24 +22,56 @@ Git.prototype.exec = function (command, options, args, callback) { args = []; } else if (arguments.length == 3) { args = arguments[1]; - options = []; + options = {}; } - args = args.join(' '); - options = Git.optionsToString(options) + // Put all the args and options together and send as one array to spawn. + var cmdArgs = this.args + .concat(command) + .concat(Git.optionsToArray(options)) + .concat(args); + + this.spawnCommand(this.binary, cmdArgs, callback); +}; + +/** + * Spawns command + * + * @param {string} binary + * @param {Array} cmdArgs + * @param {function} callback + */ +Git.prototype.spawnCommand = function(binary, cmdArgs, callback) { + var gitproc = spawn(binary, cmdArgs, { cwd: this.cwd }), + output = '', + errorOutput = ''; + + // collect stdout + gitproc.stdout.on('data', function(data) { + output += data; + }); + + // collect stderr + gitproc.stderr.on('data', function(data) { + errorOutput += data; + }); - var cmd = this.binary + ' ' + this.args + ' ' + command + ' ' + options + ' ' - + args; + gitproc.on('close', function(code) { + if (code === 0) { + callback(null, output); + } + else { + callback(new Error(errorOutput), output); + } + }); - exec(cmd, { - cwd: this.cwd - }, function (err, stdout, stderr) { - callback(err, stdout); + gitproc.on('error', function(err) { + callback(err); }); }; -// converts an object that contains key value pairs to a argv string -Git.optionsToString = function (options) { +// converts an object that contains key value pairs to a args array suitable for child_process.spawn +Git.optionsToArray = function (options) { var args = []; for (var k in options) { @@ -61,6 +91,5 @@ Git.optionsToString = function (options) { args.push('--'+k+'='+val); } } - - return args.join(' '); + return args; };