-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-project-version.mjs
79 lines (70 loc) · 2.03 KB
/
update-project-version.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
70
71
72
73
74
75
76
77
78
79
import fs from "fs";
import readline from "readline";
/**
* Updates the project version in the package.json file based on the provided type.
* Supported types are "patch", "minor", and "major".
*
* @param {string} type - Version type to increase. Must be one of "patch", "minor", or "major".
* @throws {Error} Will throw an error if invalid type provided.
*/
function updateVersion(type) {
// Read package.json
const packageJsonPath = "./package.json";
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
const currentVersion = packageJson.version;
// Get current version
let [major, minor, patch] = currentVersion.split(".").map(Number);
// Update version based on the type
switch (type) {
case "patch": {
patch++;
break;
}
case "minor": {
minor++;
patch = 0; // Reset patch version for a minor update
break;
}
case "major": {
major++;
minor = 0; // Reset minor and patch versions for a major update
patch = 0;
break;
}
default: {
throw new Error(
'❎ Invalid version type. Use "patch", "minor", or "major".'
);
}
}
// Update package.json with the new version
packageJson.version = `${major}.${minor}.${patch}`;
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
const newVersion = packageJson.version;
console.log(
`✅ Successfully updated version: ${currentVersion} → ${newVersion}`
);
}
/**
* Initiates the script prompting the user for a version type and starts the update process afterwards.
*/
function startScript() {
// Create interface to read user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Prompt user for version type
rl.question(
"Which version do you want to update (patch/minor/major)? ",
async (answer) => {
try {
updateVersion(answer.trim());
} catch (error) {
console.error(error.message);
}
rl.close();
}
);
}
startScript();