-
-
Notifications
You must be signed in to change notification settings - Fork 9.9k
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·675 lines (616 loc) · 17.6 KB
/
index.ts
File metadata and controls
executable file
·675 lines (616 loc) · 17.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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as fs from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import path from 'node:path';
// KEEP DEPENDENCY SMALL HERE!
// create-docusaurus CLI should be as lightweight as possible
// TODO try to remove these third-party dependencies if possible
import {logger} from '@docusaurus/logger';
import prompts, {type Choice} from 'prompts';
import supportsColor from 'supports-color';
import {runCommand, siteNameToPackageName} from './utils.js';
import {askPreferredLanguage} from './prompts.js';
type LanguagesOptions = {
javascript?: boolean;
typescript?: boolean;
};
type CLIOptions = LanguagesOptions & {
packageManager?: PackageManager;
skipInstall?: boolean;
gitStrategy?: GitStrategy;
};
async function getLanguage(options: LanguagesOptions) {
if (options.typescript) {
return 'typescript';
}
if (options.javascript) {
return 'javascript';
}
return askPreferredLanguage();
}
// Only used in the rare, rare case of running globally installed create +
// using --skip-install. We need a default name to show the tip text
const defaultPackageManager = 'npm';
const lockfileNames = {
npm: 'package-lock.json',
yarn: 'yarn.lock',
pnpm: 'pnpm-lock.yaml',
bun: 'bun.lockb',
};
type PackageManager = keyof typeof lockfileNames;
const packageManagers = Object.keys(lockfileNames) as PackageManager[];
function pathExists(filePath: string): Promise<boolean> {
return fs
.access(filePath, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
}
async function findPackageManagerFromLockFile(
rootDir: string,
): Promise<PackageManager | undefined> {
for (const packageManager of packageManagers) {
const lockFilePath = path.join(rootDir, lockfileNames[packageManager]);
if (await pathExists(lockFilePath)) {
return packageManager;
}
}
return undefined;
}
function findPackageManagerFromUserAgent(): PackageManager | undefined {
return packageManagers.find((packageManager) =>
process.env.npm_config_user_agent?.startsWith(packageManager),
);
}
async function askForPackageManagerChoice(): Promise<PackageManager> {
const hasYarn = (await runCommand('yarn --version')) === 0;
const hasPnpm = (await runCommand('pnpm --version')) === 0;
const hasBun = (await runCommand('bun --version')) === 0;
if (!hasYarn && !hasPnpm && !hasBun) {
return 'npm';
}
const choices = ['npm', hasYarn && 'yarn', hasPnpm && 'pnpm', hasBun && 'bun']
.filter((p): p is string => Boolean(p))
.map((p) => ({title: p, value: p}));
return (
(
(await prompts(
{
type: 'select',
name: 'packageManager',
message: 'Select a package manager...',
choices,
},
{
onCancel() {
logger.info`Falling back to name=${defaultPackageManager}`;
},
},
)) as {packageManager?: PackageManager}
).packageManager ?? defaultPackageManager
);
}
async function getPackageManager(
dest: string,
{packageManager, skipInstall}: CLIOptions,
): Promise<PackageManager> {
if (packageManager && !packageManagers.includes(packageManager)) {
throw new Error(
`Invalid package manager choice ${packageManager}. Must be one of ${packageManagers.join(
', ',
)}`,
);
}
return (
// If dest already contains a lockfile (e.g. if using a local template), we
// always use that instead
(await findPackageManagerFromLockFile(dest)) ??
packageManager ??
(await findPackageManagerFromLockFile('.')) ??
findPackageManagerFromUserAgent() ??
// This only happens if the user has a global installation in PATH
(skipInstall ? defaultPackageManager : askForPackageManagerChoice())
);
}
const recommendedTemplate = 'classic';
const typeScriptTemplateSuffix = '-typescript';
const templatesDir = fileURLToPath(new URL('../templates', import.meta.url));
type Template = {
name: string;
path: string;
tsVariantPath: string | undefined;
};
async function readTemplates(): Promise<Template[]> {
const dirContents = await fs.readdir(templatesDir);
const templates = await Promise.all(
dirContents
.filter(
(d) =>
!d.startsWith('.') &&
!d.startsWith('README') &&
!d.endsWith(typeScriptTemplateSuffix) &&
d !== 'shared',
)
.map(async (name) => {
const tsVariantPath = path.join(
templatesDir,
`${name}${typeScriptTemplateSuffix}`,
);
return {
name,
path: path.join(templatesDir, name),
tsVariantPath: (await pathExists(tsVariantPath))
? tsVariantPath
: undefined,
};
}),
);
// Classic should be first in list!
return templates.sort((a, b) => {
if (a.name === recommendedTemplate) {
return -1;
}
if (b.name === recommendedTemplate) {
return 1;
}
return 0;
});
}
async function copyTemplate(
template: Template,
dest: string,
language: 'javascript' | 'typescript',
): Promise<void> {
await fs.cp(path.join(templatesDir, 'shared'), dest, {
recursive: true,
});
const sourcePath =
language === 'typescript' ? template.tsVariantPath! : template.path;
await fs.cp(sourcePath, dest, {
recursive: true,
// Symlinks don't exist in published npm packages anymore, so this is only
// to prevent errors during local testing
filter: async (filePath) => !(await fs.lstat(filePath)).isSymbolicLink(),
});
}
function createTemplateChoices(templates: Template[]): Choice[] {
function makeNameAndValueChoice(value: string | Template): Choice {
if (typeof value === 'string') {
return {title: value, value};
}
const title =
value.name === recommendedTemplate
? `${value.name} (recommended)`
: value.name;
return {title, value};
}
return [
...templates.map((template) => makeNameAndValueChoice(template)),
makeNameAndValueChoice('Git repository'),
makeNameAndValueChoice('Local template'),
];
}
async function askTemplateChoice({
templates,
cliOptions,
}: {
templates: Template[];
cliOptions: CLIOptions;
}) {
return cliOptions.gitStrategy
? 'Git repository'
: (
(await prompts(
{
type: 'select',
name: 'template',
message: 'Select a template below...',
choices: createTemplateChoices(templates),
},
{
onCancel() {
logger.error('A choice is required.');
process.exit(1);
},
},
)) as {template: Template | 'Git repository' | 'Local template'}
).template;
}
function isValidGitRepoUrl(gitRepoUrl: string): boolean {
return ['https://', 'git@'].some((item) => gitRepoUrl.startsWith(item));
}
const gitStrategies = ['deep', 'shallow', 'copy', 'custom'] as const;
type GitStrategy = (typeof gitStrategies)[number];
async function getGitCommand(gitStrategy: GitStrategy): Promise<string> {
switch (gitStrategy) {
case 'shallow':
case 'copy':
return 'git clone --recursive --depth 1';
case 'custom': {
const {command} = (await prompts(
{
type: 'text',
name: 'command',
message:
'Write your own git clone command. The repository URL and destination directory will be supplied. E.g. "git clone --depth 10"',
},
{
onCancel() {
logger.info`Falling back to code=${'git clone'}`;
},
},
)) as {command?: string};
return command ?? 'git clone';
}
case 'deep':
default:
return 'git clone';
}
}
async function getSiteName(
reqName: string | undefined,
rootDir: string,
): Promise<string> {
async function validateSiteName(siteName: string) {
if (!siteName) {
return 'A website name is required.';
}
const dest = path.resolve(rootDir, siteName);
if (siteName === '.' && (await fs.readdir(dest)).length > 0) {
return logger.interpolate`Directory not empty at path=${dest}!`;
}
if (siteName !== '.' && (await pathExists(dest))) {
return logger.interpolate`Directory already exists at path=${dest}!`;
}
return true;
}
if (reqName) {
const res = await validateSiteName(reqName);
if (typeof res === 'string') {
throw new Error(res);
}
return reqName;
}
const {siteName} = (await prompts(
{
type: 'text',
name: 'siteName',
message: 'What should we name this site?',
initial: 'website',
validate: validateSiteName,
},
{
onCancel() {
logger.error('A website name is required.');
process.exit(1);
},
},
)) as {siteName: string};
return siteName;
}
type Source =
| {
type: 'template';
template: Template;
language: 'javascript' | 'typescript';
}
| {
type: 'git';
url: string;
strategy: GitStrategy;
}
| {
type: 'local';
path: string;
};
async function createTemplateSource({
template,
cliOptions,
}: {
template: Template;
cliOptions: CLIOptions;
}): Promise<Source> {
const language = await getLanguage(cliOptions);
if (language === 'typescript' && !template.tsVariantPath) {
logger.error`Template name=${template.name} doesn't provide a TypeScript variant.`;
process.exit(1);
}
return {
type: 'template',
template,
language,
};
}
async function getTemplateSource({
templateName,
templates,
cliOptions,
}: {
templateName: string;
templates: Template[];
cliOptions: CLIOptions;
}): Promise<Source> {
const template = templates.find((t) => t.name === templateName);
if (!template) {
logger.error('Invalid template.');
process.exit(1);
}
return createTemplateSource({template, cliOptions});
}
// Get the template source explicitly requested by the user provided cli option
async function getUserProvidedSource({
reqTemplate,
templates,
cliOptions,
}: {
reqTemplate: string;
templates: Template[];
cliOptions: CLIOptions;
}): Promise<Source> {
if (isValidGitRepoUrl(reqTemplate)) {
if (
cliOptions.gitStrategy &&
!gitStrategies.includes(cliOptions.gitStrategy)
) {
logger.error`Invalid git strategy: name=${
cliOptions.gitStrategy
}. Value must be one of ${gitStrategies.join(', ')}.`;
process.exit(1);
}
return {
type: 'git',
url: reqTemplate,
strategy: cliOptions.gitStrategy ?? 'deep',
};
}
if (await pathExists(path.resolve(reqTemplate))) {
return {
type: 'local',
path: path.resolve(reqTemplate),
};
}
return getTemplateSource({
templateName: reqTemplate,
templates,
cliOptions,
});
}
async function askGitRepositorySource({
cliOptions,
}: {
cliOptions: CLIOptions;
}): Promise<Source> {
const {gitRepoUrl} = (await prompts(
{
type: 'text',
name: 'gitRepoUrl',
validate: (url?: string) => {
if (url && isValidGitRepoUrl(url)) {
return true;
}
return logger.red('Invalid repository URL');
},
message: logger.interpolate`Enter a repository URL from GitHub, Bitbucket, GitLab, or any other public repo.
(e.g: url=${'https://github.com/ownerName/repoName.git'})`,
},
{
onCancel() {
logger.error('A git repo URL is required.');
process.exit(1);
},
},
)) as {gitRepoUrl: string};
let strategy = cliOptions.gitStrategy;
if (!strategy) {
({strategy} = (await prompts(
{
type: 'select',
name: 'strategy',
message: 'How should we clone this repo?',
choices: [
{title: 'Deep clone: preserve full history', value: 'deep'},
{title: 'Shallow clone: clone with --depth=1', value: 'shallow'},
{
title: 'Copy: do a shallow clone, but do not create a git repo',
value: 'copy',
},
{
title: 'Custom: enter your custom git clone command',
value: 'custom',
},
],
},
{
onCancel() {
logger.info`Falling back to name=${'deep'}`;
},
},
)) as {strategy?: GitStrategy});
}
return {
type: 'git',
url: gitRepoUrl,
strategy: strategy ?? 'deep',
};
}
async function askLocalSource(): Promise<Source> {
const {templateDir} = (await prompts(
{
type: 'text',
name: 'templateDir',
validate: async (dir?: string) => {
if (dir) {
const fullDir = path.resolve(dir);
if (await pathExists(fullDir)) {
return true;
}
return logger.red(
logger.interpolate`path=${fullDir} does not exist.`,
);
}
return logger.red('Please enter a valid path.');
},
message:
'Enter a local folder path, relative to the current working directory.',
},
{
onCancel() {
logger.error('A file path is required.');
process.exit(1);
},
},
)) as {templateDir: string};
return {
type: 'local',
path: templateDir,
};
}
async function getSource(
reqTemplate: string | undefined,
templates: Template[],
cliOptions: CLIOptions,
): Promise<Source> {
if (reqTemplate) {
return getUserProvidedSource({reqTemplate, templates, cliOptions});
}
const template = await askTemplateChoice({templates, cliOptions});
if (template === 'Git repository') {
return askGitRepositorySource({cliOptions});
}
if (template === 'Local template') {
return askLocalSource();
}
return createTemplateSource({
template,
cliOptions,
});
}
async function updatePkg(pkgPath: string, obj: {[key: string]: unknown}) {
const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8')) as {
[key: string]: unknown;
};
const newPkg = Object.assign(pkg, obj);
await fs.mkdir(path.dirname(pkgPath), {recursive: true});
await fs.writeFile(pkgPath, `${JSON.stringify(newPkg, null, 2)}\n`);
}
export default async function init(
rootDir: string,
reqName?: string,
reqTemplate?: string,
cliOptions: CLIOptions = {},
): Promise<void> {
const [templates, siteName] = await Promise.all([
readTemplates(),
getSiteName(reqName, rootDir),
]);
const dest = path.resolve(rootDir, siteName);
const source = await getSource(reqTemplate, templates, cliOptions);
logger.info('Creating new Docusaurus project...');
if (source.type === 'git') {
const gitCommand = await getGitCommand(source.strategy);
if ((await runCommand(gitCommand, [source.url, dest])) !== 0) {
logger.error`Cloning Git template failed!`;
process.exit(1);
}
if (source.strategy === 'copy') {
await fs.rm(path.join(dest, '.git'), {
force: true,
recursive: true,
});
}
} else if (source.type === 'template') {
try {
await copyTemplate(source.template, dest, source.language);
} catch (err) {
throw new Error(
logger.interpolate`Copying Docusaurus template name=${source.template.name} failed!`,
{cause: err},
);
}
} else {
try {
await fs.cp(source.path, dest, {recursive: true});
} catch (err) {
throw new Error(
logger.interpolate`Copying local template path=${source.path} failed!`,
{cause: err},
);
}
}
// Update package.json info.
try {
await updatePkg(path.join(dest, 'package.json'), {
name: siteNameToPackageName(siteName),
version: '0.0.0',
private: true,
});
} catch (err) {
throw new Error('Failed to update package.json.', {cause: err});
}
// We need to rename the gitignore file to .gitignore
if (
!(await pathExists(path.join(dest, '.gitignore'))) &&
(await pathExists(path.join(dest, 'gitignore')))
) {
await fs.rename(
path.join(dest, 'gitignore'),
path.join(dest, '.gitignore'),
);
}
if (await pathExists(path.join(dest, 'gitignore'))) {
await fs.rm(path.join(dest, 'gitignore'));
}
// Display the most elegant way to cd.
const cdpath = path.relative('.', dest);
const pkgManager = await getPackageManager(dest, cliOptions);
if (!cliOptions.skipInstall) {
process.chdir(dest);
logger.info`Installing dependencies with name=${pkgManager}...`;
// ...
if (
(await runCommand(
pkgManager === 'yarn'
? 'yarn'
: pkgManager === 'bun'
? 'bun install'
: `${pkgManager} install --color always`,
[],
{
env: {
...process.env,
// Force coloring the output
...(supportsColor.stdout ? {FORCE_COLOR: '1'} : {}),
},
},
)) !== 0
) {
logger.error('Dependency installation failed.');
logger.info`The site directory has already been created, and you can retry by typing:
code=${`cd ${cdpath}`}
code=${`${pkgManager} install`}`;
process.exit(0);
}
}
const useNpm = pkgManager === 'npm';
const useBun = pkgManager === 'bun';
const useRunCommand = useNpm || useBun;
logger.success`Created name=${cdpath}.`;
logger.info`Inside that directory, you can run several commands:
code=${`${pkgManager} start`}
Starts the development server.
code=${`${pkgManager} ${useRunCommand ? 'run ' : ''}build`}
Bundles your website into static files for production.
code=${`${pkgManager} ${useRunCommand ? 'run ' : ''}serve`}
Serves the built website locally.
code=${`${pkgManager} ${useRunCommand ? 'run ' : ''}deploy`}
Publishes the website to GitHub pages.
We recommend that you begin by typing:
code=${`cd ${cdpath}`}
code=${`${pkgManager} start`}
Happy building awesome websites!
`;
}