-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
settings.ts
484 lines (413 loc) · 13.1 KB
/
settings.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
import * as os from 'os';
import * as fs_path from 'path';
import * as fs from 'fs-extra';
import { Tag } from './cdk-toolkit';
import { debug, warning } from './logging';
import * as util from './util';
export type SettingsMap = {[key: string]: any};
export const PROJECT_CONFIG = 'cdk.json';
export const PROJECT_CONTEXT = 'cdk.context.json';
export const USER_DEFAULTS = '~/.cdk.json';
/**
* If a context value is an object with this key set to a truthy value, it won't be saved to cdk.context.json
*/
export const TRANSIENT_CONTEXT_KEY = '$dontSaveContext';
const CONTEXT_KEY = 'context';
export enum Command {
LS = 'ls',
LIST = 'list',
DIFF = 'diff',
BOOTSTRAP = 'bootstrap',
DEPLOY = 'deploy',
DESTROY = 'destroy',
SYNTHESIZE = 'synthesize',
SYNTH = 'synth',
METADATA = 'metadata',
INIT = 'init',
VERSION = 'version',
WATCH = 'watch',
}
const BUNDLING_COMMANDS = [
Command.DEPLOY,
Command.DIFF,
Command.SYNTH,
Command.SYNTHESIZE,
Command.WATCH,
];
export type Arguments = {
readonly _: [Command, ...string[]];
readonly exclusively?: boolean;
readonly STACKS?: string[];
readonly lookups?: boolean;
readonly [name: string]: unknown;
};
export interface ConfigurationProps {
/**
* Configuration passed via command line arguments
*
* @default - Nothing passed
*/
readonly commandLineArguments?: Arguments;
/**
* Whether or not to use context from `.cdk.json` in user home directory
*
* @default true
*/
readonly readUserContext?: boolean;
}
/**
* All sources of settings combined
*/
export class Configuration {
public settings = new Settings();
public context = new Context();
public readonly defaultConfig = new Settings({
versionReporting: true,
pathMetadata: true,
output: 'cdk.out',
});
private readonly commandLineArguments: Settings;
private readonly commandLineContext: Settings;
private _projectConfig?: Settings;
private _projectContext?: Settings;
private loaded = false;
constructor(private readonly props: ConfigurationProps = {}) {
this.commandLineArguments = props.commandLineArguments
? Settings.fromCommandLineArguments(props.commandLineArguments)
: new Settings();
this.commandLineContext = this.commandLineArguments.subSettings([CONTEXT_KEY]).makeReadOnly();
}
private get projectConfig() {
if (!this._projectConfig) {
throw new Error('#load has not been called yet!');
}
return this._projectConfig;
}
private get projectContext() {
if (!this._projectContext) {
throw new Error('#load has not been called yet!');
}
return this._projectContext;
}
/**
* Load all config
*/
public async load(): Promise<this> {
const userConfig = await loadAndLog(USER_DEFAULTS);
this._projectConfig = await loadAndLog(PROJECT_CONFIG);
this._projectContext = await loadAndLog(PROJECT_CONTEXT);
const readUserContext = this.props.readUserContext ?? true;
if (userConfig.get(['build'])) {
throw new Error('The `build` key cannot be specified in the user config (~/.cdk.json), specify it in the project config (cdk.json) instead');
}
const contextSources = [
this.commandLineContext,
this.projectConfig.subSettings([CONTEXT_KEY]).makeReadOnly(),
this.projectContext,
];
if (readUserContext) {
contextSources.push(userConfig.subSettings([CONTEXT_KEY]).makeReadOnly());
}
this.context = new Context(...contextSources);
// Build settings from what's left
this.settings = this.defaultConfig
.merge(userConfig)
.merge(this.projectConfig)
.merge(this.commandLineArguments)
.makeReadOnly();
debug('merged settings:', this.settings.all);
this.loaded = true;
return this;
}
/**
* Save the project context
*/
public async saveContext(): Promise<this> {
if (!this.loaded) { return this; } // Avoid overwriting files with nothing
await this.projectContext.save(PROJECT_CONTEXT);
return this;
}
}
async function loadAndLog(fileName: string): Promise<Settings> {
const ret = new Settings();
await ret.load(fileName);
if (!ret.empty) {
debug(fileName + ':', JSON.stringify(ret.all, undefined, 2));
}
return ret;
}
/**
* Class that supports overlaying property bags
*
* Reads come from the first property bag that can has the given key,
* writes go to the first property bag that is not readonly. A write
* will remove the value from all property bags after the first
* writable one.
*/
export class Context {
private readonly bags: Settings[];
constructor(...bags: Settings[]) {
this.bags = bags.length > 0 ? bags : [new Settings()];
}
public get keys(): string[] {
return Object.keys(this.all);
}
public has(key: string) {
return this.keys.indexOf(key) > -1;
}
public get all(): {[key: string]: any} {
let ret = new Settings();
// In reverse order so keys to the left overwrite keys to the right of them
for (const bag of [...this.bags].reverse()) {
ret = ret.merge(bag);
}
return ret.all;
}
public get(key: string): any {
for (const bag of this.bags) {
const v = bag.get([key]);
if (v !== undefined) { return v; }
}
return undefined;
}
public set(key: string, value: any) {
for (const bag of this.bags) {
if (bag.readOnly) { continue; }
// All bags past the first one have the value erased
bag.set([key], value);
value = undefined;
}
}
public unset(key: string) {
this.set(key, undefined);
}
public clear() {
for (const key of this.keys) {
this.unset(key);
}
}
}
/**
* A single bag of settings
*/
export class Settings {
/**
* Parse Settings out of CLI arguments.
*
* CLI arguments in must be accessed in the CLI code via
* `configuration.settings.get(['argName'])` instead of via `args.argName`.
*
* The advantage is that they can be configured via `cdk.json` and
* `$HOME/.cdk.json`. Arguments not listed below and accessed via this object
* can only be specified on the command line.
*
* @param argv the received CLI arguments.
* @returns a new Settings object.
*/
public static fromCommandLineArguments(argv: Arguments): Settings {
const context = this.parseStringContextListToObject(argv);
const tags = this.parseStringTagsListToObject(expectStringList(argv.tags));
// Determine bundling stacks
let bundlingStacks: string[];
if (BUNDLING_COMMANDS.includes(argv._[0])) {
// If we deploy, diff, synth or watch a list of stacks exclusively we skip
// bundling for all other stacks.
bundlingStacks = argv.exclusively
? argv.STACKS ?? ['**']
: ['**'];
} else { // Skip bundling for all stacks
bundlingStacks = [];
}
return new Settings({
app: argv.app,
browser: argv.browser,
build: argv.build,
context,
debug: argv.debug,
tags,
language: argv.language,
pathMetadata: argv.pathMetadata,
assetMetadata: argv.assetMetadata,
profile: argv.profile,
plugin: argv.plugin,
requireApproval: argv.requireApproval,
toolkitStackName: argv.toolkitStackName,
toolkitBucket: {
bucketName: argv.bootstrapBucketName,
kmsKeyId: argv.bootstrapKmsKeyId,
},
versionReporting: argv.versionReporting,
staging: argv.staging,
output: argv.output,
outputsFile: argv.outputsFile,
progress: argv.progress,
bundlingStacks,
lookups: argv.lookups,
rollback: argv.rollback,
notices: argv.notices,
assetParallelism: argv['asset-parallelism'],
});
}
public static mergeAll(...settings: Settings[]): Settings {
let ret = new Settings();
for (const setting of settings) {
ret = ret.merge(setting);
}
return ret;
}
private static parseStringContextListToObject(argv: Arguments): any {
const context: any = {};
for (const assignment of ((argv as any).context || [])) {
const parts = assignment.split(/=(.*)/, 2);
if (parts.length === 2) {
debug('CLI argument context: %s=%s', parts[0], parts[1]);
if (parts[0].match(/^aws:.+/)) {
throw new Error(`User-provided context cannot use keys prefixed with 'aws:', but ${parts[0]} was provided.`);
}
context[parts[0]] = parts[1];
} else {
warning('Context argument is not an assignment (key=value): %s', assignment);
}
}
return context;
}
/**
* Parse tags out of arguments
*
* Return undefined if no tags were provided, return an empty array if only empty
* strings were provided
*/
private static parseStringTagsListToObject(argTags: string[] | undefined): Tag[] | undefined {
if (argTags === undefined) { return undefined; }
if (argTags.length === 0) { return undefined; }
const nonEmptyTags = argTags.filter(t => t !== '');
if (nonEmptyTags.length === 0) { return []; }
const tags: Tag[] = [];
for (const assignment of nonEmptyTags) {
const parts = assignment.split('=', 2);
if (parts.length === 2) {
debug('CLI argument tags: %s=%s', parts[0], parts[1]);
tags.push({
Key: parts[0],
Value: parts[1],
});
} else {
warning('Tags argument is not an assignment (key=value): %s', assignment);
}
}
return tags.length > 0 ? tags : undefined;
}
constructor(private settings: SettingsMap = {}, public readonly readOnly = false) {}
public async load(fileName: string): Promise<this> {
if (this.readOnly) {
throw new Error(`Can't load ${fileName}: settings object is readonly`);
}
this.settings = {};
const expanded = expandHomeDir(fileName);
if (await fs.pathExists(expanded)) {
this.settings = await fs.readJson(expanded);
}
// See https://github.com/aws/aws-cdk/issues/59
this.prohibitContextKey('default-account', fileName);
this.prohibitContextKey('default-region', fileName);
this.warnAboutContextKey('aws:', fileName);
return this;
}
public async save(fileName: string): Promise<this> {
const expanded = expandHomeDir(fileName);
await fs.writeJson(expanded, stripTransientValues(this.settings), { spaces: 2 });
return this;
}
public get all(): any {
return this.get([]);
}
public merge(other: Settings): Settings {
return new Settings(util.deepMerge(this.settings, other.settings));
}
public subSettings(keyPrefix: string[]) {
return new Settings(this.get(keyPrefix) || {}, false);
}
public makeReadOnly(): Settings {
return new Settings(this.settings, true);
}
public clear() {
if (this.readOnly) {
throw new Error('Cannot clear(): settings are readonly');
}
this.settings = {};
}
public get empty(): boolean {
return Object.keys(this.settings).length === 0;
}
public get(path: string[]): any {
return util.deepClone(util.deepGet(this.settings, path));
}
public set(path: string[], value: any): Settings {
if (this.readOnly) {
throw new Error(`Can't set ${path}: settings object is readonly`);
}
if (path.length === 0) {
// deepSet can't handle this case
this.settings = value;
} else {
util.deepSet(this.settings, path, value);
}
return this;
}
public unset(path: string[]) {
this.set(path, undefined);
}
private prohibitContextKey(key: string, fileName: string) {
if (!this.settings.context) { return; }
if (key in this.settings.context) {
// eslint-disable-next-line max-len
throw new Error(`The 'context.${key}' key was found in ${fs_path.resolve(fileName)}, but it is no longer supported. Please remove it.`);
}
}
private warnAboutContextKey(prefix: string, fileName: string) {
if (!this.settings.context) { return; }
for (const contextKey of Object.keys(this.settings.context)) {
if (contextKey.startsWith(prefix)) {
// eslint-disable-next-line max-len
warning(`A reserved context key ('context.${prefix}') key was found in ${fs_path.resolve(fileName)}, it might cause surprising behavior and should be removed.`);
}
}
}
}
function expandHomeDir(x: string) {
if (x.startsWith('~')) {
return fs_path.join(os.homedir(), x.slice(1));
}
return x;
}
/**
* Return all context value that are not transient context values
*/
function stripTransientValues(obj: {[key: string]: any}) {
const ret: any = {};
for (const [key, value] of Object.entries(obj)) {
if (!isTransientValue(value)) {
ret[key] = value;
}
}
return ret;
}
/**
* Return whether the given value is a transient context value
*
* Values that are objects with a magic key set to a truthy value are considered transient.
*/
function isTransientValue(value: any) {
return typeof value === 'object' && value !== null && (value as any)[TRANSIENT_CONTEXT_KEY];
}
function expectStringList(x: unknown): string[] | undefined {
if (x === undefined) { return undefined; }
if (!Array.isArray(x)) {
throw new Error(`Expected array, got '${x}'`);
}
const nonStrings = x.filter(e => typeof e !== 'string');
if (nonStrings.length > 0) {
throw new Error(`Expected list of strings, found ${nonStrings}`);
}
return x;
}