generated from TheBookKnight/nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (42 loc) · 1.51 KB
/
index.js
File metadata and controls
53 lines (42 loc) · 1.51 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
const fs = require('fs');
const childProcess = require('child_process');
const path = require('path');
function getShortGitSHA() {
return childProcess.execSync('git rev-parse --short HEAD').toString().trim();
}
function readPackageJson(filePath = './package.json') {
const pkgPath = path.resolve(process.cwd(), filePath);
if (!fs.existsSync(pkgPath)) {
throw new Error('package.json not found in the current working directory.');
}
const raw = fs.readFileSync(pkgPath);
return JSON.parse(raw);
}
function generateGitVersion(filePath, options = {}) {
const sha = getShortGitSHA();
const pkg = readPackageJson(filePath);
if (!pkg.version) {
throw new Error('The "version" key is missing in package.json.');
}
const baseVersion = pkg.version.split('-')[0]; // remove any pre-release suffix
let suffix = sha;
if (options.includeBranch) {
const branch = getGitBranch()
.replace(/\//g, '-') // replace slashes in branch name for safety
// eslint-disable-next-line no-useless-escape
.replace(/[^\w\-]/g, ''); // remove any unsafe characters
suffix = `${branch}.${sha}`;
}
const newVersion = `${baseVersion}-${suffix}`;
if (options.outputJson) {
return JSON.stringify({ 'version': newVersion })
} else {
return newVersion;
}
}
function getGitBranch() {
return childProcess.execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
}
module.exports = {
generateGitVersion,
};