-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgerrit.js
67 lines (61 loc) · 1.78 KB
/
gerrit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var child_process = require('child_process');
var Ssh2Connection;
var getProcessUsername = function(callback) {
child_process.exec('whoami', function(err, res) {
if (err) callback(err);
else {
res = res.split('\n')[0];
if (res.indexOf('/') != -1) res = res.split('/').pop();
res = res.trim();
callback(null, res);
}
});
};
var ssh2 = function(sshConfig, command, callback) {
if (!Ssh2Connection) Ssh2Connection = require('ssh2');
var connection = new Ssh2Connection();
connection.on('connect', function() {
});
connection.on('ready', function() {
connection.exec(command, function(err, stream) {
if (err) return callback(err);
var result = '';
stream.on('data', function(data, extended) {
result += data.toString();
});
stream.on('end', function() {
callback(null, result);
});
});
});
connection.on('error', function(err) {
callback(err);
});
var doConnect = function() { connection.connect(sshConfig); };
if (sshConfig.username) doConnect();
else getProcessUsername(function(err, username) {
if (err) callback(err);
else {
sshConfig.username = username;
doConnect();
}
});
};
var gerrit = function(sshConfig, command, res, callback) {
command = 'gerrit ' + command;
ssh2(sshConfig, command, function(error, result) {
var errorCode = 'unknown'
if (result && result.indexOf('gerrit: command not found') != -1) {
errorCode = error = 'not-a-gerrit-remote';
}
if (error) {
var err = { errorCode: errorCode, command: command, error: error.toString() };
if (!callback || !callback(err, result)) {
res.json(400, err);
}
} else {
callback(null, result);
}
});
};
module.exports = gerrit;