-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathjsenv_cli.js
executable file
·400 lines (390 loc) · 12 KB
/
jsenv_cli.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/usr/bin/env node
// see https://docs.npmjs.com/cli/v8/commands/npm-init#description
import { ANSI, createTaskLog, UNICODE } from "@jsenv/humanize";
import {
ensurePathnameTrailingSlash,
urlToFilename,
urlToRelativeUrl,
} from "@jsenv/urls";
import { execSync } from "node:child_process";
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
statSync,
writeFileSync,
} from "node:fs";
import { relative } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { parseArgs } from "node:util";
import prompts from "prompts";
// not using readdir to control order
const availableTemplateNameArray = [
"web",
"web-components",
"web-react",
"web-preact",
"node-package",
];
const options = {
help: {
type: "boolean",
},
web: {
type: "boolean",
},
["web-components"]: {
type: "boolean",
},
["web-react"]: {
type: "boolean",
},
["web-preact"]: {
type: "boolean",
},
["node-package"]: {
type: "boolean",
},
};
const { values, positionals } = parseArgs({
options,
allowPositionals: true,
});
if (values.help) {
console.log(`@jsenv/cli: Init jsenv in a directory.
Usage: npx @jsenv/cli <dir> [options]
https://github.com/jsenv/core/tree/main/packages/related/cli
<dir> Where to install jsenv files; Otherwise you'll be prompted to select.
Options:
--help Display this message.
--web Consider directory as "web" project; Otherwise you'll be prompted to select.
--web-components Consider directory as "web-components" project; Otherwise you'll be prompted to select.
--web-react Consider directory as "web-react" project; Otherwise you'll be prompted to select.
--web-preact Consider directory as "web-preact" project; Otherwise you'll be prompted to select.
--node-package Consider directory as "node-package" project; Otherwise you'll be prompted to select.
`);
process.exit(0);
}
console.log("Welcome in jsenv CLI; this will install jsenv in a directory.");
const commands = [];
const cwdUrl = ensurePathnameTrailingSlash(pathToFileURL(process.cwd()));
let directoryUrl;
dir: {
const directoryPathFromArg = positionals[0];
if (directoryPathFromArg) {
directoryUrl = ensurePathnameTrailingSlash(
new URL(directoryPathFromArg, cwdUrl),
);
console.log(`${UNICODE.OK} Enter a directory: ${directoryPathFromArg}`);
break dir;
}
const result = await prompts(
{
type: "text",
name: "directory",
message: `Directory: ${ANSI.color(`(Return to use current directory)`, ANSI.GREY)}`,
initial: ".",
},
{
onCancel: () => {
console.log("Aborted, can be resumed any time");
process.exit(0);
},
},
);
let { directory } = result;
directoryUrl = ensurePathnameTrailingSlash(new URL(directory, cwdUrl));
}
const runWithChildProcess = (command) => {
console.log(command);
execSync(command, {
cwd: directoryUrl,
stdio: [0, 1, 2],
});
};
if (directoryUrl.href !== cwdUrl.href) {
const dir = relative(fileURLToPath(cwdUrl), fileURLToPath(directoryUrl));
commands.push({
label: `cd ${dir}`,
run: () => {},
});
}
let templateName;
template: {
const templateNameFromArg = availableTemplateNameArray.find(
(availableTemplateName) => values[availableTemplateName],
);
if (templateNameFromArg) {
templateName = templateNameFromArg;
console.log(`${UNICODE.OK} Select a template: ${templateNameFromArg}`);
break template;
}
const result = await prompts(
[
{
type: "select",
name: "templateName",
message: "Select a template:",
initial: 0,
choices: availableTemplateNameArray.map((availableTemplateName) => {
return {
title: availableTemplateName,
value: availableTemplateName,
};
}),
},
],
{
onCancel: () => {
console.log("Aborted, can be resumed any time");
process.exit(0);
},
},
);
templateName = result.templateName;
}
write_files: {
const writeFilesTask = createTaskLog(`init jsenv in "${directoryUrl}"`);
const mergeTwoIgnoreFileContents = (left, right) => {
const leftLines = String(left)
.split("\n")
.map((l) => l.trim());
const rightLines = String(right)
.split("\n")
.map((l) => l.trim());
let finalContent = left;
for (const rightLine of rightLines) {
if (!leftLines.includes(rightLine)) {
finalContent += "\n";
finalContent += rightLine;
}
}
return finalContent;
};
const overrideHandlers = {
"package.json": (existingContent, templateContent) => {
const existingPackage = JSON.parse(existingContent);
const templatePackage = JSON.parse(templateContent);
const override = (left, right, { parentKey, allowedKeys }) => {
if (right === null) {
return left === undefined ? null : left;
}
if (Array.isArray(right)) {
if (Array.isArray(left)) {
for (const valueFromRight of right) {
if (!left.includes(valueFromRight)) {
left.push(valueFromRight);
}
}
return left;
}
return left === undefined ? right : left;
}
if (typeof right === "object") {
if (left && typeof left === "object") {
const keysToVisit = allowedKeys || Object.keys(right);
for (const keyToVisit of keysToVisit) {
const rightValue = right[keyToVisit];
if (rightValue === undefined) {
continue;
}
const leftValue = left[keyToVisit];
const finalValue = override(leftValue, rightValue, {
parentKey: keyToVisit,
});
left[keyToVisit] = finalValue;
if (parentKey === "scripts" && keyToVisit === "start") {
commands.push({
label: "npm start",
run: () => runWithChildProcess("npm start"),
});
}
}
return left;
}
return left === undefined ? right : left;
}
return left === undefined ? right : left;
};
const existingDependencies = existingPackage.dependencies
? { ...existingPackage.dependencies }
: {};
const existingDevDependencies = existingPackage.devDependencies
? { ...existingPackage.devDependencies }
: {};
override(existingPackage, templatePackage, {
allowedKeys: ["scripts", "dependencies", "devDependencies"],
});
const finalDependencies = existingPackage.dependencies || {};
const finalDevDependencies = existingPackage.devDependencies || {};
if (
JSON.stringify(existingDependencies) !==
JSON.stringify(finalDependencies) ||
JSON.stringify(existingDevDependencies) !==
JSON.stringify(finalDevDependencies)
) {
commands.push({
label: "npm install",
run: () => runWithChildProcess("npm install"),
});
}
if (existingContent.startsWith("{\n")) {
return JSON.stringify(existingPackage, null, " ");
}
return JSON.stringify(existingPackage);
},
".gitignore": mergeTwoIgnoreFileContents,
".eslintignore": mergeTwoIgnoreFileContents,
};
const templateSourceDirectoryUrl = new URL(
`./template-${templateName}/`,
import.meta.url,
);
const isWebAndHaveRootHtmlFile = (() => {
if (!templateName.startsWith("web")) {
return false;
}
if (existsSync(new URL("./index.html", directoryUrl))) {
return true;
}
if (existsSync(new URL("./main.html", directoryUrl))) {
return true;
}
return false;
})();
const copyDirectoryContent = (fromDirectoryUrl, toDirectoryUrl) => {
const directoryEntryNameArray = readdirSync(fromDirectoryUrl);
for (const directoryEntryName of directoryEntryNameArray) {
if (
directoryEntryName === ".jsenv" ||
directoryEntryName === "dist" ||
directoryEntryName === "node_modules" ||
directoryEntryName === "readme.md"
) {
continue;
}
const fromUrl = new URL(directoryEntryName, fromDirectoryUrl);
const toUrl = new URL(
directoryEntryName === "_gitignore" ? ".gitignore" : directoryEntryName,
toDirectoryUrl,
);
const fromStat = statSync(fromUrl);
if (fromStat.isDirectory()) {
if (directoryEntryName === "src" || directoryEntryName === "tests") {
if (existsSync(toUrl) && readdirSync(toUrl).length > 0) {
// copy src and tests if they don't exists or are empty
continue;
}
if (isWebAndHaveRootHtmlFile) {
// for web the presence of index.html or main.html at the root
// prevent src/ content from being copied
continue;
}
}
copyDirectoryContent(
ensurePathnameTrailingSlash(fromUrl),
ensurePathnameTrailingSlash(toUrl),
);
continue;
}
let templateFileContent = String(readFileSync(fromUrl));
if (isWebAndHaveRootHtmlFile) {
if (directoryEntryName === ".eslintrc.cjs") {
templateFileContent = templateFileContent.replaceAll(
'files: ["./src/**"]',
'files: ["./index.html", "./src/**"]',
);
} else {
templateFileContent = templateFileContent.replaceAll(
'new URL("../src/", import.meta.url)',
'new URL("../", import.meta.url)',
);
}
}
if (!existsSync(toUrl)) {
const parentDirectoryUrl = new URL("./", toUrl);
if (!existsSync(parentDirectoryUrl)) {
mkdirSync(parentDirectoryUrl, { recursive: true });
}
if (directoryEntryName === "package.json") {
commands.push({
label: "npm install",
run: () => runWithChildProcess("npm install"),
});
commands.push({
label: "npm start",
run: () => runWithChildProcess("npm start"),
});
const packageTemplateObject = JSON.parse(templateFileContent);
packageTemplateObject.name = urlToFilename(directoryUrl);
const packageString = JSON.stringify(
packageTemplateObject,
null,
" ",
);
writeFileSync(toUrl, packageString);
} else {
writeFileSync(toUrl, templateFileContent);
}
continue;
}
const relativeUrl = urlToRelativeUrl(fromUrl, templateSourceDirectoryUrl);
const overrideHandler = overrideHandlers[relativeUrl];
if (!overrideHandler) {
// when there is no handler the file is kept as is
continue;
}
const existingContent = String(readFileSync(toUrl));
const finalContent = overrideHandler(
existingContent,
templateFileContent,
);
writeFileSync(toUrl, finalContent);
}
};
copyDirectoryContent(
new URL(templateSourceDirectoryUrl),
new URL(directoryUrl),
);
writeFilesTask.done();
}
run_commands: {
if (commands.length === 0) {
break run_commands;
}
let message;
if (commands.length === 1) {
console.log(`----- 1 command to run -----
${commands[0].label}
---------------------------`);
// we can't run cd for the parent terminal
// so we'll just print the command in that case
// and user will have to run it if he want to go into the
// directory
if (commands[0].label.startsWith("cd")) {
console.log("Done, thank you");
process.exit(0);
}
message = "Can we run the command";
} else {
console.log(`----- ${commands.length} commands to run -----
${commands.map((c) => c.label).join("\n")}
-----------------------------`);
message = "Can we run the commands";
}
const { value } = await prompts({
type: "confirm",
name: "value",
message,
initial: true,
});
if (!value) {
console.log("Done, thank you");
process.exit(0);
}
for (const command of commands) {
await command.run();
}
console.log("Done, thank you");
}