-
Notifications
You must be signed in to change notification settings - Fork 28
/
git.mjs
69 lines (61 loc) · 1.56 KB
/
git.mjs
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
"use strict";
import { exec } from "child_process";
import path from "path";
function toExecPromise(cmd, timeout) {
if (!timeout) {
timeout = 60000;
}
return new Promise((resolve, reject) => {
const id = setTimeout(() => {
reject(new Error(`Command took too long: ${cmd}`));
proc.kill("SIGTERM");
}, timeout);
const proc = exec(cmd, (err, stdout) => {
clearTimeout(id);
if (err) {
return reject(err);
}
resolve(stdout);
});
});
}
export function git(cmd) {
return toExecPromise(`git ${cmd}`);
}
git.getCurrentBranch = async () => {
const branch = await git(`rev-parse --abbrev-ref HEAD`);
return branch.trim();
};
git.getConfigData = async (configItem) => {
let data;
try {
data = await git(configItem);
} catch (err) {
data = "";
}
return data;
};
git.getBranches = async () => {
const rawBranches = await git("branch --no-color");
const branches = rawBranches
.split("\n")
.map((branch) => branch.replace("*", "").trim())
.reduce((collector, branch) => collector.add(branch), new Set());
return Array.from(branches);
};
git.hasBranch = async (branch) => {
const branches = await git.getBranches();
return branches.includes(branch);
};
git.switchBranch = async (branch) => {
const hasBranch = await git.hasBranch(branch);
if (!hasBranch) {
await git(`checkout -b ${branch}`);
} else {
await git(`checkout ${branch}`);
}
};
git.getRepoName = async () => {
const name = await git("rev-parse --show-toplevel");
return path.basename(name).trim();
};