-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathcli.ts
More file actions
917 lines (822 loc) · 32.8 KB
/
Copy pathcli.ts
File metadata and controls
917 lines (822 loc) · 32.8 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
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
/* eslint-disable @typescript-eslint/no-shadow */ // yargs
import * as cxapi from '@aws-cdk/cx-api';
import type { ChangeSetDeployment, DeploymentMethod, DirectDeployment, StackSelector as LibStackSelector } from '@aws-cdk/toolkit-lib';
import { ExpandStackSelection, StackSelectionStrategy, ToolkitError, Toolkit } from '@aws-cdk/toolkit-lib';
import * as chalk from 'chalk';
import { guessLanguage } from '../util';
import { CdkToolkit, AssetBuildTime } from './cdk-toolkit';
import { ciSystemIsStdErrSafe } from './ci-systems';
import { displayVersionMessage, shouldDisplayVersionMessage } from './display-version';
import type { IoMessageLevel } from './io-host';
import { CliIoHost } from './io-host';
import { parseCommandLineArguments } from './parse-command-line-arguments';
import { checkForPlatformWarnings } from './platform-warnings';
import { prettyPrintError } from './pretty-print-error';
import { ProxyAgentProvider } from './proxy-agent';
import { GLOBAL_PLUGIN_HOST } from './singleton-plugin-host';
import { cdkCliErrorName } from './telemetry/error';
import type { ErrorDetails } from './telemetry/schema';
import type { Command } from './user-configuration';
import { Configuration } from './user-configuration';
import { trapErrors } from './util/trap-errors';
import { isDeveloperBuildVersion, versionWithBuild, versionNumber } from './version';
import { asIoHelper } from '../../lib/api-private';
import type { IReadLock } from '../api';
import { ToolkitInfo, Notices, loadTree, findConstructLibraryVersion } from '../api';
import { SdkProvider, IoHostSdkLogger, setSdkTracing, sdkRequestHandler } from '../api/aws-auth';
import type { BootstrapSource } from '../api/bootstrap';
import { Bootstrapper } from '../api/bootstrap';
import { Deployments } from '../api/deployments';
import { HotswapMode } from '../api/hotswap';
import type { Settings } from '../api/settings';
import { contextHandler as context } from '../commands/context';
import { docs } from '../commands/docs';
import { doctor } from '../commands/doctor';
import { FlagCommandHandler } from '../commands/flags/flags';
import { cliInit, printAvailableTemplates } from '../commands/init';
import { getLanguageFromAlias } from '../commands/language';
import { getMigrateScanType } from '../commands/migrate';
import { execProgram, CloudExecutable } from '../cxapp';
import type { StackSelector, Synthesizer } from '../cxapp';
import { findUnknownOptions } from './util/check-unknown-options';
import { isCI } from './util/ci';
import { guessAgent } from './util/guess-agent';
export async function exec(args: string[], synthesizer?: Synthesizer): Promise<number | void> {
// This is the very first code that runs, but libraries have been loaded already and that also costs time.
// Measure that.
const libraryLoadTime = performance.now();
const argv = await parseCommandLineArguments(args);
argv.language = getLanguageFromAlias(argv.language) ?? argv.language;
// Handle color output settings
// Priority: --no-color > --color > TTY detection
if (argv.noColor) {
process.env.FORCE_COLOR = '0';
} else if (argv.color) {
process.env.FORCE_COLOR = '3';
} else if (!process.stdout.isTTY) {
// Default behavior: disable colors for non-TTY
process.env.FORCE_COLOR = '0';
}
const cmd = argv._[0];
// if one -v, log at a DEBUG level
// if 2 -v, log at a TRACE level
let ioMessageLevel: IoMessageLevel = 'info';
if (argv.verbose) {
switch (argv.verbose) {
case 1:
ioMessageLevel = 'debug';
break;
case 2:
default:
ioMessageLevel = 'trace';
break;
}
}
const ioHost = CliIoHost.instance({
logLevel: ioMessageLevel,
isTTY: process.stdout.isTTY,
isCI: Boolean(argv.ci),
currentAction: cmd,
stackProgress: argv.progress,
autoRespond: argv.yes,
}, true);
const ioHelper = asIoHelper(ioHost, ioHost.currentAction as any);
// CLI debugging (and the highest verbosity, `-vvv`) turns on verbose AWS SDK tracing.
setSdkTracing(Boolean(argv.debugCli) || argv.verbose > 2);
try {
await checkForPlatformWarnings(ioHelper);
} catch (e) {
await ioHost.defaults.debug(`Error while checking for platform warnings: ${e}`);
}
await ioHost.defaults.debug('CDK Toolkit CLI version:', versionWithBuild());
await ioHost.defaults.debug('Command line arguments:', argv);
const unknownOptions = findUnknownOptions(argv);
if (unknownOptions.length > 0) {
const formatted = unknownOptions.map((o) => `--${o}`).join(', ');
await ioHost.defaults.warn(`Unknown option(s): ${formatted}. These will be ignored. Run 'cdk --help' to see available options.`);
}
const configuration = await Configuration.fromArgsAndFiles(ioHelper,
{
commandLineArguments: {
...argv,
_: argv._ as [Command, ...string[]], // TypeScript at its best
},
});
// Always create and use ProxyAgent to support configuration via env vars
const proxyAgent = await new ProxyAgentProvider(ioHelper).create({
proxyAddress: configuration.settings.get(['proxy']),
caBundlePath: configuration.settings.get(['caBundlePath']),
});
try {
await ioHost.startTelemetry(argv, configuration.context, proxyAgent);
} catch (e: any) {
await ioHost.asIoHelper().defaults.trace(`Telemetry instantiation failed: ${e.message}`);
}
ioHost.telemetry?.attachLoadTime(libraryLoadTime);
ioHost.telemetry?.attachLanguage(await guessLanguage(process.cwd()));
ioHost.telemetry?.attachAgent(guessAgent());
/**
* The default value for displaying (and refreshing) notices on all commands.
*
* If the user didn't supply either `--notices` or `--no-notices`, we do
* autodetection. The autodetection currently is: do write notices if we are
* not on CI, or are on a CI system where we know that writing to stderr is
* safe. We fail "closed"; that is, we decide to NOT print for unknown CI
* systems, even though technically we maybe could.
*/
const isSafeToWriteNotices = !isCI() || Boolean(ciSystemIsStdErrSafe());
// Determine if notices should be displayed based on CLI args and configuration
let shouldDisplayNotices: boolean;
if (argv.notices !== undefined) {
// CLI argument takes precedence
shouldDisplayNotices = argv.notices;
} else {
// Fall back to configuration file setting, then autodetection
const configNotices = configuration.settings.get(['notices']);
if (configNotices !== undefined) {
// Consider string "false" to be falsy in this context
shouldDisplayNotices = configNotices !== 'false' && Boolean(configNotices);
} else {
// Default autodetection behavior
shouldDisplayNotices = isSafeToWriteNotices;
}
}
// Notices either go to stderr, or nowhere
ioHost.noticesDestination = shouldDisplayNotices ? 'stderr' : 'drop';
const notices = Notices.create({
ioHost,
context: configuration.context,
output: configuration.settings.get(['outdir']),
language: await guessLanguage(process.cwd()),
httpOptions: { agent: proxyAgent },
cliVersion: versionNumber(),
});
const refreshNotices = (async () => {
// the cdk notices command has it's own refresh
if (shouldDisplayNotices && cmd !== 'notices') {
await trapErrors(ioHelper, 'Could not refresh notices', () => notices.refresh());
}
})();
const sdkProvider = await SdkProvider.withAwsCliCompatibleDefaults({
ioHelper,
requestHandler: sdkRequestHandler(proxyAgent),
logger: new IoHostSdkLogger(asIoHelper(ioHost, ioHost.currentAction as any)),
pluginHost: GLOBAL_PLUGIN_HOST,
}, configuration.settings.get(['profile']), configuration.settings.get(['region']));
try {
await ioHost.telemetry?.attachRegion(sdkProvider.defaultRegion);
} catch (e: any) {
await ioHost.asIoHelper().defaults.trace(`Telemetry attach region failed: ${e.message}`);
}
let outDirLock: IReadLock | undefined;
const cloudExecutable = new CloudExecutable({
configuration,
sdkProvider,
synthesizer:
synthesizer ??
(async (aws, config) => {
// Invoke 'execProgram', and copy the lock for the directory in the global
// variable here. It will be released when the CLI exits. Locks are not re-entrant
// so release it if we have to synthesize more than once (because of context lookups).
await outDirLock?.release();
const { assembly, lock, perfCounters } = await execProgram(aws, ioHost.asIoHelper(), config);
outDirLock = lock;
const tree = await loadTree(assembly, ioHelper.defaults.trace.bind(ioHelper.defaults));
if (tree) {
const v = findConstructLibraryVersion(tree);
if (v) {
ioHost.telemetry?.attachCdkLibVersion(v);
}
}
if (perfCounters) {
ioHost.telemetry?.attachCountersToNextEvent(perfCounters);
}
return assembly;
}),
ioHelper: ioHost.asIoHelper(),
});
/** Function to load plug-ins, using configurations additively. */
async function loadPlugins(...settings: Settings[]) {
for (const source of settings) {
const plugins: string[] = source.get(['plugin']) || [];
for (const plugin of plugins) {
await GLOBAL_PLUGIN_HOST.load(plugin, ioHost);
}
}
}
await loadPlugins(configuration.settings);
if ((typeof cmd) !== 'string') {
throw new ToolkitError('InvalidArgType', `First argument should be a string. Got: ${cmd} (${typeof cmd})`);
}
try {
return await main(cmd, argv);
} finally {
// If we locked the 'cdk.out' directory, release it here.
await outDirLock?.release();
// Do PSAs here
if (shouldDisplayVersionMessage()) {
await displayVersionMessage(ioHelper);
}
await refreshNotices;
if (cmd === 'notices') {
// do not trap errors here
// this is the notices command itself, any error should be loud
await notices.refresh({ force: true });
await notices.display({
includeAcknowledged: !argv.unacknowledged,
showTotal: argv.unacknowledged,
});
} else if (shouldDisplayNotices && cmd !== 'version') {
await trapErrors(ioHelper, 'Could not display notices', () => notices.display());
}
}
async function main(command: string, args: any): Promise<number | void> {
ioHost.currentAction = command as any;
const toolkitStackName: string = ToolkitInfo.determineName(configuration.settings.get(['toolkitStackName']));
await ioHost.defaults.debug(`Toolkit stack: ${chalk.bold(toolkitStackName)}`);
const cloudFormation = new Deployments({
sdkProvider,
toolkitStackName,
ioHelper: asIoHelper(ioHost, ioHost.currentAction as any),
});
if (args.all && args.STACKS) {
throw new ToolkitError('StacksOrAllRequired', 'You must either specify a list of Stacks or the `--all` argument');
}
args.STACKS = args.STACKS ?? (args.STACK ? [args.STACK] : []);
args.ENVIRONMENTS = args.ENVIRONMENTS ?? [];
const selector: StackSelector = {
allTopLevel: args.all,
patterns: args.STACKS,
};
const cli = new CdkToolkit({
ioHost,
cloudExecutable,
toolkitStackName,
deployments: cloudFormation,
verbose: argv.trace || argv.verbose > 0,
ignoreErrors: argv['ignore-errors'],
strict: argv.strict,
configuration,
sdkProvider,
});
ioHost.telemetry?.markOperationStart();
switch (command) {
case 'context':
ioHost.currentAction = 'context';
return context({
ioHelper,
context: configuration.context,
clear: argv.clear,
json: argv.json,
force: argv.force,
reset: argv.reset,
});
case 'docs':
case 'doc':
ioHost.currentAction = 'docs';
return docs({
ioHelper,
browser: configuration.settings.get(['browser']),
});
case 'doctor':
ioHost.currentAction = 'doctor';
return doctor({
ioHelper,
settings: configuration.settings,
});
case 'ls':
case 'list':
ioHost.currentAction = 'list';
return cli.list(args.STACKS, {
long: args.long,
json: argv.json,
showDeps: args.showDependencies,
});
case 'diff':
ioHost.currentAction = 'diff';
const enableDiffNoFail = isFeatureEnabled(configuration, cxapi.ENABLE_DIFF_NO_FAIL_CONTEXT);
return cli.diff({
stackNames: args.STACKS,
exclusively: args.exclusively,
templatePath: args.template,
strict: args.strict,
contextLines: args.contextLines,
securityOnly: args.securityOnly,
fail: args.fail != null ? args.fail : !enableDiffNoFail,
compareAgainstProcessedTemplate: args.processed,
quiet: args.quiet,
method: determineDiffMethod(args),
toolkitStackName: toolkitStackName,
importExistingResources: args.importExistingResources,
includeMoves: args['include-moves'],
});
case 'drift':
ioHost.currentAction = 'drift';
return cli.drift({
selector,
fail: args.fail,
});
case 'refactor':
cliRequireUnstable(configuration, 'refactor');
ioHost.currentAction = 'refactor';
return cli.refactor({
dryRun: args.dryRun,
overrideFile: args.overrideFile,
revert: args.revert,
stacks: selector,
additionalStackNames: arrayFromYargs(args.additionalStackName ?? []),
force: args.force ?? false,
roleArn: args.roleArn,
});
case 'bootstrap':
ioHost.currentAction = 'bootstrap';
const source: BootstrapSource = await determineBootstrapVersion(ioHost, args);
if (args.showTemplate) {
const bootstrapper = new Bootstrapper(source, asIoHelper(ioHost, ioHost.currentAction));
return bootstrapper.showTemplate(args.json);
}
return cli.bootstrap(args.ENVIRONMENTS, {
source,
roleArn: args.roleArn,
forceDeployment: argv.force,
toolkitStackName: toolkitStackName,
execute: args.execute,
tags: configuration.settings.get(['tags']),
terminationProtection: args.terminationProtection,
usePreviousParameters: args['previous-parameters'],
importExistingResources: args.importExistingResources,
parameters: {
bucketName: configuration.settings.get(['toolkitBucket', 'bucketName']),
kmsKeyId: configuration.settings.get(['toolkitBucket', 'kmsKeyId']),
createCustomerMasterKey: args.bootstrapCustomerKey,
qualifier: args.qualifier ?? configuration.context.get('@aws-cdk/core:bootstrapQualifier'),
publicAccessBlockConfiguration: args.publicAccessBlockConfiguration,
examplePermissionsBoundary: argv.examplePermissionsBoundary,
customPermissionsBoundary: argv.customPermissionsBoundary,
trustedAccounts: arrayFromYargs(args.trust),
trustedAccountsForLookup: arrayFromYargs(args.trustForLookup),
untrustedAccounts: arrayFromYargs(args.untrust),
cloudFormationExecutionPolicies: arrayFromYargs(args.cloudformationExecutionPolicies),
denyExternalId: args.denyExternalId,
},
});
case 'deploy':
ioHost.currentAction = 'deploy';
const parameterMap: { [name: string]: string | undefined } = {};
for (const parameter of args.parameters) {
if (typeof parameter === 'string') {
const keyValue = (parameter as string).split('=');
parameterMap[keyValue[0]] = keyValue.slice(1).join('=');
}
}
if (args.execute !== undefined && args.method !== undefined) {
throw new ToolkitError('ConflictingExecuteAndMethod', 'Can not supply both --[no-]execute and --method at the same time');
}
return cli.deploy({
selector,
exclusively: args.exclusively,
toolkitStackName,
roleArn: args.roleArn,
notificationArns: args.notificationArns,
requireApproval: configuration.settings.get(['requireApproval']),
reuseAssets: args['build-exclude'],
tags: configuration.settings.get(['tags']),
deploymentMethod: determineDeploymentMethod(args, configuration),
force: args.force,
parameters: parameterMap,
usePreviousParameters: args['previous-parameters'],
outputsFile: configuration.settings.get(['outputsFile']),
progress: configuration.settings.get(['progress']),
ci: args.ci,
rollback: configuration.settings.get(['rollback']),
watch: args.watch,
traceLogs: args.logs,
concurrency: args.concurrency,
assetParallelism: configuration.settings.get(['assetParallelism']),
assetBuildConcurrency: configuration.settings.get(['assetBuildConcurrency']),
assetBuildTime: configuration.settings.get(['assetPrebuild'])
? AssetBuildTime.ALL_BEFORE_DEPLOY
: AssetBuildTime.JUST_IN_TIME,
ignoreNoStacks: args.ignoreNoStacks,
});
case 'validate':
cliRequireUnstable(configuration, 'validate');
ioHost.currentAction = 'validate';
configuration.context.set('@aws-cdk/core:failSynthOnValidationErrors', false);
return cli.validate({
stacks: specificStacksOrAllRecursively(args.STACKS),
online: args.online,
});
case 'diagnose':
cliRequireUnstable(configuration, 'diagnose');
ioHost.currentAction = 'diagnose';
// Implicitly switch 'debug' mode to true, that is going to be most useful.
configuration.settings.temporarilyMutable((settings) => {
settings.set(['debug'], true);
});
return cli.diagnose({
stacks: specificStacksOrAllRecursively(args.STACKS),
concurrency: args.concurrency,
toolkitStackName: args.toolkitStackName,
});
case 'rollback':
ioHost.currentAction = 'rollback';
return cli.rollback({
selector,
toolkitStackName,
roleArn: args.roleArn,
force: args.force,
validateBootstrapStackVersion: args['validate-bootstrap-version'],
orphanLogicalIds: args.orphan,
});
case 'publish-assets':
ioHost.currentAction = 'publish-assets';
cliRequireUnstable(configuration, 'publish-assets');
return cli.publishAssets({
stacks: convertStackSelector(selector, args.exclusively),
force: args.force,
concurrency: args.concurrency,
});
case 'orphan':
cliRequireUnstable(configuration, 'orphan');
ioHost.currentAction = 'orphan';
return cli.orphan({
constructPath: args.PATHS ?? [],
roleArn: args.roleArn,
toolkitStackName,
});
case 'import':
ioHost.currentAction = 'import';
return cli.import({
selector,
toolkitStackName,
roleArn: args.roleArn,
deploymentMethod: {
method: 'change-set',
execute: args.execute,
changeSetName: args.changeSetName,
},
progress: configuration.settings.get(['progress']),
rollback: configuration.settings.get(['rollback']),
recordResourceMapping: args['record-resource-mapping'],
resourceMappingFile: args['resource-mapping'],
resourceMappingInline: args['resource-mapping-inline'],
force: args.force,
});
case 'watch':
ioHost.currentAction = 'watch';
await cli.watch({
selector,
exclusively: args.exclusively,
toolkitStackName,
roleArn: args.roleArn,
reuseAssets: args['build-exclude'],
deploymentMethod: determineDeploymentMethod(args, configuration, true),
force: args.force,
progress: configuration.settings.get(['progress']),
rollback: configuration.settings.get(['rollback']),
traceLogs: args.logs,
concurrency: args.concurrency,
});
return;
case 'destroy':
ioHost.currentAction = 'destroy';
return cli.destroy({
selector,
exclusively: args.exclusively,
force: args.force,
roleArn: args.roleArn,
concurrency: args.concurrency,
});
case 'gc':
ioHost.currentAction = 'gc';
cliRequireUnstable(configuration, 'gc');
if (args.bootstrapStackName) {
await ioHost.defaults.warn('--bootstrap-stack-name is deprecated and will be removed when gc is GA. Use --toolkit-stack-name.');
}
// roleArn is defined for when cloudformation is invoked
// This conflicts with direct sdk calls existing in the gc command to s3 and ecr
if (args.roleArn) {
await ioHost.defaults.warn('The --role-arn option is not supported for the gc command and will be ignored.');
}
return cli.garbageCollect(args.ENVIRONMENTS, {
action: args.action,
type: args.type,
rollbackBufferDays: args['rollback-buffer-days'],
createdBufferDays: args['created-buffer-days'],
bootstrapStackName: args.toolkitStackName ?? args.bootstrapStackName,
confirm: args.confirm,
});
case 'flags':
ioHost.currentAction = 'flags';
cliRequireUnstable(configuration, 'flags');
const toolkit = new Toolkit({
ioHost,
toolkitStackName,
unstableFeatures: configuration.settings.get(['unstable']),
});
const flagsData = await toolkit.flags(cloudExecutable);
const handler = new FlagCommandHandler(flagsData, ioHelper, args, toolkit, configuration.context.all);
return handler.processFlagsCommand();
case 'synthesize':
case 'synth':
ioHost.currentAction = 'synth';
const quiet = configuration.settings.get(['quiet']) ?? args.quiet;
if (args.exclusively) {
return cli.synth(args.STACKS, args.exclusively, quiet, args.validation, argv.json);
} else {
return cli.synth(args.STACKS, true, quiet, args.validation, argv.json);
}
case 'notices':
ioHost.currentAction = 'notices';
// If the user explicitly asks for notices, they are now the primary output
// of the command and they should go to stdout.
ioHost.noticesDestination = 'stdout';
// This is a valid command, but we're postponing its execution because displaying
// notices automatically happens after every command.
return;
case 'metadata':
ioHost.currentAction = 'metadata';
return cli.metadata(args.STACK, argv.json);
case 'acknowledge':
case 'ack':
ioHost.currentAction = 'notices';
return cli.acknowledge(args.ID);
case 'cli-telemetry':
ioHost.currentAction = 'cli-telemetry';
if (args.enable === undefined && args.disable === undefined && args.status === undefined) {
throw new ToolkitError('TelemetryArgRequired', 'Must specify \'--enable\', \'--disable\', or \'--status\'');
}
if (args.status) {
return cli.cliTelemetryStatus(args);
} else {
const enable = args.enable ?? !args.disable;
return cli.cliTelemetry(enable);
}
case 'init':
ioHost.currentAction = 'init';
const language = configuration.settings.get(['language']);
if (args.list) {
return printAvailableTemplates(ioHelper, language);
} else {
// Gate custom template support with unstable flag
if (args['from-path']) {
cliRequireUnstable(configuration, 'init');
}
return cliInit({
ioHelper,
type: args.TEMPLATE,
language,
canUseNetwork: undefined,
generateOnly: args.generateOnly,
libVersion: args.libVersion,
fromPath: args['from-path'],
templatePath: args['template-path'],
packageManager: args['package-manager'],
projectName: args.name,
});
}
case 'migrate':
ioHost.currentAction = 'migrate';
return cli.migrate({
stackName: args['stack-name'],
fromPath: args['from-path'],
fromStack: args['from-stack'],
language: args.language,
outputPath: args['output-path'],
fromScan: getMigrateScanType(args['from-scan']),
filter: args.filter,
account: args.account,
region: args.region,
compress: args.compress,
});
case 'version':
ioHost.currentAction = 'version';
return ioHost.defaults.result(versionWithBuild());
default:
throw new ToolkitError('UnknownCommand', 'Unknown command: ' + command);
}
}
}
/**
* Determine which version of bootstrapping
*/
async function determineBootstrapVersion(ioHost: CliIoHost, args: { template?: string }): Promise<BootstrapSource> {
let source: BootstrapSource;
if (args.template) {
await ioHost.defaults.info(`Using bootstrapping template from ${args.template}`);
source = { source: 'custom', templateFile: args.template };
} else if (process.env.CDK_LEGACY_BOOTSTRAP) {
await ioHost.defaults.info('CDK_LEGACY_BOOTSTRAP set, using legacy-style bootstrapping');
source = { source: 'legacy' };
} else {
// in V2, the "new" bootstrapping is the default
source = { source: 'default' };
}
return source;
}
function isFeatureEnabled(configuration: Configuration, featureFlag: string) {
return configuration.context.get(featureFlag) ?? cxapi.futureFlagDefault(featureFlag);
}
/**
* Convert a StackSelector and exclusively flag to toolkit-lib's StackSelector format
*/
function convertStackSelector(selector: StackSelector, exclusively?: boolean): LibStackSelector {
return {
patterns: selector.patterns,
strategy: selector.patterns.length > 0 ? StackSelectionStrategy.PATTERN_MATCH : StackSelectionStrategy.ALL_STACKS,
expand: exclusively ? ExpandStackSelection.NONE : ExpandStackSelection.UPSTREAM,
};
}
/**
* Build a toolkit-lib StackSelector from a given set of stack construct path patterns
*
* If no patterns are given, all stacks in the assembly and all of its stages are selected.
*/
function specificStacksOrAllRecursively(patterns: string[]): LibStackSelector {
return {
strategy: patterns.length > 0 ? StackSelectionStrategy.PATTERN_MATCH : StackSelectionStrategy.ALL_STACKS,
patterns,
};
}
/**
* Translate a Yargs input array to something that makes more sense in a programming language
* model (telling the difference between absence and an empty array)
*
* - An empty array is the default case, meaning the user didn't pass any arguments. We return
* undefined.
* - If the user passed a single empty string, they did something like `--array=`, which we'll
* take to mean they passed an empty array.
*/
function arrayFromYargs(xs: string[]): string[] | undefined {
if (xs.length === 0) {
return undefined;
}
return xs.filter((x) => x !== '');
}
/**
* Resolve the diff method from CLI args.
* --method takes precedence, then deprecated --change-set, then --template implies template.
*/
function determineDiffMethod(args: any): 'change-set' | 'template' | 'auto' {
if (args.method && args.method !== 'auto') {
return args.method;
}
// Deprecated --no-change-set maps to template
if (args['change-set'] === false) {
return 'template';
}
// --template implies template
if (args.template) {
return 'template';
}
return 'auto';
}
function determineDeploymentMethod(args: any, configuration: Configuration, watch?: boolean): DeploymentMethod {
let deploymentMethod: ChangeSetDeployment | DirectDeployment | undefined;
switch (args.method) {
case 'execute-change-set':
if (!args.STACKS || args.STACKS.length !== 1) {
throw new ToolkitError('ExactlyOneStack', '--method=execute-change-set requires exactly one stack');
}
if (watch || args.watch) {
throw new ToolkitError('WatchWithExecuteChangeSet', '--method=execute-change-set cannot be used with watch');
}
rejectIncompatibleOptions(args, '--method=execute-change-set', {
force: '--force',
parameters: '--parameters',
importExistingResources: '--import-existing-resources',
revertDrift: '--revert-drift',
});
return {
method: 'execute-change-set',
changeSetName: args.changeSetName ?? 'cdk-deploy-change-set',
};
case 'direct':
rejectIncompatibleOptions(args, '--method=direct', {
changeSetName: '--change-set-name',
importExistingResources: '--import-existing-resources',
revertDrift: '--revert-drift',
});
deploymentMethod = { method: 'direct' };
break;
case 'change-set':
deploymentMethod = {
method: 'change-set',
execute: true,
changeSetName: args.changeSetName,
importExistingResources: args.importExistingResources,
revertDrift: args.revertDrift,
};
break;
case 'prepare-change-set':
deploymentMethod = {
method: 'change-set',
execute: false,
changeSetName: args.changeSetName,
importExistingResources: args.importExistingResources,
revertDrift: args.revertDrift,
};
break;
case undefined:
default:
deploymentMethod = {
method: 'change-set',
execute: watch ? true : args.execute ?? true,
changeSetName: args.changeSetName,
importExistingResources: args.importExistingResources,
revertDrift: args.revertDrift,
};
break;
}
const hotswapMode = determineHotswapMode(args.hotswap, args.hotswapFallback, watch);
const hotswapProperties = configuration.settings.get(['hotswap']) || {};
switch (hotswapMode) {
case HotswapMode.FALL_BACK:
return {
method: 'hotswap',
properties: hotswapProperties,
fallback: deploymentMethod,
};
case HotswapMode.HOTSWAP_ONLY:
return {
method: 'hotswap',
properties: hotswapProperties,
};
default:
case HotswapMode.FULL_DEPLOYMENT:
return deploymentMethod;
}
}
function cliRequireUnstable(configuration: Configuration, feature: string) {
if (!configuration.settings.get(['unstable']).includes(feature)) {
throw new ToolkitError(`Unstable${ucfirst(feature)}`, `Unstable feature use: \'${feature}\' is unstable. It must be opted in via \'--unstable\', e.g. \'cdk ${feature} --unstable=${feature}\'`);
}
function ucfirst(x: string) {
return x[0].toUpperCase() + x.slice(1);
}
}
/**
* Throw if any of the given flags are set, as they are incompatible with the given option.
*/
function rejectIncompatibleOptions(args: any, option: string, flags: Record<string, string>) {
for (const [key, flag] of Object.entries(flags)) {
const value = args[key];
let isSet = false;
if (Array.isArray(value)) {
// yargs may default array options to [{}], so only count real values
isSet = value.some((v: unknown) => typeof v === 'string' || typeof v === 'number');
} else {
isSet = !!value;
}
if (isSet) {
throw new ToolkitError('IncompatibleOptions', `${flag} cannot be used with ${option}`);
}
}
}
function determineHotswapMode(hotswap?: boolean, hotswapFallback?: boolean, watch?: boolean): HotswapMode {
if (hotswap && hotswapFallback) {
throw new ToolkitError('ConflictingHotswapArgs', 'Can not supply both --hotswap and --hotswap-fallback at the same time');
} else if (!hotswap && !hotswapFallback) {
if (hotswap === undefined && hotswapFallback === undefined) {
return watch ? HotswapMode.HOTSWAP_ONLY : HotswapMode.FULL_DEPLOYMENT;
} else if (hotswap === false || hotswapFallback === false) {
return HotswapMode.FULL_DEPLOYMENT;
}
}
let hotswapMode: HotswapMode;
if (hotswap) {
hotswapMode = HotswapMode.HOTSWAP_ONLY;
/* if (hotswapFallback)*/
} else {
hotswapMode = HotswapMode.FALL_BACK;
}
return hotswapMode;
}
/* c8 ignore start */ // we never call this in unit tests
export function cli(args: string[] = process.argv.slice(2)) {
let error: ErrorDetails | undefined;
exec(args)
.then(async (value) => {
if (typeof value === 'number') {
process.exitCode = value;
}
})
.catch(async (err) => {
// Log the stack trace if we're on a developer workstation. Otherwise this will be into a minified
// file and the printed code line and stack trace are huge and useless.
prettyPrintError(err, isDeveloperBuildVersion());
error = {
name: cdkCliErrorName(err),
};
process.exitCode = 1;
})
.finally(async () => {
try {
await CliIoHost.get()?.telemetry?.end(error);
} catch (e: any) {
await CliIoHost.get()?.asIoHelper().defaults.trace(`Ending Telemetry failed: ${e.message}`);
}
});
}
/* c8 ignore stop */