/
nx-commands.ts
997 lines (945 loc) · 27.8 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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
import * as chalk from 'chalk';
import { execSync } from 'child_process';
import * as path from 'path';
import * as yargs from 'yargs';
import { nxVersion } from '../utils/versions';
import { examples } from './examples';
import { workspaceRoot } from '../utils/workspace-root';
import { getPackageManagerCommand } from '../utils/package-manager';
import { writeJsonFile } from '../utils/fileutils';
// Ensure that the output takes up the available width of the terminal.
yargs.wrap(yargs.terminalWidth());
export const parserConfiguration: Partial<yargs.ParserConfigurationOptions> = {
'strip-dashed': true,
};
/**
* 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(parserConfiguration)
.usage(chalk.bold('Smart, Fast and Extensible Build System'))
.demandCommand(1, '')
.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(), withOverrides(args)),
})
.command({
command: 'run-many',
describe: 'Run target for multiple listed projects',
builder: (yargs) =>
linkToNxDevAndExamples(
withRunManyOptions(withOutputStyleOption(withTargetOption(yargs))),
'run-many'
),
handler: async (args) =>
(await import('./run-many')).runMany(withOverrides(args)),
})
.command({
command: 'affected',
describe: 'Run target for affected projects',
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(
withRunOptions(withOutputStyleOption(withTargetOption(yargs)))
),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', withOverrides(args)),
})
.command({
command: 'affected:test',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withRunOptions(withOutputStyleOption(yargs))),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...withOverrides(args),
target: 'test',
}),
})
.command({
command: 'affected:build',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withRunOptions(withOutputStyleOption(yargs))),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...withOverrides(args),
target: 'build',
}),
})
.command({
command: 'affected:lint',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withRunOptions(withOutputStyleOption(yargs))),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...withOverrides(args),
target: 'lint',
}),
})
.command({
command: 'affected:e2e',
describe: false,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withRunOptions(withOutputStyleOption(yargs))),
'affected'
),
handler: async (args) =>
(await import('./affected')).affected('affected', {
...withOverrides(args),
target: 'e2e',
}),
})
.command({
command: 'affected:apps',
deprecated:
'Use `nx print-affected --type=app ...` instead. This command will be removed in v15.',
describe: `Print applications affected by changes`,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withPlainOption(yargs)),
'affected:apps'
),
handler: async (args) => {
await (await import('./affected')).affected('apps', { ...args });
process.exit(0);
},
})
.command({
command: 'affected:libs',
deprecated:
'Use `nx print-affected --type=lib ...` instead. This command will be removed in v15.',
describe: `Print libraries affected by changes`,
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withPlainOption(yargs)),
'affected:libs'
),
handler: async (args) => {
await (
await import('./affected')
).affected('libs', {
...args,
});
process.exit(0);
},
})
.command({
command: 'affected:graph',
describe: 'Graph dependencies affected by changes',
aliases: ['affected:dep-graph'],
builder: (yargs) =>
linkToNxDevAndExamples(
withAffectedOptions(withDepGraphOptions(yargs)),
'affected:graph'
),
handler: async (args) =>
await (
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(
withTargetOption(withPrintAffectedOptions(yargs), false)
),
'print-affected'
),
handler: async (args) => {
await (
await import('./affected')
).affected('print-affected', withOverrides(args));
process.exit(0);
},
})
.command({
command: 'daemon',
describe:
'Prints information about the Nx Daemon process or starts a daemon process',
builder: (yargs) =>
linkToNxDevAndExamples(withDaemonOptions(yargs), 'daemon'),
handler: async (args) => (await import('./daemon')).daemonHandler(args),
})
.command({
command: 'graph',
describe: 'Graph dependencies within workspace',
aliases: ['dep-graph'],
builder: (yargs) =>
linkToNxDevAndExamples(withDepGraphOptions(yargs), 'dep-graph'),
handler: async (args) =>
await (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 (await import('./format')).format('check', args);
process.exit(0);
},
})
.command({
command: 'format:write',
describe: 'Overwrite un-formatted files',
aliases: ['format'],
builder: (yargs) =>
linkToNxDevAndExamples(withFormatOptions(yargs), 'format:write'),
handler: async (args) => {
await (await import('./format')).format('write', args);
process.exit(0);
},
})
.command({
command: 'workspace-lint [files..]',
describe: 'Lint nx specific workspace files (nx.json, workspace.json)',
handler: async () => {
await (await import('./lint')).workspaceLint();
process.exit(0);
},
})
.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, process.argv.slice(3)),
'workspace-generator'
),
handler: workspaceGeneratorHandler,
})
.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();
process.exit(0);
},
})
.command({
command: 'report',
describe:
'Reports useful version numbers to copy into the Nx issue template',
handler: async () => {
await (await import('./report')).reportHandler();
process.exit(0);
},
})
.command({
command: 'init',
describe: 'Adds nx.json file and installs nx if not installed already',
handler: async () => {
await (await import('./init')).initHandler();
process.exit(0);
},
})
.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 (await import('./list')).listHandler(args);
process.exit(0);
},
})
.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',
aliases: ['connect-to-nx-cloud'],
describe: `Connect workspace to Nx Cloud`,
builder: (yargs) => linkToNxDevAndExamples(yargs, 'connect-to-nx-cloud'),
handler: async () => {
await (await import('./connect')).connectToNxCloudCommand();
process.exit(0);
},
})
.command({
command: 'new [_..]',
describe: false,
builder: (yargs) => withNewOptions(yargs),
handler: async (args) => {
args._ = args._.slice(1);
process.exit(
await (
await import('./generate')
).newWorkspace(args['nxWorkspaceRoot'] as string, args)
);
},
})
.command({
command: '_migrate [packageAndVersion]',
describe: false,
builder: (yargs) => withMigrationOptions(yargs),
handler: async (args) =>
process.exit(
await (await import('./migrate')).migrate(process.cwd(), args)
),
})
.command({
command: 'repair',
describe: 'Repair any configuration that is no longer supported by Nx.',
builder: (yargs) =>
linkToNxDevAndExamples(yargs, 'repair').option('verbose', {
type: 'boolean',
describe:
'Prints additional information about the commands (e.g., stack traces)',
}),
handler: async (args) =>
process.exit(await (await import('./repair')).repair(args)),
})
.command({
command: 'view-logs',
describe: false,
handler: async () =>
process.exit(await (await import('./view-logs')).viewLogs()),
})
.help()
.version(nxVersion);
function withFormatOptions(yargs: yargs.Argv): yargs.Argv {
return withAffectedOptions(yargs)
.parserConfiguration({
'camel-case-expansion': true,
})
.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 withDaemonOptions(yargs: yargs.Argv): yargs.Argv {
return yargs
.option('start', {
type: 'boolean',
default: false,
})
.option('stop', {
type: 'boolean',
default: false,
});
}
function withPrintAffectedOptions(yargs: yargs.Argv): yargs.Argv {
return yargs
.option('select', {
type: 'string',
describe:
'Select the subset of the returned json document (e.g., --select=projects)',
})
.option('type', {
type: 'string',
choices: ['app', 'lib'],
describe: 'Select the type of projects to be returned (e.g., --type=app)',
});
}
function withPlainOption(yargs: yargs.Argv): yargs.Argv {
return yargs.option('plain', {
describe: 'Produces a plain output for affected:apps and affected:libs',
});
}
function withExcludeOption(yargs: yargs.Argv): yargs.Argv {
return yargs.option('exclude', {
describe: 'Exclude certain projects from being processed',
type: 'array',
coerce: parseCSV,
default: [],
});
}
function withRunOptions(yargs: yargs.Argv): yargs.Argv {
return withExcludeOption(yargs)
.option('parallel', {
describe: 'Max number of parallel processes [default is 3]',
type: 'string',
})
.option('maxParallel', {
type: 'number',
hidden: true,
})
.options('runner', {
describe: 'This is the name of the tasks runner configured in nx.json',
type: 'string',
})
.options('configuration', {
describe:
'This is the configuration to use when performing tasks on projects',
type: 'string',
})
.option('prod', {
describe: 'Use the production configuration',
type: 'boolean',
default: false,
hidden: true,
})
.option('verbose', {
type: 'boolean',
describe:
'Prints additional information about the commands (e.g., stack traces)',
default: false,
})
.option('nx-bail', {
describe: 'Stop command execution after the first failed task',
type: 'boolean',
default: false,
})
.option('nx-ignore-cycles', {
describe: 'Ignore cycles in the task graph',
type: 'boolean',
default: false,
})
.options('skip-nx-cache', {
describe:
'Rerun the tasks even when the results are available in the cache',
type: 'boolean',
default: false,
})
.options('cloud', {
type: 'boolean',
hidden: true,
})
.options('dte', {
type: 'boolean',
hidden: true,
});
}
function withAffectedOptions(yargs: yargs.Argv): yargs.Argv {
return withExcludeOption(yargs)
.parserConfiguration({
'strip-dashed': true,
'unknown-options-as-args': true,
'populate--': true,
})
.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')
.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 withRunOptions(yargs)
.parserConfiguration({
'strip-dashed': true,
'unknown-options-as-args': true,
'populate--': true,
})
.option('projects', {
describe: 'Projects to run (comma delimited)',
type: 'string',
})
.option('all', {
describe: '[deprecated] Run the target on all projects in the workspace',
type: 'boolean',
default: true,
});
}
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 withOverrides(args: any): any {
args.__overrides_unparsed__ = (args['--'] ?? args._.slice(1)).map((v) =>
v.toString()
);
delete args['--'];
delete args._;
return args;
}
function withOutputStyleOption(
yargs: yargs.Argv,
choices = ['dynamic', 'static', 'stream', 'stream-without-prefixes']
): yargs.Argv {
return yargs.option('output-style', {
describe: 'Defines how Nx emits outputs tasks logs',
type: 'string',
choices,
});
}
function withTargetOption(yargs: yargs.Argv, demandOption = true): yargs.Argv {
return yargs.option('target', {
describe: 'Task to run for affected projects',
type: 'string',
requiresArg: true,
demandOption,
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,
})
.option('verbose', {
describe:
'Prints additional information about the commands (e.g., stack traces)',
type: 'boolean',
default: false,
});
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 = withRunOptions(
withOutputStyleOption(withTargetOption(yargs, false), [
'dynamic',
'static',
'stream',
'stream-without-prefixes',
'compact',
])
)
.parserConfiguration({
'strip-dashed': true,
'unknown-options-as-args': true,
'populate--': true,
})
.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.`
);
}
}
type OptionArgumentDefinition = {
type: yargs.Options['type'];
describe?: string;
default?: any;
choices?: yargs.Options['type'][];
demandOption?: boolean;
};
type WorkspaceGeneratorProperties = {
[name: string]:
| {
type: yargs.Options['type'];
description?: string;
default?: any;
enum?: yargs.Options['type'][];
demandOption?: boolean;
}
| {
type: yargs.PositionalOptionsType;
description?: string;
default?: any;
enum?: yargs.PositionalOptionsType[];
$default: {
$source: 'argv';
index: number;
};
};
};
function isPositionalProperty(
property: WorkspaceGeneratorProperties[keyof WorkspaceGeneratorProperties]
): property is { type: yargs.PositionalOptionsType } {
return property['$default']?.['$source'] === 'argv';
}
async function withWorkspaceGeneratorOptions(
yargs: yargs.Argv,
args: string[]
) {
// filter out only positional arguments
args = args.filter((a) => !a.startsWith('-'));
if (args.length) {
// this is an actual workspace generator
return withCustomGeneratorOptions(yargs, args[0]);
} else {
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;
}
}
async function withCustomGeneratorOptions(
yargs: yargs.Argv,
generatorName: string
) {
const schema = (
await import('./workspace-generators')
).workspaceGeneratorSchema(generatorName);
const options = [];
const positionals = [];
Object.entries(schema.properties as WorkspaceGeneratorProperties).forEach(
([name, prop]) => {
const option: { name: string; definition: OptionArgumentDefinition } = {
name,
definition: {
describe: prop.description,
type: prop.type,
default: prop.default,
choices: prop.enum,
},
};
if (schema.required && schema.required.includes(name)) {
option.definition.demandOption = true;
}
options.push(option);
if (isPositionalProperty(prop)) {
positionals.push({
name,
definition: {
describe: prop.description,
type: prop.type,
choices: prop.enum,
},
});
}
}
);
let command = generatorName;
positionals.forEach(({ name }) => {
command += ` [${name}]`;
});
if (options.length) {
command += ' (options)';
}
yargs
.command({
// this is the default and only command
command,
describe: schema.description || '',
builder: (y) => {
options.forEach(({ name, definition }) => {
y.option(name, definition);
});
positionals.forEach(({ name, definition }) => {
y.positional(name, definition);
});
return linkToNxDevAndExamples(y, 'workspace-generator');
},
handler: workspaceGeneratorHandler,
})
.fail(() => void 0); // no action is needed on failure as Nx will handle it based on schema validation
return yargs;
}
async function workspaceGeneratorHandler() {
await (
await import('./workspace-generators')
).workspaceGenerators(process.argv.slice(3));
process.exit(0);
}
function withMigrationOptions(yargs: yargs.Argv) {
const defaultCommitPrefix = 'chore: [nx migration] ';
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',
})
.option('createCommits', {
describe: 'Automatically create a git commit after each migration runs',
type: 'boolean',
alias: ['C'],
default: false,
})
.option('commitPrefix', {
describe:
'Commit prefix to apply to the commit for each migration, when --create-commits is enabled',
type: 'string',
default: defaultCommitPrefix,
})
.check(({ createCommits, commitPrefix }) => {
if (!createCommits && commitPrefix !== defaultCommitPrefix) {
throw new Error(
'Error: Providing a custom commit prefix requires --create-commits to be enabled'
);
}
return true;
});
}
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/nx/${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;
const version =
process.env.NX_MIGRATE_USE_NEXT === 'true' ? 'next' : 'latest';
writeJsonFile(path.join(tmpDir, 'package.json'), {
dependencies: {
nx: version,
},
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);
}