Skip to content

Commit fbb237e

Browse files
authored
refactor(cli): organize code that should only be used by the CLI into a folder (#33138)
### Reason for this change This PR is separating the code that should only be used by the CLI into a specific folder. It's currently quite hard to reason about the existing api code as its spread across many files and deep subpath imports. The change deliberately gives up on potential feature reusability of some helpers in order to create locality. Similar to #33094 ### Description of changes Collating existing files and APIs that should only be used by the CLI into a new `cli` folder. Updated imports accordingly. No functional changes. ### Describe any new or updated permissions being added n/a ### Description of how you validated changes exiting tests ### Checklist - [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md) ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
1 parent bdb4a59 commit fbb237e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+1051
-2818
lines changed

packages/@aws-cdk/cli-lib-alpha/THIRD_PARTY_LICENSES

Lines changed: 72 additions & 1923 deletions
Large diffs are not rendered by default.
Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,39 @@
11
/* eslint-disable import/no-restricted-paths */
2-
export { formatErrorMessage } from '../../../../aws-cdk/lib/util/error';
3-
export { DEFAULT_TOOLKIT_STACK_NAME, SdkProvider } from '../../../../aws-cdk/lib/api';
4-
export type { SuccessfulDeployStackResult } from '../../../../aws-cdk/lib/api';
5-
export { formatSdkLoggerContent } from '../../../../aws-cdk/lib/api/aws-auth/sdk-logger';
6-
export { CloudAssembly, sanitizePatterns, StackCollection, ExtendedStackSelection } from '../../../../aws-cdk/lib/api/cxapp/cloud-assembly';
7-
export { prepareDefaultEnvironment, prepareContext, spaceAvailableForContext } from '../../../../aws-cdk/lib/api/cxapp/exec';
8-
export { Deployments } from '../../../../aws-cdk/lib/api/deployments';
2+
3+
// APIs
4+
export { formatSdkLoggerContent, SdkProvider } from '../../../../aws-cdk/lib/api/aws-auth';
5+
export { Context, PROJECT_CONTEXT } from '../../../../aws-cdk/lib/api/context';
6+
export { Deployments, type SuccessfulDeployStackResult } from '../../../../aws-cdk/lib/api/deployments';
7+
export { Settings } from '../../../../aws-cdk/lib/api/settings';
8+
export { tagsForStack } from '../../../../aws-cdk/lib/api/tags';
9+
export { DEFAULT_TOOLKIT_STACK_NAME } from '../../../../aws-cdk/lib/api/toolkit-info';
10+
11+
// Context Providers
12+
export * as contextproviders from '../../../../aws-cdk/lib/context-providers';
13+
14+
// @todo APIs not clean import
915
export { HotswapMode } from '../../../../aws-cdk/lib/api/hotswap/common';
1016
export { StackActivityProgress } from '../../../../aws-cdk/lib/api/util/cloudformation/stack-activity-monitor';
11-
export { RWLock } from '../../../../aws-cdk/lib/api/util/rwlock';
12-
export type { ILock } from '../../../../aws-cdk/lib/api/util/rwlock';
17+
export { RWLock, type ILock } from '../../../../aws-cdk/lib/api/util/rwlock';
1318
export { formatTime } from '../../../../aws-cdk/lib/api/util/string-manipulation';
14-
export * as contextproviders from '../../../../aws-cdk/lib/context-providers';
19+
20+
// @todo Not yet API probably should be
21+
export { formatErrorMessage } from '../../../../aws-cdk/lib/util/error';
1522
export { ResourceMigrator } from '../../../../aws-cdk/lib/migrator';
1623
export { obscureTemplate, serializeStructure } from '../../../../aws-cdk/lib/serialize';
17-
export { Context, Settings, PROJECT_CONTEXT } from '../../../../aws-cdk/lib/settings';
18-
export { tagsForStack } from '../../../../aws-cdk/lib/tags';
19-
export { CliIoHost } from '../../../../aws-cdk/lib/toolkit/cli-io-host';
2024
export { loadTree, some } from '../../../../aws-cdk/lib/tree';
2125
export { splitBySize } from '../../../../aws-cdk/lib/util';
2226
export { validateSnsTopicArn } from '../../../../aws-cdk/lib/util/validate-notification-arn';
2327
export { WorkGraph } from '../../../../aws-cdk/lib/util/work-graph';
2428
export type { Concurrency } from '../../../../aws-cdk/lib/util/work-graph';
2529
export { WorkGraphBuilder } from '../../../../aws-cdk/lib/util/work-graph-builder';
2630
export type { AssetBuildNode, AssetPublishNode, StackNode } from '../../../../aws-cdk/lib/util/work-graph-types';
27-
export { versionNumber } from '../../../../aws-cdk/lib/version';
31+
32+
// @todo Cloud Assembly and Executable - this is a messy API right now
33+
export { CloudAssembly, sanitizePatterns, StackCollection, ExtendedStackSelection } from '../../../../aws-cdk/lib/api/cxapp/cloud-assembly';
34+
export { prepareDefaultEnvironment, prepareContext, spaceAvailableForContext } from '../../../../aws-cdk/lib/api/cxapp/exec';
2835
export { guessExecutable } from '../../../../aws-cdk/lib/api/cxapp/exec';
36+
37+
// @todo Should not use! investigate how to replace
38+
export { versionNumber } from '../../../../aws-cdk/lib/cli/version';
39+
export { CliIoHost } from '../../../../aws-cdk/lib/toolkit/cli-io-host';
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './sdk';
22
export * from './sdk-provider';
3+
export * from './sdk-logger';

packages/aws-cdk/lib/api/bootstrap/bootstrap-props.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { BootstrapSource } from './bootstrap-environment';
2-
import { Tag } from '../../tags';
2+
import { Tag } from '../tags';
33
import { StringWithoutPlaceholders } from '../util/placeholders';
44

55
export const BUCKET_NAME_OUTPUT = 'BucketName';

packages/aws-cdk/lib/api/context.ts

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { Settings } from './settings';
2+
import { ToolkitError } from '../toolkit/error';
3+
4+
export { TRANSIENT_CONTEXT_KEY } from './settings';
5+
export const PROJECT_CONTEXT = 'cdk.context.json';
6+
7+
interface ContextBag {
8+
/**
9+
* The file name of the context. Will be used to potentially
10+
* save new context back to the original file.
11+
*/
12+
fileName?: string;
13+
14+
/**
15+
* The context values.
16+
*/
17+
bag: Settings;
18+
}
19+
20+
/**
21+
* Class that supports overlaying property bags
22+
*
23+
* Reads come from the first property bag that can has the given key,
24+
* writes go to the first property bag that is not readonly. A write
25+
* will remove the value from all property bags after the first
26+
* writable one.
27+
*/
28+
export class Context {
29+
private readonly bags: Settings[];
30+
private readonly fileNames: (string | undefined)[];
31+
32+
constructor(...bags: ContextBag[]) {
33+
this.bags = bags.length > 0 ? bags.map((b) => b.bag) : [new Settings()];
34+
this.fileNames =
35+
bags.length > 0 ? bags.map((b) => b.fileName) : ['default'];
36+
}
37+
38+
public get keys(): string[] {
39+
return Object.keys(this.all);
40+
}
41+
42+
public has(key: string) {
43+
return this.keys.indexOf(key) > -1;
44+
}
45+
46+
public get all(): { [key: string]: any } {
47+
let ret = new Settings();
48+
49+
// In reverse order so keys to the left overwrite keys to the right of them
50+
for (const bag of [...this.bags].reverse()) {
51+
ret = ret.merge(bag);
52+
}
53+
54+
return ret.all;
55+
}
56+
57+
public get(key: string): any {
58+
for (const bag of this.bags) {
59+
const v = bag.get([key]);
60+
if (v !== undefined) {
61+
return v;
62+
}
63+
}
64+
return undefined;
65+
}
66+
67+
public set(key: string, value: any) {
68+
for (const bag of this.bags) {
69+
if (bag.readOnly) {
70+
continue;
71+
}
72+
73+
// All bags past the first one have the value erased
74+
bag.set([key], value);
75+
value = undefined;
76+
}
77+
}
78+
79+
public unset(key: string) {
80+
this.set(key, undefined);
81+
}
82+
83+
public clear() {
84+
for (const key of this.keys) {
85+
this.unset(key);
86+
}
87+
}
88+
89+
/**
90+
* Save a specific context file
91+
*/
92+
public async save(fileName: string): Promise<this> {
93+
const index = this.fileNames.indexOf(fileName);
94+
95+
// File not found, don't do anything in this scenario
96+
if (index === -1) {
97+
return this;
98+
}
99+
100+
const bag = this.bags[index];
101+
if (bag.readOnly) {
102+
throw new ToolkitError(`Context file ${fileName} is read only!`);
103+
}
104+
105+
await bag.save(fileName);
106+
return this;
107+
}
108+
}

packages/aws-cdk/lib/api/cxapp/cloud-executable.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import * as cxapi from '@aws-cdk/cx-api';
22
import { CloudAssembly } from './cloud-assembly';
3+
import { Configuration } from '../../cli/user-configuration';
34
import * as contextproviders from '../../context-providers';
45
import { debug } from '../../logging';
5-
import { Configuration } from '../../settings';
66
import { ToolkitError } from '../../toolkit/error';
77
import { SdkProvider } from '../aws-auth';
88

packages/aws-cdk/lib/api/cxapp/exec.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@ import * as cxschema from '@aws-cdk/cloud-assembly-schema';
55
import * as cxapi from '@aws-cdk/cx-api';
66
import * as fs from 'fs-extra';
77
import * as semver from 'semver';
8+
import { Configuration, PROJECT_CONFIG, USER_DEFAULTS } from '../../cli/user-configuration';
9+
import { versionNumber } from '../../cli/version';
810
import { debug, warning } from '../../logging';
9-
import { Configuration, PROJECT_CONFIG, Settings, USER_DEFAULTS } from '../../settings';
1011
import { ToolkitError } from '../../toolkit/error';
1112
import { loadTree, some } from '../../tree';
1213
import { splitBySize } from '../../util/objects';
13-
import { versionNumber } from '../../version';
1414
import { SdkProvider } from '../aws-auth';
15+
import { Settings } from '../settings';
1516
import { RWLock, ILock } from '../util/rwlock';
1617

1718
export interface ExecProgramResult {

packages/aws-cdk/lib/api/deployments/deployments.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,13 @@ import {
2929
type RootTemplateWithNestedStacks,
3030
} from './nested-stack-helpers';
3131
import { debug, warning } from '../../logging';
32-
import type { Tag } from '../../tags';
3332
import { ToolkitError } from '../../toolkit/error';
3433
import { formatErrorMessage } from '../../util/error';
3534
import type { SdkProvider } from '../aws-auth/sdk-provider';
3635
import { EnvironmentAccess } from '../environment-access';
3736
import { type EnvironmentResources } from '../environment-resources';
3837
import { HotswapMode, HotswapPropertyOverrides } from '../hotswap/common';
38+
import type { Tag } from '../tags';
3939
import { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';
4040
import { StackActivityMonitor, StackActivityProgress } from '../util/cloudformation/stack-activity-monitor';
4141
import { StackEventPoller } from '../util/cloudformation/stack-event-poller';

packages/aws-cdk/lib/api/settings.ts

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
import * as os from 'os';
2+
import * as fs_path from 'path';
3+
import * as fs from 'fs-extra';
4+
import { warning } from '../logging';
5+
import { ToolkitError } from '../toolkit/error';
6+
import * as util from '../util/objects';
7+
8+
export type SettingsMap = { [key: string]: any };
9+
10+
/**
11+
* If a context value is an object with this key set to a truthy value, it won't be saved to cdk.context.json
12+
*/
13+
export const TRANSIENT_CONTEXT_KEY = '$dontSaveContext';
14+
15+
/**
16+
* A single bag of settings
17+
*/
18+
export class Settings {
19+
public static mergeAll(...settings: Settings[]): Settings {
20+
let ret = new Settings();
21+
for (const setting of settings) {
22+
ret = ret.merge(setting);
23+
}
24+
return ret;
25+
}
26+
27+
constructor(
28+
private settings: SettingsMap = {},
29+
public readonly readOnly = false,
30+
) {}
31+
32+
public async load(fileName: string): Promise<this> {
33+
if (this.readOnly) {
34+
throw new ToolkitError(
35+
`Can't load ${fileName}: settings object is readonly`,
36+
);
37+
}
38+
this.settings = {};
39+
40+
const expanded = expandHomeDir(fileName);
41+
if (await fs.pathExists(expanded)) {
42+
this.settings = await fs.readJson(expanded);
43+
}
44+
45+
// See https://github.com/aws/aws-cdk/issues/59
46+
this.prohibitContextKey('default-account', fileName);
47+
this.prohibitContextKey('default-region', fileName);
48+
this.warnAboutContextKey('aws:', fileName);
49+
50+
return this;
51+
}
52+
53+
public async save(fileName: string): Promise<this> {
54+
const expanded = expandHomeDir(fileName);
55+
await fs.writeJson(expanded, stripTransientValues(this.settings), {
56+
spaces: 2,
57+
});
58+
return this;
59+
}
60+
61+
public get all(): any {
62+
return this.get([]);
63+
}
64+
65+
public merge(other: Settings): Settings {
66+
return new Settings(util.deepMerge(this.settings, other.settings));
67+
}
68+
69+
public subSettings(keyPrefix: string[]) {
70+
return new Settings(this.get(keyPrefix) || {}, false);
71+
}
72+
73+
public makeReadOnly(): Settings {
74+
return new Settings(this.settings, true);
75+
}
76+
77+
public clear() {
78+
if (this.readOnly) {
79+
throw new ToolkitError('Cannot clear(): settings are readonly');
80+
}
81+
this.settings = {};
82+
}
83+
84+
public get empty(): boolean {
85+
return Object.keys(this.settings).length === 0;
86+
}
87+
88+
public get(path: string[]): any {
89+
return util.deepClone(util.deepGet(this.settings, path));
90+
}
91+
92+
public set(path: string[], value: any): Settings {
93+
if (this.readOnly) {
94+
throw new ToolkitError(`Can't set ${path}: settings object is readonly`);
95+
}
96+
if (path.length === 0) {
97+
// deepSet can't handle this case
98+
this.settings = value;
99+
} else {
100+
util.deepSet(this.settings, path, value);
101+
}
102+
return this;
103+
}
104+
105+
public unset(path: string[]) {
106+
this.set(path, undefined);
107+
}
108+
109+
private prohibitContextKey(key: string, fileName: string) {
110+
if (!this.settings.context) {
111+
return;
112+
}
113+
if (key in this.settings.context) {
114+
// eslint-disable-next-line max-len
115+
throw new ToolkitError(
116+
`The 'context.${key}' key was found in ${fs_path.resolve(
117+
fileName,
118+
)}, but it is no longer supported. Please remove it.`,
119+
);
120+
}
121+
}
122+
123+
private warnAboutContextKey(prefix: string, fileName: string) {
124+
if (!this.settings.context) {
125+
return;
126+
}
127+
for (const contextKey of Object.keys(this.settings.context)) {
128+
if (contextKey.startsWith(prefix)) {
129+
// eslint-disable-next-line max-len
130+
warning(
131+
`A reserved context key ('context.${prefix}') key was found in ${fs_path.resolve(
132+
fileName,
133+
)}, it might cause surprising behavior and should be removed.`,
134+
);
135+
}
136+
}
137+
}
138+
}
139+
140+
function expandHomeDir(x: string) {
141+
if (x.startsWith('~')) {
142+
return fs_path.join(os.homedir(), x.slice(1));
143+
}
144+
return x;
145+
}
146+
147+
/**
148+
* Return all context value that are not transient context values
149+
*/
150+
function stripTransientValues(obj: { [key: string]: any }) {
151+
const ret: any = {};
152+
for (const [key, value] of Object.entries(obj)) {
153+
if (!isTransientValue(value)) {
154+
ret[key] = value;
155+
}
156+
}
157+
return ret;
158+
}
159+
160+
/**
161+
* Return whether the given value is a transient context value
162+
*
163+
* Values that are objects with a magic key set to a truthy value are considered transient.
164+
*/
165+
function isTransientValue(value: any) {
166+
return (
167+
typeof value === 'object' &&
168+
value !== null &&
169+
(value as any)[TRANSIENT_CONTEXT_KEY]
170+
);
171+
}

packages/aws-cdk/lib/tags.ts renamed to packages/aws-cdk/lib/api/tags.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import * as cxapi from '@aws-cdk/cx-api';
1+
import type * as cxapi from '@aws-cdk/cx-api';
22

33
/**
44
* @returns an array with the tags available in the stack metadata.

0 commit comments

Comments
 (0)