/
nx-commands.ts
762 lines (723 loc) · 22.2 KB
/
nx-commands.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
import * as chalk from 'chalk';
import { execSync } from 'child_process';
import * as path from 'path';
import * as yargs from 'yargs';
import { generateDaemonHelpOutput } from '../core/project-graph/daemon/client/generate-help-output';
import { nxVersion } from '../utils/versions';
import { examples } from './examples';
import { workspaceRoot } from 'nx/src/utils/app-root';
import { getPackageManagerCommand } from '../utils/package-manager';
import { writeJsonFile } from 'nx/src/utils/fileutils';
const isGenerateDocsProcess = process.env.NX_GENERATE_DOCS_PROCESS === 'true';
const daemonHelpOutput = generateDaemonHelpOutput(isGenerateDocsProcess);
// Ensure that the output takes up the available width of the terminal
yargs.wrap(yargs.terminalWidth());
/**
* Exposing the Yargs commands object so the documentation generator can
* parse it. The CLI will consume it and call the `.argv` to bootstrapped
* the CLI. These command declarations needs to be in a different file
* from the `.argv` call, so the object and it's relative scripts can
* le executed correctly.
*/
export const commandsObject = yargs
.parserConfiguration({
'strip-dashed': true,
'dot-notation': false,
})
.usage(
`
${chalk.bold('Smart, Fast and Extensible Build System')}` +
(daemonHelpOutput
? `
${daemonHelpOutput}
`.trimRight()
: '')
)
.command({
command: 'generate <generator> [_..]',
describe:
'Generate or update source code (e.g., nx generate @nrwl/js:lib mylib).',
aliases: ['g'],
builder: (yargs) => withGenerateOptions(yargs),
handler: async (args) => {
// Remove the command from the args
args._ = args._.slice(1);
process.exit(
await (await import('./generate')).generate(process.cwd(), args)
);
},
})
.command({
command: 'run [project][:target][:configuration] [_..]',
describe: `Run a target for a project
(e.g., nx run myapp:serve:production).
You can also use the infix notation to run a target:
(e.g., nx serve myapp --configuration=production)
You can skip the use of Nx cache by using the --skip-nx-cache option.
`,
builder: (yargs) => withRunOneOptions(yargs),
handler: async (args) =>
(await import('./run-one')).runOne(process.cwd(), { ...args }),
})
.command({
command: 'run-many',
describe: 'Run target for multiple listed projects',
builder: (yargs) =>
linkToNxDevAndExamples(
withRunManyOptions(withParallelOption(withTargetOption(yargs))),
'run-many'
),
handler: async (args) => (await import('./run-many')).runMany({ ...args }),
})
.command({
command: 'affected',
describe: 'Run target for affected projects',
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withParallelOption(withTargetOption(yargs))),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', { ...args }),
})
.command({
command: 'affected:test',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withParallelOption(yargs)),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...args,
target: 'test',
}),
})
.command({
command: 'affected:build',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withParallelOption(yargs)),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...args,
target: 'build',
}),
})
.command({
command: 'affected:lint',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withParallelOption(yargs)),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...args,
target: 'lint',
}),
})
.command({
command: 'affected:e2e',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withParallelOption(yargs)),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...args,
target: 'e2e',
}),
})
.command({
command: 'affected:apps',
describe: 'Print applications affected by changes',
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withPlainOption(yargs)),
'affected:apps'
),
handler: async (args) =>
(await import('./affected')).affected('apps', { ...args }),
})
.command({
command: 'affected:libs',
describe: 'Print libraries affected by changes',
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withPlainOption(yargs)),
'affected:libs'
),
handler: async (args) =>
(await import('./affected')).affected('libs', {
...args,
}),
})
.command({
command: 'affected:graph',
describe:
'Graph dependencies affected by changes. Alias: affected:dep-graph',
aliases: ['affected:dep-graph'],
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withDepGraphOptions(yargs)),
'affected:graph'
),
handler: async (args) =>
(await import('./affected')).affected('graph', {
...args,
}),
})
.command({
command: 'print-affected',
describe:
'Prints information about the projects and targets affected by changes',
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withPrintAffectedOptions(yargs)),
'print-affected'
),
handler: async (args) =>
(await import('./affected')).affected('print-affected', {
...args,
}),
})
.command({
command: 'daemon',
describe: 'Prints information about the Nx Daemon process',
builder: (yargs) =>
linkToNxDevAndExamples(withDaemonStartOptions(yargs), 'daemon'),
handler: async (args) => (await import('./daemon')).daemonHandler(args),
})
.command({
command: 'graph',
describe: 'Graph dependencies within workspace. Alias: dep-graph',
aliases: ['dep-graph'],
builder: (yargs) =>
linkToNxDevAndExamples(withDepGraphOptions(yargs), 'dep-graph'),
handler: async (args) =>
(await import('./dep-graph')).generateGraph(args as any, []),
})
.command({
command: 'format:check',
describe: 'Check for un-formatted files',
builder: (yargs) =>
linkToNxDevAndExamples(withFormatOptions(yargs), 'format:check'),
handler: async (args) => (await import('./format')).format('check', args),
})
.command({
command: 'format:write',
describe: 'Overwrite un-formatted files',
aliases: ['format'],
builder: (yargs) =>
linkToNxDevAndExamples(withFormatOptions(yargs), 'format:write'),
handler: async (args) => (await import('./format')).format('write', args),
})
.command({
command: 'workspace-lint [files..]',
describe: 'Lint nx specific workspace files (nx.json, workspace.json)',
handler: async () => (await import('./lint')).workspaceLint(),
})
.command({
command: 'workspace-generator [name]',
describe: 'Runs a workspace generator from the tools/generators directory',
aliases: ['workspace-schematic [name]'],
builder: async (yargs) =>
linkToNxDevAndExamples(
await withWorkspaceGeneratorOptions(yargs),
'workspace-generator'
),
handler: async () =>
(await import('./workspace-generators')).workspaceGenerators(
process.argv.slice(3)
),
})
.command({
command: 'migrate [packageAndVersion]',
describe: `Creates a migrations file or runs migrations from the migrations file.
- Migrate packages and create migrations.json (e.g., nx migrate @nrwl/workspace@latest)
- Run migrations (e.g., nx migrate --run-migrations=migrations.json)
`,
builder: (yargs) =>
linkToNxDevAndExamples(withMigrationOptions(yargs), 'migrate'),
handler: () => runMigration(),
})
.command({
command: 'report',
describe:
'Reports useful version numbers to copy into the Nx issue template',
handler: async () => (await import('./report')).reportHandler(),
})
.command({
command: 'list [plugin]',
describe:
'Lists installed plugins, capabilities of installed plugins and other available plugins.',
builder: (yargs) => withListOptions(yargs),
handler: async (args: any) => (await import('./list')).listHandler(args),
})
.command({
command: 'reset',
describe:
'Clears all the cached Nx artifacts and metadata about the workspace and shuts down the Nx Daemon.',
aliases: ['clear-cache'],
handler: async () => (await import('./reset')).resetHandler(),
})
.command({
command: 'connect-to-nx-cloud',
describe: `Makes sure the workspace is connected to Nx Cloud`,
builder: (yargs) => linkToNxDevAndExamples(yargs, 'connect-to-nx-cloud'),
handler: async () =>
(await import('./connect-to-nx-cloud')).connectToNxCloudCommand(),
})
.command({
command: 'new [_..]',
describe: false,
builder: (yargs) => withNewOptions(yargs),
handler: async (args) => {
args._ = args._.slice(1);
return (await import('./generate')).newWorkspace(
args['nxWorkspaceRoot'] as string,
args
);
},
})
.command(
'_migrate [packageAndVersion]',
false,
(yargs) => withMigrationOptions(yargs),
async (args) => (await import('./migrate')).migrate(process.cwd(), args)
)
.help('help')
.version(nxVersion);
function withFormatOptions(yargs: yargs.Argv): yargs.Argv {
return withAffectedOptions(yargs)
.option('libs-and-apps', {
describe: 'Format only libraries and applications files.',
type: 'boolean',
})
.option('projects', {
describe: 'Projects to format (comma delimited)',
type: 'array',
coerce: parseCSV,
})
.conflicts({
all: 'projects',
});
}
function withDaemonStartOptions(yargs: yargs.Argv): yargs.Argv {
return yargs.option('background', { type: 'boolean', default: true });
}
function withPrintAffectedOptions(yargs: yargs.Argv): yargs.Argv {
return yargs.option('select', {
type: 'string',
describe:
'Select the subset of the returned json document (e.g., --selected=projects)',
});
}
function withPlainOption(yargs: yargs.Argv): yargs.Argv {
return yargs.option('plain', {
describe: 'Produces a plain output for affected:apps and affected:libs',
});
}
function withAffectedOptions(yargs: yargs.Argv): yargs.Argv {
return yargs
.option('files', {
describe:
'Change the way Nx is calculating the affected command by providing directly changed files, list of files delimited by commas',
type: 'array',
requiresArg: true,
coerce: parseCSV,
})
.option('uncommitted', {
describe: 'Uncommitted changes',
type: 'boolean',
default: undefined,
})
.option('untracked', {
describe: 'Untracked changes',
type: 'boolean',
default: undefined,
})
.option('all', {
describe: 'All projects',
type: 'boolean',
default: undefined,
})
.option('base', {
describe: 'Base of the current branch (usually main)',
type: 'string',
requiresArg: true,
})
.option('head', {
describe: 'Latest commit of the current branch (usually HEAD)',
type: 'string',
requiresArg: true,
})
.group(
['base'],
'Run command using --base=[SHA1] (affected by the committed, uncommitted and untracked changes):'
)
.group(
['base', 'head'],
'or using --base=[SHA1] --head=[SHA2] (affected by the committed changes):'
)
.group(['files', 'uncommitted', 'untracked'], 'or using:')
.implies('head', 'base')
.option('exclude', {
describe: 'Exclude certain projects from being processed',
type: 'array',
coerce: parseCSV,
default: [],
})
.options('runner', {
describe: 'This is the name of the tasks runner configured in nx.json',
type: 'string',
})
.options('skip-nx-cache', {
describe:
'Rerun the tasks even when the results are available in the cache',
type: 'boolean',
default: false,
})
.options('configuration', {
describe:
'This is the configuration to use when performing tasks on projects',
type: 'string',
})
.options('only-failed', {
deprecated:
'The command to rerun failed projects will appear if projects fail. This now does nothing and will be removed in v15.',
describe: 'Isolate projects which previously failed',
type: 'boolean',
default: false,
})
.option('verbose', {
describe: 'Print additional error stack trace on failure',
})
.conflicts({
files: ['uncommitted', 'untracked', 'base', 'head', 'all'],
untracked: ['uncommitted', 'files', 'base', 'head', 'all'],
uncommitted: ['files', 'untracked', 'base', 'head', 'all'],
all: ['files', 'untracked', 'uncommitted', 'base', 'head'],
});
}
function withRunManyOptions(yargs: yargs.Argv): yargs.Argv {
return yargs
.option('projects', {
describe: 'Projects to run (comma delimited)',
type: 'string',
})
.option('all', {
describe: 'Run the target on all projects in the workspace',
type: 'boolean',
default: undefined,
})
.check(({ all, projects }) => {
if ((all && projects) || (!all && !projects))
throw new Error('You must provide either --all or --projects');
return true;
})
.options('runner', {
describe: 'Override the tasks runner in `nx.json`',
type: 'string',
})
.options('skip-nx-cache', {
describe:
'Rerun the tasks even when the results are available in the cache',
type: 'boolean',
default: false,
})
.options('configuration', {
describe:
'This is the configuration to use when performing tasks on projects',
type: 'string',
})
.options('with-deps', {
describe:
'Include dependencies of specified projects when computing what to run',
type: 'boolean',
default: false,
deprecated:
'Configure target dependencies instead. It will be removed in v14.',
})
.options('only-failed', {
deprecated:
'The command to rerun failed projects will appear if projects fail. This now does nothing and will be removed in v15.',
describe: 'Only run the target on projects which previously failed',
type: 'boolean',
default: false,
})
.option('exclude', {
describe: 'Exclude certain projects from being processed',
type: 'array',
coerce: parseCSV,
default: [],
})
.option('verbose', {
describe: 'Print additional error stack trace on failure',
})
.conflicts({
all: 'projects',
});
}
function withDepGraphOptions(yargs: yargs.Argv): yargs.Argv {
return yargs
.option('file', {
describe:
'Output file (e.g. --file=output.json or --file=dep-graph.html)',
type: 'string',
})
.option('focus', {
describe:
'Use to show the project graph for a particular project and every node that is either an ancestor or a descendant.',
type: 'string',
})
.option('exclude', {
describe:
'List of projects delimited by commas to exclude from the project graph.',
type: 'array',
coerce: parseCSV,
})
.option('groupByFolder', {
describe: 'Group projects by folder in the project graph',
type: 'boolean',
})
.option('host', {
describe: 'Bind the project graph server to a specific ip address.',
type: 'string',
})
.option('port', {
describe: 'Bind the project graph server to a specific port.',
type: 'number',
})
.option('watch', {
describe: 'Watch for changes to project graph and update in-browser',
type: 'boolean',
default: false,
})
.option('open', {
describe: 'Open the project graph in the browser.',
type: 'boolean',
default: true,
});
}
function withParallelOption(yargs: yargs.Argv): yargs.Argv {
return yargs.option('parallel', {
describe: 'Max number of parallel processes [default is 3]',
type: 'string',
});
}
function withTargetOption(yargs: yargs.Argv): yargs.Argv {
return yargs.option('target', {
describe: 'Task to run for affected projects',
type: 'string',
requiresArg: true,
demandOption: true,
global: false,
});
}
function withNewOptions(yargs: yargs.Argv) {
return yargs
.option('nxWorkspaceRoot', {
describe: 'The folder where the new workspace is going to be created',
type: 'string',
required: true,
})
.option('interactive', {
describe: 'When false disables interactive input prompts for options',
type: 'boolean',
default: true,
});
}
function withGenerateOptions(yargs: yargs.Argv) {
const generatorWillShowHelp =
process.argv[3] && !process.argv[3].startsWith('-');
const res = yargs
.positional('generator', {
describe: 'Name of the generator (e.g., @nrwl/js:library, library)',
type: 'string',
required: true,
})
.option('dryRun', {
describe: 'Preview the changes without updating files',
alias: 'd',
type: 'boolean',
default: false,
})
.option('interactive', {
describe: 'When false disables interactive input prompts for options',
type: 'boolean',
default: true,
});
if (generatorWillShowHelp) {
return res.help(false);
} else {
return res.epilog(
`Run "nx g collection:generator --help" to see information about the generator's schema.`
);
}
}
function withRunOneOptions(yargs: yargs.Argv) {
const executorShouldShowHelp = !(
process.argv[2] === 'run' && process.argv[3] === '--help'
);
const res = yargs
.option('prod', {
describe: 'Use the production configuration',
type: 'boolean',
default: false,
})
.option('configuration', {
describe: 'Target configuration',
alias: 'c',
type: 'string',
})
.option('project', {
describe: 'Target project',
type: 'string',
});
if (executorShouldShowHelp) {
return res.help(false);
} else {
return res.epilog(
`Run "nx run myapp:mytarget --help" to see information about the executor's schema.`
);
}
}
async function withWorkspaceGeneratorOptions(yargs: yargs.Argv) {
yargs
.option('list-generators', {
describe: 'List the available workspace-generators',
type: 'boolean',
})
.positional('name', {
type: 'string',
describe: 'The name of your generator`',
});
/**
* Don't require `name` if only listing available
* schematics
*/
if ((await yargs.argv).listGenerators !== true) {
yargs.demandOption('name');
}
return yargs;
}
function withMigrationOptions(yargs: yargs.Argv) {
return yargs
.positional('packageAndVersion', {
describe: `The target package and version (e.g, @nrwl/workspace@13.0.0)`,
type: 'string',
})
.option('runMigrations', {
describe: `Execute migrations from a file (when the file isn't provided, execute migrations from migrations.json)`,
type: 'string',
})
.option('from', {
describe:
'Use the provided versions for packages instead of the ones installed in node_modules (e.g., --from="@nrwl/react:12.0.0,@nrwl/js:12.0.0")',
type: 'string',
})
.option('to', {
describe:
'Use the provided versions for packages instead of the ones calculated by the migrator (e.g., --to="@nrwl/react:12.0.0,@nrwl/js:12.0.0")',
type: 'string',
});
}
function parseCSV(args: string[]) {
if (!args) {
return args;
}
return args
.map((arg) => arg.split(','))
.reduce((acc, value) => {
return [...acc, ...value];
}, [] as string[]);
}
function linkToNxDevAndExamples(yargs: yargs.Argv, command: string) {
(examples[command] || []).forEach((t) => {
yargs = yargs.example(t.command, t.description);
});
return yargs.epilog(
chalk.bold(
`Find more information and examples at https://nx.dev/cli/${command.replace(
':',
'-'
)}`
)
);
}
function withListOptions(yargs) {
return yargs.positional('plugin', {
type: 'string',
description: 'The name of an installed plugin to query',
});
}
function runMigration() {
const runLocalMigrate = () => {
const pmc = getPackageManagerCommand();
execSync(`${pmc.exec} nx _migrate ${process.argv.slice(3).join(' ')}`, {
stdio: ['inherit', 'inherit', 'inherit'],
});
};
if (process.env.NX_MIGRATE_USE_LOCAL === undefined) {
const p = nxCliPath();
if (p === null) {
runLocalMigrate();
} else {
execSync(`${p} _migrate ${process.argv.slice(3).join(' ')}`, {
stdio: ['inherit', 'inherit', 'inherit'],
});
}
} else {
runLocalMigrate();
}
}
function nxCliPath() {
try {
const packageManager = getPackageManagerCommand();
const { dirSync } = require('tmp');
const tmpDir = dirSync().name;
writeJsonFile(path.join(tmpDir, 'package.json'), {
dependencies: {
nx: 'latest',
},
license: 'MIT',
});
execSync(packageManager.install, {
cwd: tmpDir,
stdio: ['ignore', 'ignore', 'ignore'],
});
// Set NODE_PATH so that these modules can be used for module resolution
addToNodePath(path.join(tmpDir, 'node_modules'));
addToNodePath(path.join(workspaceRoot, 'node_modules'));
return path.join(tmpDir, `node_modules`, '.bin', 'nx');
} catch (e) {
console.error(
'Failed to install the latest version of the migration script. Using the current version.'
);
if (process.env.NX_VERBOSE_LOGGING) {
console.error(e);
}
return null;
}
}
function addToNodePath(dir: string) {
// NODE_PATH is a delimited list of paths.
// The delimiter is different for windows.
const delimiter = require('os').platform() === 'win32' ? ';' : ':';
const paths = process.env.NODE_PATH
? process.env.NODE_PATH.split(delimiter)
: [];
// Add the tmp path
paths.push(dir);
// Update the env variable.
process.env.NODE_PATH = paths.join(delimiter);
}