diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/cloud-assembly/context-store.ts b/packages/@aws-cdk/toolkit-lib/lib/api/cloud-assembly/context-store.ts index 1513a303f..5f1009f68 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/cloud-assembly/context-store.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/cloud-assembly/context-store.ts @@ -2,6 +2,7 @@ import { promises as fs } from 'fs'; import * as os from 'os'; import * as path from 'path'; import { ToolkitError } from '../../toolkit/toolkit-error'; +import { readConfigFileIfExists, resolveConfigFile, resolveProjectConfigFile } from '../../util/config-file'; import type { ContextBag } from '../context'; import { Context } from '../context'; import { Settings, TRANSIENT_CONTEXT_KEY } from '../settings'; @@ -37,22 +38,20 @@ export interface IContextStore { * * - Any context values passed to the constructor (expected * to come from the command line, treated as ephemeral). - * - The `context` key in `/cdk.json`. + * - The `context` key in `/cdk.json` (or `cdk.yaml`). * - `/cdk.context.json`. - * - The `context` key in `~/.cdk.json`. + * - The `context` key in `~/.cdk.json` (or `~/.cdk.yaml`). * * Updates will be written to `/cdk.context.json`. */ export class CdkAppMultiContext implements IContextStore { private _context?: Context; - private configContextFile: string; + private readonly appDirectory: string; private projectContextFile: string; - private userConfigFile: string; constructor(appDirectory: string, private readonly commandlineContext?: Record) { - this.configContextFile = path.join(appDirectory, 'cdk.json'); + this.appDirectory = appDirectory; this.projectContextFile = path.join(appDirectory, 'cdk.context.json'); - this.userConfigFile = path.join(os.homedir() ?? '/tmp', '.cdk.json'); } public async read(): Promise> { @@ -83,19 +82,27 @@ export class CdkAppMultiContext implements IContextStore { return this._context; } + // The two hand-authored files may be written as YAML instead of JSON. + const homeDirectory = os.homedir() ?? '/tmp'; + const { fileName: configContextFile } = await resolveProjectConfigFile(this.appDirectory); + const { fileName: userConfigFile } = await resolveConfigFile( + path.join(homeDirectory, '.cdk.json'), + path.join(homeDirectory, '.cdk.yaml'), + ); + const contextSources: ContextBag[] = [ { bag: new Settings(this.commandlineContext, true) }, { - fileName: this.configContextFile, - bag: (await settingsFromFile(this.configContextFile)).subSettings(['context']).makeReadOnly(), + fileName: configContextFile, + bag: (await settingsFromFile(configContextFile)).subSettings(['context']).makeReadOnly(), }, { fileName: this.projectContextFile, bag: await settingsFromFile(this.projectContextFile), }, { - fileName: this.userConfigFile, - bag: (await settingsFromFile(this.userConfigFile)).subSettings(['context']).makeReadOnly(), + fileName: userConfigFile, + bag: (await settingsFromFile(userConfigFile)).subSettings(['context']).makeReadOnly(), }, ]; @@ -179,13 +186,5 @@ function isTransientValue(x: unknown) { } async function settingsFromFile(filename: string): Promise { - try { - const data = JSON.parse(await fs.readFile(filename, 'utf-8')); - return new Settings(data); - } catch (e: any) { - if (e.code === 'ENOENT') { - return new Settings(); - } - throw e; - } + return new Settings((await readConfigFileIfExists(filename)) ?? {}); } diff --git a/packages/@aws-cdk/toolkit-lib/lib/util/config-file.ts b/packages/@aws-cdk/toolkit-lib/lib/util/config-file.ts new file mode 100644 index 000000000..de309eaf8 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/lib/util/config-file.ts @@ -0,0 +1,181 @@ +import * as os from 'os'; +import * as path from 'path'; +import * as fs from 'fs-extra'; +import * as yaml from 'yaml'; +import { ToolkitError } from '../toolkit/toolkit-error'; + +/** + * The hand-authored project configuration file. + * + * May be written as YAML instead, so that it can carry comments -- which JSON + * cannot. See https://github.com/aws/aws-cdk/issues/15529. + */ +export const PROJECT_CONFIG = 'cdk.json'; + +/** + * The YAML spelling of the project configuration file. + * + * Interchangeable with `PROJECT_CONFIG`. + */ +export const PROJECT_CONFIG_YAML = 'cdk.yaml'; + +/** + * The hand-authored per-user configuration file. + */ +export const USER_DEFAULTS = '~/.cdk.json'; + +/** + * The YAML spelling of the per-user configuration file. + * + * Interchangeable with `USER_DEFAULTS`. + */ +export const USER_DEFAULTS_YAML = '~/.cdk.yaml'; + +const YAML_EXTENSIONS = ['.yaml', '.yml']; + +/** + * Which spelling of an interchangeable config file is in use. + */ +export interface ResolvedConfigFile { + /** + * The file to read. + */ + readonly fileName: string; + + /** + * The other spelling, which exists on disk but is not being read. + * + * Only set when both spellings are present. + */ + readonly ignored?: string; +} + +/** + * Whether a config file is to be parsed as YAML rather than as JSON. + */ +export function isYamlConfigFile(fileName: string): boolean { + return YAML_EXTENSIONS.includes(path.extname(fileName).toLowerCase()); +} + +/** + * Replace a leading `~` with the current user's home directory. + */ +export function expandHomeDir(x: string): string { + if (x.startsWith('~')) { + return path.join(os.homedir(), x.slice(1)); + } + return x; +} + +/** + * Decide which spelling of an interchangeable config file to read. + * + * JSON wins when both files are present, because a project that already has + * both works today by reading the JSON one, and that must keep working. The + * YAML file is reported back as `ignored` so that callers which can reach the + * user are able to say so. + * + * The JSON name is also returned when neither file is present, so that + * messages about an absent or default config keep naming `cdk.json`. + */ +export async function resolveConfigFile(jsonFileName: string, yamlFileName: string): Promise { + const jsonExists = await fs.pathExists(expandHomeDir(jsonFileName)); + const yamlExists = await fs.pathExists(expandHomeDir(yamlFileName)); + + if (jsonExists && yamlExists) { + return { fileName: jsonFileName, ignored: yamlFileName }; + } + + return { fileName: yamlExists ? yamlFileName : jsonFileName }; +} + +/** + * Resolve the project config file in a directory, in whichever format it uses. + */ +export async function resolveProjectConfigFile(directory: string): Promise { + return resolveConfigFile(path.join(directory, PROJECT_CONFIG), path.join(directory, PROJECT_CONFIG_YAML)); +} + +/** + * Read and parse a config file, as JSON or as YAML according to its extension. + * + * The file is expected to exist; use `readConfigFileIfExists` when it may not. + */ +export async function readConfigFile(fileName: string): Promise> { + const expanded = expandHomeDir(fileName); + + if (!isYamlConfigFile(expanded)) { + return fs.readJson(expanded); + } + + const text = await fs.readFile(expanded, { encoding: 'utf-8' }); + + let data: unknown; + try { + data = yaml.parse(text); + } catch (e: any) { + throw new ToolkitError('InvalidConfigFile', `${path.resolve(expanded)} is not valid YAML: ${e.message}`); + } + + // An empty document parses to null, which is the same thing as no settings + if (data == null) { + return {}; + } + + if (typeof data !== 'object' || Array.isArray(data)) { + throw new ToolkitError( + 'InvalidConfigFile', + `expected ${path.resolve(expanded)} to hold a map of settings, found ${Array.isArray(data) ? 'a list' : typeof data}`, + ); + } + + return data as Record; +} + +/** + * Read and parse a config file, returning `undefined` if it does not exist. + */ +export async function readConfigFileIfExists(fileName: string): Promise | undefined> { + try { + return await readConfigFile(fileName); + } catch (e: any) { + if (e.code === 'ENOENT') { + return undefined; + } + throw e; + } +} + +/** + * Set values underneath a key path of a config file, in place. + * + * Keeps the rest of the file as it was, which for YAML includes its comments -- + * the reason the format is accepted at all. Missing keys along `keyPath` are + * created. + */ +export async function setConfigValues( + fileName: string, + keyPath: string[], + values: Record, +): Promise { + const expanded = expandHomeDir(fileName); + const text = await fs.readFile(expanded, { encoding: 'utf-8' }); + + if (isYamlConfigFile(expanded)) { + const doc = yaml.parseDocument(text); + for (const [key, value] of Object.entries(values)) { + doc.setIn([...keyPath, key], value); + } + await fs.writeFile(expanded, doc.toString(), 'utf-8'); + return; + } + + const data = JSON.parse(text); + let target: any = data; + for (const key of keyPath) { + target[key] ??= {}; + target = target[key]; + } + Object.assign(target, values); + await fs.writeFile(expanded, JSON.stringify(data, null, 2), 'utf-8'); +} diff --git a/packages/@aws-cdk/toolkit-lib/test/util/config-file.test.ts b/packages/@aws-cdk/toolkit-lib/test/util/config-file.test.ts new file mode 100644 index 000000000..433e762a8 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/util/config-file.test.ts @@ -0,0 +1,192 @@ +import * as os from 'os'; +import * as path from 'path'; +import * as fs from 'fs-extra'; +import { + PROJECT_CONFIG, + PROJECT_CONFIG_YAML, + isYamlConfigFile, + readConfigFile, + readConfigFileIfExists, + resolveConfigFile, + resolveProjectConfigFile, + setConfigValues, +} from '../../lib/util/config-file'; + +let tmpDir: string; + +beforeEach(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk-config-file-test-')); +}); + +afterEach(async () => { + await fs.remove(tmpDir); +}); + +function p(fileName: string) { + return path.join(tmpDir, fileName); +} + +describe('isYamlConfigFile', () => { + test.each([ + ['cdk.yaml', true], + ['cdk.yml', true], + ['cdk.YAML', true], + ['cdk.json', false], + ['cdk.context.json', false], + ])('%s -> %s', (fileName, expected) => { + expect(isYamlConfigFile(fileName)).toBe(expected); + }); +}); + +describe('resolveConfigFile', () => { + test('returns the JSON name when only the JSON file exists', async () => { + await fs.writeFile(p(PROJECT_CONFIG), '{}'); + + await expect(resolveProjectConfigFile(tmpDir)).resolves.toEqual({ fileName: p(PROJECT_CONFIG) }); + }); + + test('returns the YAML name when only the YAML file exists', async () => { + await fs.writeFile(p(PROJECT_CONFIG_YAML), 'app: cdk-app'); + + await expect(resolveProjectConfigFile(tmpDir)).resolves.toEqual({ fileName: p(PROJECT_CONFIG_YAML) }); + }); + + test('returns the JSON name when neither file exists, so messages keep naming cdk.json', async () => { + await expect(resolveProjectConfigFile(tmpDir)).resolves.toEqual({ fileName: p(PROJECT_CONFIG) }); + }); + + test('JSON keeps winning when both files exist, and the YAML one is reported as ignored', async () => { + // A project that has both files today is read from the JSON one; that must + // not change into an error. + await fs.writeFile(p(PROJECT_CONFIG), '{}'); + await fs.writeFile(p(PROJECT_CONFIG_YAML), 'app: cdk-app'); + + await expect(resolveProjectConfigFile(tmpDir)).resolves.toEqual({ + fileName: p(PROJECT_CONFIG), + ignored: p(PROJECT_CONFIG_YAML), + }); + }); + + test('expands a home directory reference before testing for existence', async () => { + // `~/.cdk.json` is not expected to exist in the test environment, but the + // call must not treat the literal `~` as a directory name either. + await expect(resolveConfigFile('~/.cdk.json', '~/.cdk.yaml')).resolves.toEqual({ fileName: '~/.cdk.json' }); + }); +}); + +describe('readConfigFile', () => { + test('parses JSON', async () => { + await fs.writeFile(p('cdk.json'), JSON.stringify({ app: 'node bin/app.js', context: { foo: 'bar' } })); + + await expect(readConfigFile(p('cdk.json'))).resolves.toEqual({ + app: 'node bin/app.js', + context: { foo: 'bar' }, + }); + }); + + test('parses YAML, including comments which are simply dropped from the data', async () => { + await fs.writeFile(p('cdk.yaml'), [ + '# the app to synth', + 'app: node bin/app.js', + 'context:', + ' # why this flag is off', + ' some-flag: false', + ' nested:', + ' list:', + ' - a', + ' - b', + ].join('\n')); + + await expect(readConfigFile(p('cdk.yaml'))).resolves.toEqual({ + app: 'node bin/app.js', + context: { + 'some-flag': false, + 'nested': { list: ['a', 'b'] }, + }, + }); + }); + + test('an empty YAML file reads as no settings', async () => { + await fs.writeFile(p('cdk.yaml'), '# nothing but a comment\n'); + + await expect(readConfigFile(p('cdk.yaml'))).resolves.toEqual({}); + }); + + test('invalid YAML is reported against the file name', async () => { + await fs.writeFile(p('cdk.yaml'), 'app: [unclosed\n'); + + await expect(readConfigFile(p('cdk.yaml'))).rejects.toThrow(/cdk\.yaml is not valid YAML/); + }); + + test('a YAML file that is not a map is rejected', async () => { + await fs.writeFile(p('cdk.yaml'), '- one\n- two\n'); + + await expect(readConfigFile(p('cdk.yaml'))).rejects.toThrow(/to hold a map of settings, found a list/); + }); + + test('readConfigFileIfExists returns undefined for an absent file', async () => { + await expect(readConfigFileIfExists(p('cdk.yaml'))).resolves.toBeUndefined(); + await expect(readConfigFileIfExists(p('cdk.json'))).resolves.toBeUndefined(); + }); +}); + +describe('setConfigValues', () => { + test('writes JSON with two-space indentation', async () => { + await fs.writeFile(p('cdk.json'), JSON.stringify({ app: 'node bin/app.js' }, null, 2)); + + await setConfigValues(p('cdk.json'), ['context'], { 'a-flag': true }); + + expect(await fs.readFile(p('cdk.json'), 'utf-8')).toEqual([ + '{', + ' "app": "node bin/app.js",', + ' "context": {', + ' "a-flag": true', + ' }', + '}', + ].join('\n')); + }); + + test('creates the parent key when it is missing', async () => { + await fs.writeFile(p('cdk.json'), '{}'); + + await setConfigValues(p('cdk.json'), ['context'], { 'a-flag': false }); + + await expect(readConfigFile(p('cdk.json'))).resolves.toEqual({ context: { 'a-flag': false } }); + }); + + test('keeps YAML comments when updating a value', async () => { + await fs.writeFile(p('cdk.yaml'), [ + '# The app to synthesize.', + 'app: node bin/app.js', + '', + 'context:', + ' # Left off deliberately until the migration lands.', + ' some-flag: false', + ].join('\n') + '\n'); + + await setConfigValues(p('cdk.yaml'), ['context'], { 'some-flag': true, 'other-flag': true }); + + const after = await fs.readFile(p('cdk.yaml'), 'utf-8'); + expect(after).toContain('# The app to synthesize.'); + expect(after).toContain('# Left off deliberately until the migration lands.'); + expect(after).toContain('some-flag: true'); + expect(after).toContain('other-flag: true'); + await expect(readConfigFile(p('cdk.yaml'))).resolves.toEqual({ + app: 'node bin/app.js', + context: { 'some-flag': true, 'other-flag': true }, + }); + }); + + test('creates the parent key in YAML when it is missing', async () => { + await fs.writeFile(p('cdk.yaml'), '# only an app\napp: node bin/app.js\n'); + + await setConfigValues(p('cdk.yaml'), ['context'], { 'a-flag': true }); + + const after = await fs.readFile(p('cdk.yaml'), 'utf-8'); + expect(after).toContain('# only an app'); + await expect(readConfigFile(p('cdk.yaml'))).resolves.toEqual({ + app: 'node bin/app.js', + context: { 'a-flag': true }, + }); + }); +}); diff --git a/packages/aws-cdk/README.md b/packages/aws-cdk/README.md index e6871dfb3..f4499ffd9 100644 --- a/packages/aws-cdk/README.md +++ b/packages/aws-cdk/README.md @@ -1977,12 +1977,12 @@ if you set the profile name as the value of `AWS_PROFILE` or pass it to `--profi ## Configuration -On top of passing configuration through command-line arguments, it is possible to use JSON configuration files. The -configuration's order of precedence is: +On top of passing configuration through command-line arguments, it is possible to use configuration files, written in +either JSON or YAML. The configuration's order of precedence is: 1. Command-line arguments -2. Project configuration (`./cdk.json`) -3. User configuration (`~/.cdk.json`) +2. Project configuration (`./cdk.json`, or `./cdk.yaml`) +3. User configuration (`~/.cdk.json`, or `~/.cdk.yaml`) ### JSON Configuration files @@ -2012,6 +2012,30 @@ This can be used to build Lambda Functions, CDK Application code, or other asset and must be specified in the Project configuration. The command specified in `build` will be executed by the "watch" process before deployment. +### YAML configuration files + +The project and user configuration may be written as YAML instead, as `cdk.yaml` and `~/.cdk.yaml`. The keys are the +same as in the JSON form; the only difference is that YAML can carry comments, which is useful for recording why a +setting or a feature flag is the way it is: + +```yaml +app: node bin/main.js + +context: + # Turned off until the VPC migration in JIRA-1234 is finished; turning it on + # replaces the subnets. + '@aws-cdk/aws-ec2:someFeatureFlag': false +``` + +Notes: + +- `cdk.context.json` is always JSON. It is a cache of context provider lookups that the CLI writes, rather than a file + meant to be edited by hand; manage it with the `cdk context` command. +- If both spellings of a file exist, the JSON one is used and the CLI warns that the YAML one is being ignored. Keep + only one of the two. +- `cdk flags --set` rewrites a YAML configuration in place and leaves its comments intact. +- `cdk init` still generates `cdk.json`. Rename it to `cdk.yaml` and convert the contents if you prefer YAML. + ### Environment The following environment variables affect aws-cdk: diff --git a/packages/aws-cdk/lib/api-private.ts b/packages/aws-cdk/lib/api-private.ts index 4eb65e730..5330f4d0f 100644 --- a/packages/aws-cdk/lib/api-private.ts +++ b/packages/aws-cdk/lib/api-private.ts @@ -6,6 +6,19 @@ export { ChangeSetDescriber } from '../../@aws-cdk/toolkit-lib/lib/api/change-se export { Diagnosis } from '../../@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis'; export type { ChangeSetReport } from '../../@aws-cdk/toolkit-lib/lib/api/change-sets'; export { createIgnoreMatcher } from '../../@aws-cdk/toolkit-lib/lib/util/glob-matcher'; +export { + PROJECT_CONFIG, + PROJECT_CONFIG_YAML, + USER_DEFAULTS, + USER_DEFAULTS_YAML, + expandHomeDir, + isYamlConfigFile, + readConfigFile, + readConfigFileIfExists, + resolveConfigFile, + resolveProjectConfigFile, + setConfigValues, +} from '../../@aws-cdk/toolkit-lib/lib/util/config-file'; export { formatExpressStabilizationWarning } from '../../@aws-cdk/toolkit-lib/lib/util/cfn-express'; export { toCloudFormationRollbackConfiguration } from '../../@aws-cdk/toolkit-lib/lib/util/cloudformation'; export * from '../../@aws-cdk/toolkit-lib/lib/api/io/private'; diff --git a/packages/aws-cdk/lib/cli/user-configuration.ts b/packages/aws-cdk/lib/cli/user-configuration.ts index 4a54d0b84..10377c12f 100644 --- a/packages/aws-cdk/lib/cli/user-configuration.ts +++ b/packages/aws-cdk/lib/cli/user-configuration.ts @@ -1,4 +1,3 @@ -import * as os from 'os'; import * as fs_path from 'path'; import { ToolkitError } from '@aws-cdk/toolkit-lib'; import * as fs from 'fs-extra'; @@ -6,10 +5,23 @@ import { Context, PROJECT_CONTEXT } from '../api/context'; import { Settings } from '../api/settings'; import type { Tag } from '../api/tags'; import type { IoHelper } from '../api-private'; - -export const PROJECT_CONFIG = 'cdk.json'; +import { + PROJECT_CONFIG, + PROJECT_CONFIG_YAML, + USER_DEFAULTS, + USER_DEFAULTS_YAML, + expandHomeDir, + readConfigFile, + resolveConfigFile, +} from '../api-private'; + +export { + PROJECT_CONFIG, + PROJECT_CONFIG_YAML, + USER_DEFAULTS, + USER_DEFAULTS_YAML, +} from '../api-private'; export { PROJECT_CONTEXT } from '../api/context'; -export const USER_DEFAULTS = '~/.cdk.json'; const CONTEXT_KEY = 'context'; export enum Command { @@ -161,28 +173,45 @@ export class Configuration { * Load all config */ private async loadConfigFiles(readUserContext: boolean): Promise { - const userConfig = await loadAndLog(this.ioHelper, USER_DEFAULTS); - this._projectConfig = await loadAndLog(this.ioHelper, PROJECT_CONFIG); + // Both config files may be written as YAML instead of JSON. Resolve which + // spelling is in use first, so that every message and every context source + // below names the file the user actually has. + const userDefaults = await resolveConfigFile(USER_DEFAULTS, USER_DEFAULTS_YAML); + const projectSettings = await resolveConfigFile(PROJECT_CONFIG, PROJECT_CONFIG_YAML); + const userDefaultsFile = userDefaults.fileName; + const projectConfigFile = projectSettings.fileName; + + for (const resolved of [projectSettings, userDefaults]) { + if (resolved.ignored) { + await this.ioHelper.defaults.warning( + `ignoring ${fs_path.resolve(expandHomeDir(resolved.ignored))} because ` + + `${fs_path.resolve(expandHomeDir(resolved.fileName))} also exists; remove one of the two`, + ); + } + } + + const userConfig = await loadAndLog(this.ioHelper, userDefaultsFile); + this._projectConfig = await loadAndLog(this.ioHelper, projectConfigFile); this._projectContext = await loadAndLog(this.ioHelper, PROJECT_CONTEXT); if (userConfig.get(['build'])) { throw new ToolkitError( 'BuildKeyInUserConfig', - 'The `build` key cannot be specified in the user config (~/.cdk.json), specify it in the project config (cdk.json) instead', + `The \`build\` key cannot be specified in the user config (${userDefaultsFile}), specify it in the project config (${projectConfigFile}) instead`, ); } const contextSources = [ { bag: this.commandLineContext }, { - fileName: PROJECT_CONFIG, + fileName: projectConfigFile, bag: this.projectConfig.subSettings([CONTEXT_KEY]).makeReadOnly(), }, { fileName: PROJECT_CONTEXT, bag: this.projectContext }, ]; if (readUserContext) { contextSources.push({ - fileName: USER_DEFAULTS, + fileName: userDefaultsFile, bag: userConfig.subSettings([CONTEXT_KEY]).makeReadOnly(), }); } @@ -238,8 +267,7 @@ async function settingsFromFile(ioHelper: IoHelper, fileName: string): Promise { - const cdkJson = await JSON.parse(await fs.readFile(path.join(process.cwd(), 'cdk.json'), 'utf-8')); - this.app = params.app || cdkJson.app; + const cdkJson = await readConfigFile((await resolveProjectConfigFile(process.cwd())).fileName); + this.app = params.app || (cdkJson.app as string); const isUsingTsNode = this.app.includes('ts-node'); if (isUsingTsNode && !this.app.includes('-T') && !this.app.includes('--transpileOnly')) { @@ -277,8 +278,8 @@ export class FlagOperations { const baseContextValues = { ...await baseContext.read(), ...this.cliContextValues }; const memoryContext = new MemoryContext(baseContextValues); - const cdkJson = await JSON.parse(await fs.readFile(path.join(process.cwd(), 'cdk.json'), 'utf-8')); - const app = cdkJson.app; + const cdkJson = await readConfigFile((await resolveProjectConfigFile(process.cwd())).fileName); + const app = cdkJson.app as string; this.originalTempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cdk-original-')); const source = await this.toolkit.fromCdkApp(app, { @@ -395,27 +396,26 @@ export class FlagOperations { } } - /** Actually modifies the cdk.json file with the new flag values */ + /** Actually modifies the project config file with the new flag values */ private async modifyValues(flagNames: string[], params: FlagOperationsParams): Promise { - const cdkJsonPath = path.join(process.cwd(), 'cdk.json'); - const cdkJsonContent = await fs.readFile(cdkJsonPath, 'utf-8'); - const cdkJson = JSON.parse(cdkJsonContent); - cdkJson.context ??= {}; + const { fileName: configFile } = await resolveProjectConfigFile(process.cwd()); + const values: Record = {}; if (flagNames.length === 1 && params.value !== undefined && !params.safe && !params.all) { const boolValue = params.value === 'true'; - cdkJson.context[String(flagNames[0])] = boolValue; + values[String(flagNames[0])] = boolValue; await this.ioHelper.defaults.info(`Setting flag '${flagNames}' to: ${boolValue}`); } else { for (const flagName of flagNames) { const flag = this.flags.find(f => f.name === flagName)!; - const newValue = params.recommended || params.safe + values[flagName] = params.recommended || params.safe ? flag.recommendedValue as boolean : String(defaultValue(flag)) === 'true'; - cdkJson.context[flagName] = newValue; } } - await fs.writeFile(cdkJsonPath, JSON.stringify(cdkJson, null, 2), 'utf-8'); + + // Writes YAML back as YAML, keeping the file's comments intact. + await setConfigValues(configFile, ['context'], values); } /** Displays flags in a table format, either specific flags or filtered by criteria */ diff --git a/packages/aws-cdk/test/cli/user-config.test.ts b/packages/aws-cdk/test/cli/user-config.test.ts index 7f1ca7c5c..ba26b91a8 100644 --- a/packages/aws-cdk/test/cli/user-config.test.ts +++ b/packages/aws-cdk/test/cli/user-config.test.ts @@ -3,9 +3,15 @@ import * as os from 'os'; import * as fs_path from 'path'; import * as fs from 'fs-extra'; import type { Arguments, Command } from '../../lib/cli/user-configuration'; -import { Configuration, PROJECT_CONFIG, PROJECT_CONTEXT } from '../../lib/cli/user-configuration'; +import { + Configuration, + PROJECT_CONFIG, + PROJECT_CONFIG_YAML, + PROJECT_CONTEXT, + USER_DEFAULTS_YAML, +} from '../../lib/cli/user-configuration'; import { parseCommandLineArguments } from '../../lib/cli/parse-command-line-arguments'; -import { TestIoHost } from '../_helpers/io-host'; +import { TestIoHost, expectIoMsg } from '../_helpers/io-host'; // mock fs deeply jest.mock('fs-extra'); @@ -256,3 +262,103 @@ test('a `debug: true` config file setting implies both debug targets', async () expect(config.settings.get(['debugApp'])).toBe(true); expect(config.settings.get(['debugCli'])).toBe(true); }); + +describe('YAML config files', () => { + const USER_CONFIG_YAML = fs_path.join(os.homedir(), '.cdk.yaml'); + + /** + * Serve the given files, parsing YAML ones for real and handing JSON ones + * back as already-parsed objects, the way the tests above do. + */ + function givenFiles(files: Map) { + mockedFs.pathExists.mockImplementation(path => { + return files.has(path as string); + }); + mockedFs.readJSON.mockImplementation(((path: string) => { + return files.get(path); + }) as any); + mockedFs.readFile.mockImplementation(((path: string) => { + return Promise.resolve(files.get(path)); + }) as any); + } + + test('settings are read from cdk.yaml', async () => { + // GIVEN + givenFiles(new Map([ + [PROJECT_CONFIG_YAML, [ + '# which app to synth', + 'app: node bin/app.js', + 'quiet: true', + ].join('\n')], + ])); + + // WHEN + const config = await Configuration.fromArgsAndFiles(ioHelper); + + // THEN + expect(config.settings.get(['app'])).toEqual('node bin/app.js'); + expect(config.settings.get(['quiet'])).toBe(true); + }); + + test('context is read from cdk.yaml and ~/.cdk.yaml', async () => { + // GIVEN + givenFiles(new Map([ + [PROJECT_CONFIG_YAML, 'context:\n # a comment\n project-key: project-value\n'], + [USER_CONFIG_YAML, 'context:\n user-key: user-value\n'], + ])); + + // WHEN + const config = await Configuration.fromArgsAndFiles(ioHelper); + + // THEN + expect(config.context.get('project-key')).toEqual('project-value'); + expect(config.context.get('user-key')).toEqual('user-value'); + // Reported under the name they are configured by, not the expanded path, + // which is how the JSON spelling has always been reported. + expect(config.contextSourceFiles).toEqual([PROJECT_CONFIG_YAML, USER_DEFAULTS_YAML]); + }); + + test('with both a JSON and a YAML project config, JSON still wins and the YAML one is called out', async () => { + // GIVEN + ioHost.notifySpy.mockClear(); + givenFiles(new Map([ + [PROJECT_CONFIG, { app: 'from json' }], + [PROJECT_CONFIG_YAML, 'app: from yaml\n'], + ])); + + // WHEN + const config = await Configuration.fromArgsAndFiles(ioHelper); + + // THEN + expect(config.settings.get(['app'])).toEqual('from json'); + expect(ioHost.notifySpy).toHaveBeenCalledWith(expectIoMsg( + expect.stringMatching(/ignoring .*cdk\.yaml because .*cdk\.json also exists/), + 'warn', + )); + }); + + test('the `build` key error names the YAML file the user actually has', async () => { + // GIVEN + givenFiles(new Map([ + [USER_CONFIG_YAML, 'build: foobar\n'], + ])); + + // THEN + await expect(Configuration.fromArgsAndFiles(ioHelper)).rejects.toThrow( + 'The `build` key cannot be specified in the user config (~/.cdk.yaml), specify it in the project config (cdk.json) instead', + ); + }); + + test('JSON is still read when no YAML file is present', async () => { + // GIVEN + givenFiles(new Map([ + [PROJECT_CONFIG, { app: 'from json' }], + ])); + + // WHEN + const config = await Configuration.fromArgsAndFiles(ioHelper); + + // THEN + expect(config.settings.get(['app'])).toEqual('from json'); + }); +});