-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.js
More file actions
97 lines (87 loc) · 2.48 KB
/
Copy pathcli.js
File metadata and controls
97 lines (87 loc) · 2.48 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env node
import { resolve, dirname } from "node:path";
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { pathToFileURL } from "node:url";
async function main() {
const command = process.argv[2];
switch (command) {
case "list":
await listCommand();
break;
case "apply":
await applyCommand();
break;
case undefined:
process.stderr.write(`supported commands: list, apply\n`);
process.exit(-1);
break;
default:
process.stderr.write(`no such command ${command}\n`);
process.exit(-1);
}
}
function normalizeScenario(scenario) {
// always include an empty env by default, so that it's convenient to pass
// `${{ matrix.env }}` in github actions
return { env: {}, ...scenario };
}
async function listCommand() {
const config = await loadConfig();
process.stdout.write(
JSON.stringify({
name: config.scenarios.map((s) => s.name),
include: config.scenarios.map((s) => normalizeScenario(s)),
})
);
}
async function applyCommand() {
const scenarioName = process.argv[3];
if (!scenarioName) {
process.stderr.write(`apply command needs to be passed a scenario name\n`);
process.exit(-1);
}
const config = await loadConfig();
const scenario = config.scenarios.find((s) => s.name === scenarioName);
if (!scenario) {
process.stderr.write(`No such scenario "${scenarioName}"\n`);
process.exit(-1);
}
await applyScenario(scenario);
}
async function loadConfig() {
const { default: config } = await import(
pathToFileURL(resolve(process.cwd(), ".try.mjs"))
);
return config;
}
async function applyScenario(scenario) {
const pkgJSONPath = resolve(process.cwd(), "package.json");
const pkg = JSON.parse(readFileSync(pkgJSONPath, "utf8"));
if (scenario.npm) {
for (let key of [
"devDependencies",
"dependencies",
"peerDependencies",
"overrides",
]) {
if (scenario.npm[key]) {
if (!pkg[key]) {
pkg[key] = {};
}
Object.assign(pkg[key], scenario.npm[key]);
}
}
}
if (scenario.files) {
for (let [filename, content] of Object.entries(scenario.files)) {
const fullName = resolve(process.cwd(), filename);
mkdirSync(dirname(fullName), {
recursive: true,
});
writeFileSync(fullName, content);
}
}
writeFileSync(pkgJSONPath, JSON.stringify(pkg, null, 2));
process.stdout.write(`Applied scenario ${scenario.name}\n`);
}
await main();