Skip to content
Open
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
63 changes: 46 additions & 17 deletions git.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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)
Expand All @@ -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) {
Expand All @@ -61,6 +91,5 @@ Git.optionsToString = function (options) {
args.push('--'+k+'='+val);
}
}

return args.join(' ');
return args;
};