-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract-semver.js
54 lines (47 loc) · 1.72 KB
/
extract-semver.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
'use strict'
let rawSemver = process.argv[2];
const type = process.argv[3];
function isValidSemver(version) {
// Remove leading 'v' if present
if (version.startsWith('v')) {
version = version.slice(1);
}
const semverRegex = /^([0-9]+)\.([0-9]+)\.([0-9]+)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
return semverRegex.test(version);
}
if (rawSemver === undefined || rawSemver === null) {
throw new Error(`Input of first arg is undefined! Input a valid semver.`);
} else if (typeof rawSemver !== 'string') {
throw new Error(`Input must be a string! Got ${typeof rawSemver}`);
} else if (!isValidSemver(rawSemver)) {
throw new Error(`Input ${rawSemver} is not a valid semver format`);
}
if (
type === undefined ||
type === null ||
(type !== 'minor' && type !== 'patch' && type !== 'major')
) {
throw new Error('You must define a type of either "major" "minor" or "patch" as the second argument.');
}
function getSemverPart(semver, part) {
// Remove leading 'v' if present
if (semver.startsWith('v')) {
semver = semver.slice(1);
}
const semverRegex = /^([0-9]+)\.([0-9]+)\.([0-9]+)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
const match = semver.match(semverRegex);
if (!match) {
throw new Error('Invalid semver format');
}
switch (part) {
case 'major':
return parseInt(match[1], 10);
case 'minor':
return parseInt(match[2], 10);
case 'patch':
return parseInt(match[3], 10);
default:
throw new Error('Invalid part specified. Use "major", "minor" or "patch".');
}
}
process.stdout.write(getSemverPart(rawSemver, type).toString());