-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
setPackageManager.cjs
72 lines (60 loc) · 2.26 KB
/
setPackageManager.cjs
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
const { scripts, config } = require("../../package.json");
const { execSync } = require("child_process");
const newPackageManager = process.argv[2];
const packageManagers = ["pnpm", "npm", "yarn"];
if (config?.packageManager) {
const isAlone = Object.keys(config).length == 1;
if (isAlone) {
execSync("npm pkg delete config");
} else {
execSync("npm pkg delete config.packageManager");
}
}
if (!newPackageManager) {
errorMessage("Please specify a package manager as an argument.");
}
if (!packageManagers.includes(newPackageManager)) {
errorMessage("Please specify a valid package manager");
}
// Push dynamic entry for backward compatibility
packageManagers.push("$npm_package_config_packageManager");
const replacementKey = "NEW_PACKAGE_MANAGER";
console.log(" Updating package.json scripts...");
for (const key in scripts) {
let command = scripts[key];
// First, replace the package manager with NEW_PACKAGE_MANAGER
// We have to do this as pnpm and npm are similar
packageManagers.forEach((oldManger) => {
command = command.replaceAll(`${oldManger} `, `${replacementKey} `);
command = command.replaceAll(`${oldManger}:`, `${replacementKey}:`);
});
// Now we put the new package manager in place
command = command.replaceAll(`${replacementKey} `, `${newPackageManager} `);
command = command.replaceAll(`${replacementKey}:`, `${newPackageManager}:`);
execSync(`npm pkg set scripts.${key}="${command}"`);
}
sucessMessage();
function sucessMessage() {
console.log("\n");
console.log(cyan(` Set package manager to ${bold(newPackageManager)}`));
console.log("");
}
function errorMessage(message) {
const randomPackageManager = packageManagers[Math.floor(Math.random() * packageManagers.length)];
console.error("\n");
console.error(red(` ${message}`));
console.error("");
console.error(` Valid options are: ${bold(packageManagers.join(", "))}`);
console.error(` Example: ${cyan(`${randomPackageManager} setPackageManager ${randomPackageManager}`)}`);
console.error("\n");
process.exit(1);
}
function cyan(text) {
return `\x1b[36m${text}\x1b[0m`;
}
function red(text) {
return `\x1b[31m${text}\x1b[0m`;
}
function bold(text) {
return `\x1b[1m${text}\x1b[0m`;
}