Skip to content

Commit f925551

Browse files
rix0rrrgithub-actions
and
github-actions
authored
feat(cli): control library init version with a command-line parameter (#149)
Allows controlling of the `cdk init` version of `aws-cdk-lib`: ``` cdk init --lib-version=1.2.3 ``` Mainly intended to be used by tests (to smoke-test that upcoming library versions still `init` properly), but it can be used by users as well. --- By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license --------- Signed-off-by: github-actions <[email protected]> Co-authored-by: github-actions <[email protected]>
1 parent 5b3afbe commit f925551

File tree

7 files changed

+48
-5
lines changed

7 files changed

+48
-5
lines changed

packages/aws-cdk/lib/cli/cli-config.ts

+1
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ export async function makeConfig(): Promise<CliConfig> {
345345
'language': { type: 'string', alias: 'l', desc: 'The language to be used for the new project (default can be configured in ~/.cdk.json)', choices: await availableInitLanguages() },
346346
'list': { type: 'boolean', desc: 'List the available templates' },
347347
'generate-only': { type: 'boolean', default: false, desc: 'If true, only generates project files, without executing additional operations such as setting up a git repo, installing dependencies or compiling the project' },
348+
'lib-version': { type: 'string', alias: 'V', default: undefined, desc: 'The version of the CDK library (aws-cdk-lib) to initialize the project with. Defaults to the version that was current when this CLI was built.' },
348349
},
349350
},
350351
migrate: {

packages/aws-cdk/lib/cli/cli.ts

+1
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@ export async function exec(args: string[], synthesizer?: Synthesizer): Promise<n
480480
language,
481481
canUseNetwork: undefined,
482482
generateOnly: args.generateOnly,
483+
libVersion: args.libVersion,
483484
});
484485
}
485486
case 'migrate':

packages/aws-cdk/lib/cli/convert-to-user-input.ts

+2
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ export function convertYargsToUserInput(args: any): UserInput {
213213
language: args.language,
214214
list: args.list,
215215
generateOnly: args.generateOnly,
216+
libVersion: args.libVersion,
216217
TEMPLATE: args.TEMPLATE,
217218
};
218219
break;
@@ -408,6 +409,7 @@ export function convertConfigToUserInput(config: any): UserInput {
408409
language: config.init?.language,
409410
list: config.init?.list,
410411
generateOnly: config.init?.generateOnly,
412+
libVersion: config.init?.libVersion,
411413
};
412414
const migrateOptions = {
413415
stackName: config.migrate?.stackName,

packages/aws-cdk/lib/cli/parse-command-line-arguments.ts

+6
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,12 @@ export function parseCommandLineArguments(args: Array<string>): any {
744744
default: false,
745745
type: 'boolean',
746746
desc: 'If true, only generates project files, without executing additional operations such as setting up a git repo, installing dependencies or compiling the project',
747+
})
748+
.option('lib-version', {
749+
default: undefined,
750+
type: 'string',
751+
alias: 'V',
752+
desc: 'The version of the CDK library (aws-cdk-lib) to initialize the project with. Defaults to the version that was current when this CLI was built.',
747753
}),
748754
)
749755
.command('migrate', 'Migrate existing AWS resources into a CDK app', (yargs: Argv) =>

packages/aws-cdk/lib/cli/user-input.ts

+9
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,15 @@ export interface InitOptions {
11821182
*/
11831183
readonly generateOnly?: boolean;
11841184

1185+
/**
1186+
* The version of the CDK library (aws-cdk-lib) to initialize the project with. Defaults to the version that was current when this CLI was built.
1187+
*
1188+
* aliases: V
1189+
*
1190+
* @default - undefined
1191+
*/
1192+
readonly libVersion?: string;
1193+
11851194
/**
11861195
* Positional argument for init
11871196
*/

packages/aws-cdk/lib/init.ts

+16-5
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ export interface CliInitOptions {
2424
readonly workDir?: string;
2525
readonly stackName?: string;
2626
readonly migrate?: boolean;
27+
28+
/**
29+
* Override the built-in CDK version
30+
*/
31+
readonly libVersion?: string;
2732
}
2833

2934
/**
@@ -64,6 +69,7 @@ export async function cliInit(options: CliInitOptions) {
6469
workDir,
6570
options.stackName,
6671
options.migrate,
72+
options.libVersion,
6773
);
6874
}
6975

@@ -116,7 +122,7 @@ export class InitTemplate {
116122
* @param language the language to instantiate this template with
117123
* @param targetDirectory the directory where the template is to be instantiated into
118124
*/
119-
public async install(language: string, targetDirectory: string, stackName?: string) {
125+
public async install(language: string, targetDirectory: string, stackName?: string, libVersion?: string) {
120126
if (this.languages.indexOf(language) === -1) {
121127
error(
122128
`The ${chalk.blue(language)} language is not supported for ${chalk.green(this.name)} ` +
@@ -131,6 +137,10 @@ export class InitTemplate {
131137
versions: await loadInitVersions(),
132138
};
133139

140+
if (libVersion) {
141+
projectInfo.versions['aws-cdk-lib'] = libVersion;
142+
}
143+
134144
const sourceDirectory = path.join(this.basePath, language);
135145

136146
await this.installFiles(sourceDirectory, targetDirectory, language, projectInfo);
@@ -323,10 +333,11 @@ async function initializeProject(
323333
workDir: string,
324334
stackName?: string,
325335
migrate?: boolean,
336+
cdkVersion?: string,
326337
) {
327338
await assertIsEmptyDirectory(workDir);
328339
info(`Applying project template ${chalk.green(template.name)} for ${chalk.blue(language)}`);
329-
await template.install(language, workDir, stackName);
340+
await template.install(language, workDir, stackName, cdkVersion);
330341
if (migrate) {
331342
await template.addMigrateContext(workDir);
332343
}
@@ -490,8 +501,8 @@ interface Versions {
490501
* This has been built into the CLI at build time.
491502
*/
492503
async function loadInitVersions(): Promise<Versions> {
493-
const recommendedFlagsFile = path.join(__dirname, './init-templates/.init-version.json');
494-
const contents = JSON.parse(await fs.readFile(recommendedFlagsFile, { encoding: 'utf-8' }));
504+
const initVersionFile = path.join(__dirname, './init-templates/.init-version.json');
505+
const contents = JSON.parse(await fs.readFile(initVersionFile, { encoding: 'utf-8' }));
495506

496507
const ret = {
497508
'aws-cdk-lib': contents['aws-cdk-lib'],
@@ -501,7 +512,7 @@ async function loadInitVersions(): Promise<Versions> {
501512
for (const [key, value] of Object.entries(ret)) {
502513
/* istanbul ignore next */
503514
if (!value) {
504-
throw new ToolkitError(`Missing init version from ${recommendedFlagsFile}: ${key}`);
515+
throw new ToolkitError(`Missing init version from ${initVersionFile}: ${key}`);
505516
}
506517
}
507518

packages/aws-cdk/test/init.test.ts

+13
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,19 @@ describe('constructs version', () => {
1717
expect(await fs.pathExists(path.join(workDir, 'lib'))).toBeTruthy();
1818
});
1919

20+
cliTest('can override requested version with environment variable', async (workDir) => {
21+
await cliInit({
22+
type: 'lib',
23+
language: 'typescript',
24+
workDir,
25+
libVersion: '2.100',
26+
});
27+
28+
// Check that package.json and lib/ got created in the current directory
29+
const pj = JSON.parse(await fs.readFile(path.join(workDir, 'package.json'), 'utf-8'));
30+
expect(Object.entries(pj.devDependencies)).toContainEqual(['aws-cdk-lib', '2.100']);
31+
});
32+
2033
cliTest('asking for a nonexistent template fails', async (workDir) => {
2134
await expect(cliInit({
2235
type: 'banana',

0 commit comments

Comments
 (0)