-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.ts
More file actions
652 lines (563 loc) · 16.6 KB
/
Copy pathindex.ts
File metadata and controls
652 lines (563 loc) · 16.6 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
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import fs from 'node:fs';
import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
cancel,
isCancel,
multiselect,
note,
outro,
select,
text,
} from '@clack/prompts';
import deepmerge from 'deepmerge';
import minimist from 'minimist';
import color from 'picocolors';
import { logger } from 'rslog';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export { select, multiselect, text };
function cancelAndExit() {
cancel('Operation cancelled.');
process.exit(0);
}
export function checkCancel<T>(value: unknown) {
if (isCancel(value)) {
cancelAndExit();
}
return value as T;
}
/**
* 1. Input: 'foo'
* Output: folder `<cwd>/foo`, `package.json#name` -> `foo`
*
* 2. Input: 'foo/bar'
* Output: folder -> `<cwd>/foo/bar` folder, `package.json#name` -> `bar`
*
* 3. Input: '@scope/foo'
* Output: folder -> `<cwd>/@scope/bar` folder, `package.json#name` -> `@scope/foo`
*
* 4. Input: './foo/bar'
* Output: folder -> `<cwd>/foo/bar` folder, `package.json#name` -> `bar`
*
* 5. Input: '/root/path/to/foo'
* Output: folder -> `'/root/path/to/foo'` folder, `package.json#name` -> `foo`
*/
function formatProjectName(input: string) {
const formatted = input.trim().replace(/\/+$/g, '');
return {
packageName: formatted.startsWith('@')
? formatted
: path.basename(formatted),
targetDir: formatted,
};
}
function pkgFromUserAgent(userAgent: string | undefined) {
if (!userAgent) return undefined;
const pkgSpec = userAgent.split(' ')[0];
const pkgSpecArr = pkgSpec.split('/');
return {
name: pkgSpecArr[0],
version: pkgSpecArr[1],
};
}
function isEmptyDir(path: string) {
const files = fs.readdirSync(path);
return files.length === 0 || (files.length === 1 && files[0] === '.git');
}
export type Argv = {
help?: boolean;
dir?: string;
template?: string;
override?: boolean;
tools?: string | string[];
packageName?: string;
'package-name'?: string;
};
export const BUILTIN_TOOLS = ['eslint', 'prettier', 'biome'];
function logHelpMessage(name: string, templates: string[]) {
logger.log(`
Usage: create-${name} [dir] [options]
Options:
-h, --help display help for command
-d, --dir <dir> create project in specified directory
-t, --template <tpl> specify the template to use
--tools <tool> select additional tools (biome, eslint, prettier)
--override override files in target directory
--packageName <name> specify the package name
Templates:
${templates.join(', ')}
`);
}
async function getTools({ tools, dir, template }: Argv) {
if (tools) {
let toolsArr = Array.isArray(tools) ? tools : [tools];
toolsArr = toolsArr.filter((tool) => BUILTIN_TOOLS.includes(tool));
return toolsArr;
}
// skip tools selection when using CLI options
if (dir && template) {
return [];
}
// skip tools selection when tools is empty string
if (tools === '') {
return [];
}
return checkCancel<string[]>(
await multiselect({
message:
'Select additional tools (Use <space> to select, <enter> to continue)',
options: [
{ value: 'biome', label: 'Add Biome for code linting and formatting' },
{ value: 'eslint', label: 'Add ESLint for code linting' },
{ value: 'prettier', label: 'Add Prettier for code formatting' },
],
required: false,
}),
);
}
function upperFirst(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export type ESLintTemplateName =
| 'vanilla-js'
| 'vanilla-ts'
| 'react-js'
| 'react-ts'
| 'vue-ts'
| 'vue-js'
| 'svelte-js'
| 'svelte-ts';
const readJSON = async (path: string) =>
JSON.parse(await fs.promises.readFile(path, 'utf-8'));
const readPackageJson = async (filePath: string) =>
readJSON(path.join(filePath, 'package.json'));
const parseArgv = () => {
const argv = minimist<Argv>(process.argv.slice(2), {
alias: { h: 'help', d: 'dir', t: 'template' },
});
// Set dir to first argument if not specified via `--dir`
if (!argv.dir && argv._[0]) {
argv.dir = argv._[0];
}
if (argv['package-name']) {
argv.packageName = argv['package-name'];
}
return argv;
};
export async function create({
name,
root,
templates,
skipFiles,
getTemplateName,
mapESLintTemplate,
version,
noteInformation,
}: {
name: string;
root: string;
skipFiles?: string[];
templates: string[];
getTemplateName: (argv: Argv) => Promise<string>;
mapESLintTemplate: (
templateName: string,
context: { distFolder: string },
) => ESLintTemplateName | null;
version?: Record<string, string> | string;
noteInformation?: string[];
}) {
console.log('');
logger.greet(`◆ Create ${upperFirst(name)} Project`);
const argv = parseArgv();
if (argv.help) {
logHelpMessage(name, templates);
return;
}
const cwd = process.cwd();
const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent);
const packageManager = pkgInfo ? pkgInfo.name : 'npm';
const templateParameters = { packageManager };
// No version provided, read from package.json
if (!version) {
version = (await readPackageJson(root)).version;
}
const projectName =
argv.dir ??
checkCancel<string>(
await text({
message: 'Project name or path',
placeholder: `${name.toLowerCase()}-project`,
defaultValue: `${name.toLowerCase()}-project`,
validate(value) {
if (value.length === 0) {
return 'Project name is required';
}
},
}),
);
const formatted = formatProjectName(projectName);
const { targetDir } = formatted;
const packageName = argv.packageName || formatted.packageName;
const distFolder = path.isAbsolute(targetDir)
? targetDir
: path.join(cwd, targetDir);
if (!argv.override && fs.existsSync(distFolder) && !isEmptyDir(distFolder)) {
const option = checkCancel<string>(
await select({
message: `"${targetDir}" is not empty, please choose:`,
options: [
{ value: 'yes', label: 'Continue and override files' },
{ value: 'no', label: 'Cancel operation' },
],
}),
);
if (option === 'no') {
cancelAndExit();
}
}
const templateName = await getTemplateName(argv);
const tools = await getTools(argv);
const srcFolder = path.join(root, `template-${templateName}`);
const commonFolder = path.join(root, 'template-common');
if (!fs.existsSync(srcFolder)) {
throw new Error(`Invalid input: template "${templateName}" not found.`);
}
copyFolder({
from: commonFolder,
to: distFolder,
version,
skipFiles,
templateParameters,
});
copyFolder({
from: srcFolder,
to: distFolder,
version,
packageName,
templateParameters,
skipFiles,
});
const packageRoot = path.resolve(__dirname, '..');
const agentsMdSearchDirs = [commonFolder, srcFolder];
for (const tool of tools) {
const toolFolder = path.join(packageRoot, `template-${tool}`);
if (tool === 'eslint') {
const eslintTemplateName = mapESLintTemplate(templateName, {
distFolder,
});
if (!eslintTemplateName) {
continue;
}
const subFolder = path.join(toolFolder, eslintTemplateName);
copyFolder({
from: subFolder,
to: distFolder,
version,
skipFiles,
templateParameters,
isMergePackageJson: true,
});
agentsMdSearchDirs.push(toolFolder);
agentsMdSearchDirs.push(subFolder);
continue;
}
copyFolder({
from: toolFolder,
to: distFolder,
version,
skipFiles,
templateParameters,
isMergePackageJson: true,
});
agentsMdSearchDirs.push(toolFolder);
if (tool === 'biome') {
await fs.promises.rename(
path.join(distFolder, 'biome.json.template'),
path.join(distFolder, 'biome.json'),
);
}
}
const agentsFiles = collectAgentsFiles(agentsMdSearchDirs);
if (agentsFiles.length > 0) {
const mergedAgents = mergeAgentsFiles(agentsFiles);
const agentsPath = path.join(distFolder, 'AGENTS.md');
fs.writeFileSync(
agentsPath,
`${replacePlaceholder(mergedAgents, templateParameters)}\n`,
);
}
const nextSteps = noteInformation
? noteInformation
: [
`1. ${color.cyan(`cd ${targetDir}`)}`,
`2. ${color.cyan('git init')} ${color.dim('(optional)')}`,
`3. ${color.cyan(`${packageManager} install`)}`,
`4. ${color.cyan(`${packageManager} run dev`)}`,
];
if (nextSteps.length) {
note(nextSteps.map((step) => color.reset(step)).join('\n'), 'Next steps');
}
outro('All set, happy coding!');
}
function sortObjectKeys(obj: Record<string, unknown>) {
const sortedKeys = Object.keys(obj).sort();
const sortedObj: Record<string, unknown> = {};
for (const key of sortedKeys) {
sortedObj[key] = obj[key];
}
return sortedObj;
}
/**
* Merge two package.json files and keep the order of keys.
* @param targetPackage Path to the base package.json file
* @param extraPackage Path to the extra package.json file to merge
*/
export function mergePackageJson(targetPackage: string, extraPackage: string) {
if (!fs.existsSync(targetPackage)) {
return;
}
const targetJson = JSON.parse(fs.readFileSync(targetPackage, 'utf-8'));
const extraJson = JSON.parse(fs.readFileSync(extraPackage, 'utf-8'));
const mergedJson: Record<string, unknown> = deepmerge(targetJson, extraJson);
mergedJson.name = targetJson.name || extraJson.name;
for (const key of ['scripts', 'dependencies', 'devDependencies']) {
if (!(key in mergedJson)) {
continue;
}
mergedJson[key] = sortObjectKeys(
mergedJson[key] as Record<string, unknown>,
);
}
fs.writeFileSync(targetPackage, `${JSON.stringify(mergedJson, null, 2)}\n`);
}
const isMarkdown = (file: string) =>
file.endsWith('.md') || file.endsWith('.mdx');
const replacePlaceholder = (
content: string,
templateParameters: Record<string, string>,
) => {
let result = content;
for (const key of Object.keys(templateParameters)) {
result = result.replace(
new RegExp(`{{ ${key} }}`, 'g'),
templateParameters[key],
);
}
return result;
};
/**
* Copy files from one folder to another.
* @param from Source folder
* @param to Destination folder
* @param version - Optional. The version to update in the package.json. If not provided, version will not be updated.
* @param name - Optional. The name to update in the package.json. If not provided, name will not be updated.
* @param isMergePackageJson Merge package.json files
* @param skipFiles Files to skip
*/
export function copyFolder({
from,
to,
version,
packageName,
templateParameters,
isMergePackageJson,
skipFiles = [],
}: {
from: string;
to: string;
version?: string | Record<string, string>;
packageName?: string;
templateParameters?: Record<string, string>;
isMergePackageJson?: boolean;
skipFiles?: string[];
}) {
const renameFiles: Record<string, string> = {
gitignore: '.gitignore',
};
// Skip local files
const allSkipFiles = ['node_modules', 'dist', ...skipFiles];
fs.mkdirSync(to, { recursive: true });
for (const file of fs.readdirSync(from)) {
if (allSkipFiles.includes(file)) {
continue;
}
const srcFile = path.resolve(from, file);
const distFile = renameFiles[file]
? path.resolve(to, renameFiles[file])
: path.resolve(to, file);
const stat = fs.statSync(srcFile);
if (stat.isDirectory()) {
copyFolder({
from: srcFile,
to: distFile,
templateParameters,
version,
skipFiles,
});
} else if (file === 'package.json') {
const targetPackage = path.resolve(to, 'package.json');
if (isMergePackageJson && fs.existsSync(targetPackage)) {
mergePackageJson(targetPackage, srcFile);
} else {
fs.copyFileSync(srcFile, distFile);
}
updatePackageJson(distFile, version, packageName);
} else {
fs.copyFileSync(srcFile, distFile);
if (templateParameters && isMarkdown(distFile)) {
const content = fs.readFileSync(distFile, 'utf-8');
fs.writeFileSync(
distFile,
replacePlaceholder(content, templateParameters),
);
}
}
}
}
const isStableVersion = (version: string) => {
return ['alpha', 'beta', 'rc', 'canary', 'nightly'].every(
(tag) => !version.includes(tag),
);
};
/**
* Updates the package.json file at the specified path with the provided version and name.
*
* @param pkgJsonPath - The file path to the package.json file.
* @param version - Optional. The version to update in the package.json. If not provided, version will not be updated.
* @param name - Optional. The name to update in the package.json. If not provided, name will not be updated.
*/
const updatePackageJson = (
pkgJsonPath: string,
version?: string | Record<string, string>,
name?: string,
) => {
let content = fs.readFileSync(pkgJsonPath, 'utf-8');
if (typeof version === 'string') {
// Lock the version if it is not stable
const targetVersion = isStableVersion(version) ? `^${version}` : version;
content = content.replace(/workspace:\*/g, targetVersion);
}
const pkg = JSON.parse(content);
if (typeof version === 'object') {
for (const [name, ver] of Object.entries(version)) {
if (pkg.dependencies?.[name]) {
pkg.dependencies[name] = ver;
}
if (pkg.devDependencies?.[name]) {
pkg.devDependencies[name] = ver;
}
}
}
if (name === '.') {
const projectName = path.basename(path.dirname(pkgJsonPath));
if (projectName.length) {
pkg.name = projectName;
}
} else if (name) {
pkg.name = name;
}
fs.writeFileSync(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
};
/**
* Read AGENTS.md files from template directories
*/
function readAgentsFile(filePath: string): string | null {
if (!fs.existsSync(filePath)) {
return null;
}
return fs.readFileSync(filePath, 'utf-8');
}
/**
* Parse AGENTS.md content and extract sections
*/
function parseAgentsContent(
content: string,
): Record<string, { title: string; content: string; level: number }> {
const sections: Record<
string,
{ title: string; content: string; level: number }
> = {};
const lines = content.split('\n');
let currentKey = '';
let currentTitle = '';
let currentLevel = 0;
let currentContent: string[] = [];
for (const line of lines) {
const sectionMatch = line.match(/^(#{1,2})\s+(.+)$/);
if (sectionMatch) {
if (currentKey) {
sections[currentKey] = {
title: currentTitle,
level: currentLevel,
content: currentContent.join('\n').trim(),
};
}
currentLevel = sectionMatch[1].length;
currentTitle = sectionMatch[2].trim();
currentKey = `${currentLevel}-${currentTitle.toLowerCase()}`;
currentContent = [];
} else if (currentKey) {
currentContent.push(line);
}
}
if (currentKey) {
sections[currentKey] = {
title: currentTitle,
level: currentLevel,
content: currentContent.join('\n').trim(),
};
}
return sections;
}
/**
* Merge AGENTS.md files from multiple sources
*/
function mergeAgentsFiles(agentsFiles: string[]): string {
const allSections: Record<
string,
{ title: string; level: number; contents: string[] }
> = {};
for (const fileContent of agentsFiles) {
if (!fileContent) continue;
const sections = parseAgentsContent(fileContent);
for (const [key, section] of Object.entries(sections)) {
if (!allSections[key]) {
allSections[key] = {
title: section.title,
level: section.level,
contents: [],
};
}
if (
section.content &&
!allSections[key].contents.includes(section.content)
) {
allSections[key].contents.push(section.content);
}
}
}
const result: string[] = [];
for (const [, section] of Object.entries(allSections)) {
result.push(`${'#'.repeat(section.level)} ${section.title}`);
result.push('');
for (const content of section.contents) {
result.push(content);
result.push('');
}
}
return result.join('\n').trim();
}
/**
* Collect AGENTS.md files from template directories
*/
function collectAgentsFiles(agentsMdSearchDirs: string[]): string[] {
const agentsFiles: string[] = [];
for (const dir of agentsMdSearchDirs) {
const agentsContent = readAgentsFile(path.join(dir, 'AGENTS.md'));
if (agentsContent) {
agentsFiles.push(agentsContent);
}
}
return agentsFiles;
}