-
Notifications
You must be signed in to change notification settings - Fork 54
/
git_client.js
65 lines (58 loc) · 1.91 KB
/
git_client.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
const simpleGit = require('simple-git/promise');
const path = require('path');
const url = require('url');
const fs = require('fs');
function getRepoName(repoUrl) {
const parsed = url.parse(repoUrl);
return path.basename(parsed.path);
}
/**
* Retrieve the base git repo URL from a provided URL.
*
* A URL could contain a hash, which we're interpreting as a branch/tag separator,
* we shouldn't include this.
* */
function cleanupRepoUrl(repoUrl) {
const parsed = url.parse(repoUrl);
return `${parsed.protocol}//${parsed.host}${parsed.path}`;
}
/**
* Retrieve the options for the clone, given the URL.
*
* If the URL has a hash at the end of it then this is used as the branch name.
*/
function getCloneOptionsForRepo(repoUrl) {
let cloneOptions = ['--depth', 1, '--single-branch'];
const parsed = url.parse(repoUrl);
if (parsed.hash) {
// From experimenting, parsed.hash starts with a hash symbol. Just in case.
const branchName = parsed.hash[0] === '#' ? parsed.hash.substring(1) : parsed.hash;
cloneOptions = cloneOptions.concat(['--branch', branchName]);
}
return cloneOptions;
}
exports.latestLog = repoPath =>
simpleGit(repoPath)
.log(['--max-count', 1])
.catch(err => console.error(err));
exports.cloneRepo = (repoUrl, targetDir) =>
new Promise((resolve, reject) => {
// Ensure directory exists
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir);
}
const repoName = getRepoName(repoUrl);
const clonePath = path.join(targetDir, repoName);
const cleanRepoUrl = cleanupRepoUrl(repoUrl);
const cloneOpts = getCloneOptionsForRepo(repoUrl);
simpleGit(__dirname)
// Disable terminal prompts, so Git does not prompt for username/password on a clone.
.clone(cleanRepoUrl, clonePath, cloneOpts)
.then(() =>
resolve({
localDir: clonePath,
repoName: cleanRepoUrl
})
)
.catch(reject);
});