This repository was archived by the owner on May 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathgit.js
80 lines (68 loc) · 2.07 KB
/
git.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
68
69
70
71
72
73
74
75
76
77
78
79
80
var os = require('os')
, fs = require('fs')
, splitter = require('stream-splitter')
, spawn = require('child_process').spawn;
function buildGitUrl(user, repo) {
return 'https://github.com/' + user + '/' + repo + '.git';
}
function randomChars(length) {
var a = 97;
var result = "";
for (var i=0; i<length; i++) {
result += String.fromCharCode(a + Math.floor(Math.random() * 26));
}
return result;
}
function buildTmpDirPath() {
return '/tmp/line-count-clone-' + randomChars(8);
}
function deleteFolderRecursive(path) {
if(fs.existsSync(path)) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
function execGitCloneCmd(gitUrl, clonePath, socket, onSuccess, onError) {
var proc = spawn('git', ['clone', '-v', gitUrl, clonePath]);
var stdoutLines = proc.stdout.pipe(splitter("\n"));
var stderrLines = proc.stderr.pipe(splitter("\n"));
stdoutLines.encoding = "utf-8";
stderrLines.encoding = "utf-8";
stdoutLines.on("token", function(line) {
socket.emit('console-output', line);
});
stderrLines.on("token", function(line) {
socket.emit('console-output', line);
});
proc.on("close", function(code) {
if (code != 0) {
socket.emit('console-output', "ERROR: git clone failed. Exit code = " + code);
onError();
} else {
onSuccess(clonePath, socket);
}
});
}
function cleanup(clonePath, socket) {
socket.emit("console-output", "Cleaning up...");
deleteFolderRecursive(clonePath);
};
var Git = {
cloneRepo: function(user, repo, socket, onSuccessBuilder) {
var gitUrl = buildGitUrl(user, repo);
var clonePath = buildTmpDirPath();
var cleanupFn = function() {
cleanup(clonePath, socket);
};
var onSuccess = onSuccessBuilder(cleanupFn);
execGitCloneCmd(gitUrl, clonePath, socket, onSuccess, cleanupFn);
}
};
module.exports = Git;