-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild-id.mjs
More file actions
76 lines (65 loc) · 1.92 KB
/
build-id.mjs
File metadata and controls
76 lines (65 loc) · 1.92 KB
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
import fs from "fs";
import path from "path";
import { execFile } from "child_process";
function lastCommitId(dir) {
return new Promise((resolve, reject) => {
const gitArgs = [
`--git-dir=${path.join(dir, ".git")}`,
`--work-tree=${dir}`,
"rev-parse",
"HEAD",
];
execFile("git", gitArgs, (err, stdout, stderr) => {
if (err) return reject(err);
if (stderr) return reject(String(stderr).trim());
if (stdout) return resolve(String(stdout).trim());
return reject(
new Error(`No output from command: git ${gitArgs.join(" ")}`)
);
});
});
}
function gitDescribe(dir) {
return new Promise((resolve, reject) => {
const gitArgs = [
`--git-dir=${path.join(dir, ".git")}`,
`--work-tree=${dir}`,
"describe",
"--tags",
"--abbrev=1"
];
execFile("git", gitArgs, (err, stdout, stderr) => {
if (err) return reject(err);
if (stderr) return reject(String(stderr).trim());
if (stdout) return resolve(String(stdout).trim());
return reject(
new Error(`No output from command: git ${gitArgs.join(" ")}`)
);
});
});
}
function findDotGit(inputDir, maxAttempts = 999) {
// inputDir may not be the project root so look for .git dir in parent dirs too
let dir = inputDir;
const { root } = path.parse(dir);
let attempts = 0; // protect against infinite tight loop if libs misbehave
while (dir !== root && attempts < maxAttempts) {
attempts += 1;
try {
fs.accessSync(path.join(dir, ".git"), (fs.constants || fs).R_OK);
break;
} catch (_) {
dir = path.dirname(dir);
}
}
if (dir === root || attempts >= maxAttempts) {
dir = inputDir;
}
return dir;
}
async function determineBuildId({ dir } = { dir: "." }) {
let topDir = findDotGit(dir);
let version = gitDescribe(topDir);
return version;
}
export { determineBuildId, findDotGit, lastCommitId, gitDescribe };