Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 `<appDirectory>/cdk.json`.
* - The `context` key in `<appDirectory>/cdk.json` (or `cdk.yaml`).
* - `<appDirectory>/cdk.context.json`.
* - The `context` key in `~/.cdk.json`.
* - The `context` key in `~/.cdk.json` (or `~/.cdk.yaml`).
*
* Updates will be written to `<appDirectory>/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<string, unknown>) {
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<Record<string, unknown>> {
Expand Down Expand Up @@ -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(),
},
];

Expand Down Expand Up @@ -179,13 +186,5 @@ function isTransientValue(x: unknown) {
}

async function settingsFromFile(filename: string): Promise<Settings> {
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)) ?? {});
}
181 changes: 181 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/util/config-file.ts
Original file line number Diff line number Diff line change
@@ -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<ResolvedConfigFile> {
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<ResolvedConfigFile> {
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<Record<string, unknown>> {
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<string, unknown>;
}

/**
* Read and parse a config file, returning `undefined` if it does not exist.
*/
export async function readConfigFileIfExists(fileName: string): Promise<Record<string, unknown> | 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<string, unknown>,
): Promise<void> {
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');
}
Loading
Loading