/
create-nx-workspace.ts
853 lines (781 loc) · 21.6 KB
/
create-nx-workspace.ts
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
#!/usr/bin/env node
import { exec } from 'child_process';
import { writeFileSync } from 'fs';
import * as enquirer from 'enquirer';
import * as path from 'path';
import { dirSync } from 'tmp';
import * as yargs from 'yargs';
import { showNxWarning, unparse } from './shared';
import { output } from './output';
import * as ora from 'ora';
import {
detectInvokedPackageManager,
getPackageManagerCommand,
getPackageManagerVersion,
PackageManager,
packageManagerList,
} from './package-manager';
import { validateNpmPackage } from './validate-npm-package';
import { deduceDefaultBase } from './default-base';
import { stringifyCollection } from './utils';
import { yargsDecorator } from './decorator';
type Arguments = {
name: string;
preset: string;
appName: string;
cli: string;
style: string;
nxCloud: boolean;
allPrompts: boolean;
packageManager: string;
defaultBase: string;
};
enum Preset {
Apps = 'apps',
Empty = 'empty', // same as apps, deprecated
Core = 'core',
NPM = 'npm', // same as core, deprecated
TS = 'ts',
WebComponents = 'web-components',
Angular = 'angular',
AngularWithNest = 'angular-nest',
React = 'react',
ReactWithExpress = 'react-express',
ReactNative = 'react-native',
NextJs = 'next',
Nest = 'nest',
Express = 'express',
}
const presetOptions: { name: Preset; message: string }[] = [
{
name: Preset.Apps,
message:
'apps [an empty workspace with no plugins with a layout that works best for building apps]',
},
{
name: Preset.Core,
message:
'core [an empty workspace with no plugins set up to publish npm packages (similar to yarn workspaces)]',
},
{
name: Preset.TS,
message:
'ts [an empty workspace with the JS/TS plugin preinstalled]',
},
{
name: Preset.React,
message: 'react [a workspace with a single React application]',
},
{
name: Preset.Angular,
message:
'angular [a workspace with a single Angular application]',
},
{
name: Preset.NextJs,
message:
'next.js [a workspace with a single Next.js application]',
},
{
name: Preset.Nest,
message: 'nest [a workspace with a single Nest application]',
},
{
name: Preset.Express,
message:
'express [a workspace with a single Express application]',
},
{
name: Preset.WebComponents,
message:
'web components [a workspace with a single app built using web components]',
},
{
name: Preset.ReactNative,
message:
'react-native [a workspace with a single React Native application]',
},
{
name: Preset.ReactWithExpress,
message:
'react-express [a workspace with a full stack application (React + Express)]',
},
{
name: Preset.AngularWithNest,
message:
'angular-nest [a workspace with a full stack application (Angular + Nest)]',
},
];
const tsVersion = 'TYPESCRIPT_VERSION';
const cliVersion = 'NX_VERSION';
const nxVersion = 'NX_VERSION';
const prettierVersion = 'PRETTIER_VERSION';
export const commandsObject: yargs.Argv<Arguments> = yargs
.wrap(yargs.terminalWidth())
.parserConfiguration({
'strip-dashed': true,
'dot-notation': false,
})
.command(
// this is the default and only command
'$0 [name] [options]',
'Create a new Nx workspace',
(yargs) =>
yargs
.option('name', {
describe: `Workspace name (e.g. org name)`,
type: 'string',
})
.option('preset', {
describe: `Customizes the initial content of your workspace. To build your own see https://nx.dev/nx-plugin/overview#preset`,
choices: Object.values(Preset),
type: 'string',
})
.option('appName', {
describe: `The name of the application when a preset with pregenerated app is selected`,
type: 'string',
})
.option('interactive', {
describe: `Enable interactive mode with presets`,
type: 'boolean',
})
.option('cli', {
describe: `CLI to power the Nx workspace`,
choices: ['nx', 'angular'],
type: 'string',
})
.option('style', {
describe: `Style option to be used when a preset with pregenerated app is selected`,
type: 'string',
})
.option('nxCloud', {
describe: `Use Nx Cloud`,
defaultDescription: 'true',
type: 'boolean',
})
.option('allPrompts', {
alias: 'a',
describe: `Show all prompts`,
type: 'boolean',
default: false,
})
.option('packageManager', {
alias: 'pm',
describe: `Package manager to use`,
choices: [...packageManagerList].sort(),
defaultDescription: 'npm',
type: 'string',
})
.option('defaultBase', {
defaultDescription: 'main',
describe: `Default base to use for new projects`,
type: 'string',
}),
async (argv: yargs.ArgumentsCamelCase<Arguments>) => {
await main(argv).catch((error) => {
const { version } = require('../package.json');
output.error({
title: `Something went wrong! v${version}`,
});
throw error;
});
},
[getConfiguration]
)
.help('help')
.updateLocale(yargsDecorator)
.version(nxVersion) as yargs.Argv<Arguments>;
async function main(parsedArgs: yargs.Arguments<Arguments>) {
const {
name,
cli,
preset,
appName,
style,
nxCloud,
packageManager,
defaultBase,
} = parsedArgs;
output.log({
title: `Nx is creating your v${cliVersion} workspace.`,
bodyLines: [
'To make sure the command works reliably in all environments, and that the preset is applied correctly,',
`Nx will run "${packageManager} install" several times. Please wait.`,
],
});
const tmpDir = await createSandbox(packageManager);
await createApp(tmpDir, name, packageManager as PackageManager, {
...parsedArgs,
cli,
preset,
appName,
style,
nxCloud,
defaultBase,
});
let nxCloudInstallRes;
if (nxCloud) {
nxCloudInstallRes = await setupNxCloud(
name,
packageManager as PackageManager
);
}
showNxWarning(name);
pointToTutorialAndCourse(preset as Preset);
if (nxCloud && nxCloudInstallRes.code === 0) {
printNxCloudSuccessMessage(nxCloudInstallRes.stdout);
}
}
async function getConfiguration(
argv: yargs.Arguments<Arguments>
): Promise<void> {
try {
let style, appName;
const name = await determineWorkspaceName(argv);
let preset = await determineThirdPartyPackage(argv);
if (!preset) {
preset = await determinePreset(argv);
appName = await determineAppName(preset, argv);
style = await determineStyle(preset, argv);
}
const cli = await determineCli(preset, argv);
const packageManager = await determinePackageManager(argv);
const defaultBase = await determineDefaultBase(argv);
const nxCloud = await determineNxCloud(argv);
Object.assign(argv, {
name,
preset,
appName,
style,
cli,
nxCloud,
packageManager,
defaultBase,
});
} catch (e) {
console.error(e);
process.exit(1);
}
}
function determineWorkspaceName(
parsedArgs: yargs.Arguments<Arguments>
): Promise<string> {
const workspaceName: string = parsedArgs._[0]
? parsedArgs._[0].toString()
: parsedArgs.name;
if (workspaceName) {
return Promise.resolve(workspaceName);
}
return enquirer
.prompt([
{
name: 'WorkspaceName',
message: `Workspace name (e.g., org name) `,
type: 'input',
},
])
.then((a: { WorkspaceName: string }) => {
if (!a.WorkspaceName) {
output.error({
title: 'Invalid workspace name',
bodyLines: [`Workspace name cannot be empty`],
});
process.exit(1);
}
return a.WorkspaceName;
});
}
async function determinePackageManager(
parsedArgs: yargs.Arguments<Arguments>
): Promise<PackageManager> {
const packageManager: string = parsedArgs.packageManager;
if (packageManager) {
if (packageManagerList.includes(packageManager as PackageManager)) {
return Promise.resolve(packageManager as PackageManager);
}
output.error({
title: 'Invalid package manager',
bodyLines: [
`Package manager must be one of ${stringifyCollection([
...packageManagerList,
])}`,
],
});
process.exit(1);
}
if (parsedArgs.allPrompts) {
return enquirer
.prompt([
{
name: 'PackageManager',
message: `Which package manager to use `,
initial: 'npm' as any,
type: 'select',
choices: [
{ name: 'npm', message: 'NPM' },
{ name: 'yarn', message: 'Yarn' },
{ name: 'pnpm', message: 'PNPM' },
],
},
])
.then((a: { PackageManager }) => a.PackageManager);
}
return Promise.resolve(detectInvokedPackageManager());
}
async function determineDefaultBase(
parsedArgs: yargs.Arguments<Arguments>
): Promise<string> {
if (parsedArgs.defaultBase) {
return Promise.resolve(parsedArgs.defaultBase);
}
if (parsedArgs.allPrompts) {
return enquirer
.prompt([
{
name: 'DefaultBase',
message: `Main branch name `,
initial: `main`,
type: 'input',
},
])
.then((a: { DefaultBase: string }) => {
if (!a.DefaultBase) {
output.error({
title: 'Invalid branch name',
bodyLines: [`Branch name cannot be empty`],
});
process.exit(1);
}
return a.DefaultBase;
});
}
return Promise.resolve(deduceDefaultBase());
}
function isKnownPreset(preset: string): preset is Preset {
return Object.values(Preset).includes(preset as Preset);
}
async function determineThirdPartyPackage({
preset,
}: yargs.Arguments<Arguments>) {
if (preset && !isKnownPreset(preset)) {
const packageName = preset.match(/.+@/)
? preset[0] + preset.substring(1).split('@')[0]
: preset;
const validateResult = validateNpmPackage(packageName);
if (validateResult.validForNewPackages) {
return Promise.resolve(preset);
} else {
//! Error here
output.error({
title: 'Invalid preset npm package',
bodyLines: [
`There was an error with the preset npm package you provided:`,
'',
...validateResult.errors,
],
});
process.exit(1);
}
} else {
return Promise.resolve(null);
}
}
async function determinePreset(parsedArgs: any): Promise<Preset> {
if (parsedArgs.preset) {
if (Object.values(Preset).indexOf(parsedArgs.preset) === -1) {
output.error({
title: 'Invalid preset',
bodyLines: [
`It must be one of the following:`,
'',
...Object.values(Preset),
],
});
process.exit(1);
} else {
return Promise.resolve(parsedArgs.preset);
}
}
return enquirer
.prompt([
{
name: 'Preset',
message: `What to create in the new workspace`,
initial: 'empty' as any,
type: 'select',
choices: presetOptions,
},
])
.then((a: { Preset: Preset }) => a.Preset);
}
async function determineAppName(
preset: Preset,
parsedArgs: yargs.Arguments<Arguments>
): Promise<string> {
if (
preset === Preset.Apps ||
preset === Preset.Core ||
preset === Preset.TS ||
preset === Preset.Empty ||
preset === Preset.NPM
) {
return Promise.resolve('');
}
if (parsedArgs.appName) {
return Promise.resolve(parsedArgs.appName);
}
return enquirer
.prompt([
{
name: 'AppName',
message: `Application name `,
type: 'input',
},
])
.then((a: { AppName: string }) => {
if (!a.AppName) {
output.error({
title: 'Invalid name',
bodyLines: [`Name cannot be empty`],
});
process.exit(1);
}
return a.AppName;
});
}
function isValidCli(cli: string): cli is 'angular' | 'nx' {
return ['nx', 'angular'].indexOf(cli) !== -1;
}
async function determineCli(
preset: Preset,
parsedArgs: yargs.Arguments<Arguments>
): Promise<'nx' | 'angular'> {
if (parsedArgs.cli) {
if (!isValidCli(parsedArgs.cli)) {
output.error({
title: 'Invalid cli',
bodyLines: [`It must be one of the following:`, '', 'nx', 'angular'],
});
process.exit(1);
}
return Promise.resolve(parsedArgs.cli);
}
switch (preset) {
case Preset.Angular:
case Preset.AngularWithNest: {
return Promise.resolve('angular');
}
default: {
return Promise.resolve('nx');
}
}
}
async function determineStyle(
preset: Preset,
parsedArgs: yargs.Arguments<Arguments>
) {
if (
preset === Preset.Apps ||
preset === Preset.Core ||
preset === Preset.TS ||
preset === Preset.Empty ||
preset === Preset.NPM ||
preset === Preset.Nest ||
preset === Preset.Express ||
preset === Preset.ReactNative
) {
return Promise.resolve(null);
}
const choices = [
{
name: 'css',
message: 'CSS',
},
{
name: 'scss',
message: 'SASS(.scss) [ http://sass-lang.com ]',
},
{
name: 'less',
message: 'LESS [ http://lesscss.org ]',
},
];
if (![Preset.Angular, Preset.AngularWithNest].includes(preset)) {
choices.push({
name: 'styl',
message: 'Stylus(.styl) [ http://stylus-lang.com ]',
});
}
if ([Preset.ReactWithExpress, Preset.React, Preset.NextJs].includes(preset)) {
choices.push(
{
name: 'styled-components',
message:
'styled-components [ https://styled-components.com ]',
},
{
name: '@emotion/styled',
message:
'emotion [ https://emotion.sh ]',
},
{
name: 'styled-jsx',
message:
'styled-jsx [ https://www.npmjs.com/package/styled-jsx ]',
}
);
}
if (!parsedArgs.style) {
return enquirer
.prompt([
{
name: 'style',
message: `Default stylesheet format `,
initial: 'css' as any,
type: 'select',
choices: choices,
},
])
.then((a: { style: string }) => a.style);
}
const foundStyle = choices.find((choice) => choice.name === parsedArgs.style);
if (foundStyle === undefined) {
output.error({
title: 'Invalid style',
bodyLines: [
`It must be one of the following:`,
'',
...choices.map((choice) => choice.name),
],
});
process.exit(1);
}
return Promise.resolve(parsedArgs.style);
}
async function createSandbox(packageManager: string) {
const installSpinner = ora(
`Installing dependencies with ${packageManager}`
).start();
const tmpDir = dirSync().name;
try {
writeFileSync(
path.join(tmpDir, 'package.json'),
JSON.stringify({
dependencies: {
'@nrwl/workspace': nxVersion,
nx: cliVersion,
typescript: tsVersion,
prettier: prettierVersion,
},
license: 'MIT',
})
);
await execAndWait(`${packageManager} install --silent`, tmpDir);
installSpinner.succeed();
} catch (e) {
installSpinner.fail();
output.error({
title: `Nx failed to install dependencies`,
bodyLines: mapErrorToBodyLines(e),
});
process.exit(1);
} finally {
installSpinner.stop();
}
return tmpDir;
}
async function createApp(
tmpDir: string,
name: string,
packageManager: PackageManager,
parsedArgs: any
) {
const { _, cli, ...restArgs } = parsedArgs;
// Ensure to use packageManager for args
// if it's not already passed in from previous process
if (!restArgs.packageManager) {
restArgs.packageManager = packageManager;
}
const args = unparse(restArgs).join(' ');
const pmc = getPackageManagerCommand(packageManager);
const command = `new ${name} ${args} --collection=@nrwl/workspace`;
let nxWorkspaceRoot = `"${process.cwd().replace(/\\/g, '/')}"`;
// If path contains spaces there is a problem in Windows for npm@6.
// In this case we have to escape the wrapping quotes.
if (
process.platform === 'win32' &&
/\s/.test(nxWorkspaceRoot) &&
packageManager === 'npm'
) {
const pmVersion = +getPackageManagerVersion(packageManager).split('.')[0];
if (pmVersion < 7) {
nxWorkspaceRoot = `\\"${nxWorkspaceRoot.slice(1, -1)}\\"`;
}
}
const fullCommandWithoutWorkspaceRoot = `${pmc.exec} nx ${command}/generators.json --cli=${cli}`;
let workspaceSetupSpinner = ora('Creating your workspace').start();
try {
const fullCommand = `${fullCommandWithoutWorkspaceRoot} --nxWorkspaceRoot=${nxWorkspaceRoot}`;
await execAndWait(fullCommand, tmpDir);
workspaceSetupSpinner.succeed('Nx has successfully created the workspace.');
} catch (e) {
workspaceSetupSpinner.fail();
output.error({
title: `Nx failed to create a workspace.`,
bodyLines: mapErrorToBodyLines(e),
});
process.exit(1);
} finally {
workspaceSetupSpinner.stop();
}
}
async function setupNxCloud(name: string, packageManager: PackageManager) {
const nxCloudSpinner = ora(`Setting up NxCloud`).start();
try {
const pmc = getPackageManagerCommand(packageManager);
const res = await execAndWait(
`${pmc.exec} nx g @nrwl/nx-cloud:init --no-analytics`,
path.join(process.cwd(), name)
);
nxCloudSpinner.succeed('NxCloud has been set up successfully');
return res;
} catch (e) {
nxCloudSpinner.fail();
output.error({
title: `Nx failed to setup NxCloud`,
bodyLines: mapErrorToBodyLines(e),
});
process.exit(1);
} finally {
nxCloudSpinner.stop();
}
}
function printNxCloudSuccessMessage(nxCloudOut: string) {
const bodyLines = nxCloudOut.split('Nx Cloud has been enabled')[1].trim();
output.note({
title: `Nx Cloud has been enabled`,
bodyLines: bodyLines.split('\n').map((r) => r.trim()),
});
}
function mapErrorToBodyLines(error: {
logMessage: string;
code: number;
logFile: string;
}): string[] {
if (error.logMessage.split('\n').filter((line) => !!line).length === 1) {
// print entire log message only if it's only a single message
return [`Error: ${error.logMessage}`];
}
const lines = [`Exit code: ${error.code}`, `Log file: ${error.logFile}`];
if (process.env.NX_VERBOSE_LOGGING) {
lines.push(`Error: ${error.logMessage}`);
}
return lines;
}
function execAndWait(command: string, cwd: string) {
return new Promise((res, rej) => {
exec(command, { cwd }, (error, stdout, stderr) => {
if (error) {
const logFile = path.join(cwd, 'error.log');
writeFileSync(logFile, `${stdout}\n${stderr}`);
rej({ code: error.code, logFile, logMessage: stderr });
} else {
res({ code: 0, stdout });
}
});
});
}
async function determineNxCloud(parsedArgs: yargs.Arguments<Arguments>) {
if (parsedArgs.nxCloud === undefined) {
return enquirer
.prompt([
{
name: 'NxCloud',
message: `Use Nx Cloud? (It's free and doesn't require registration.)`,
type: 'select',
choices: [
{
name: 'Yes',
hint: 'Faster builds, run details, GitHub integration. Learn more at https://nx.app',
},
{
name: 'No',
},
],
initial: 'Yes' as any,
},
])
.then((a: { NxCloud: 'Yes' | 'No' }) => a.NxCloud === 'Yes');
} else {
return parsedArgs.nxCloud;
}
}
function pointToTutorialAndCourse(preset: Preset) {
const title = `First time using Nx? Check out this interactive Nx tutorial.`;
switch (preset) {
case Preset.Empty:
case Preset.NPM:
case Preset.Apps:
case Preset.Core:
output.addVerticalSeparator();
output.note({
title,
bodyLines: [`https://nx.dev/core-tutorial/01-create-blog`],
});
break;
case Preset.TS:
output.addVerticalSeparator();
output.note({
title,
bodyLines: [`https://nx.dev/getting-started/nx-and-typescript`],
});
break;
case Preset.React:
case Preset.ReactWithExpress:
case Preset.NextJs:
output.addVerticalSeparator();
output.note({
title,
bodyLines: [
`https://nx.dev/react-tutorial/01-create-application`,
...pointToFreeCourseOnEgghead(),
],
});
break;
case Preset.Angular:
case Preset.AngularWithNest:
output.addVerticalSeparator();
output.note({
title,
bodyLines: [
`https://nx.dev/angular-tutorial/01-create-application`,
...pointToFreeCourseOnYoutube(),
],
});
break;
case Preset.Nest:
output.addVerticalSeparator();
output.note({
title,
bodyLines: [
`https://nx.dev/node-tutorial/01-create-application`,
...pointToFreeCourseOnYoutube(),
],
});
break;
}
}
function pointToFreeCourseOnYoutube(): string[] {
return [
``,
`Prefer watching videos? Check out this free Nx course on YouTube.`,
`https://www.youtube.com/watch?v=2mYLe9Kp9VM&list=PLakNactNC1dH38AfqmwabvOszDmKriGco`,
];
}
function pointToFreeCourseOnEgghead(): string[] {
return [
``,
`Prefer watching videos? Check out this free Nx course on Egghead.io.`,
`https://egghead.io/playlists/scale-react-development-with-nx-4038`,
];
}