Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): control library init version with a command-line parameter #149

Merged
merged 5 commits into from
Feb 27, 2025
Merged
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
1 change: 1 addition & 0 deletions packages/aws-cdk/lib/cli/cli-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ export async function makeConfig(): Promise<CliConfig> {
'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() },
'list': { type: 'boolean', desc: 'List the available templates' },
'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' },
'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.' },
},
},
migrate: {
Expand Down
1 change: 1 addition & 0 deletions packages/aws-cdk/lib/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ export async function exec(args: string[], synthesizer?: Synthesizer): Promise<n
language,
canUseNetwork: undefined,
generateOnly: args.generateOnly,
libVersion: args.libVersion,
});
}
case 'migrate':
Expand Down
2 changes: 2 additions & 0 deletions packages/aws-cdk/lib/cli/convert-to-user-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ export function convertYargsToUserInput(args: any): UserInput {
language: args.language,
list: args.list,
generateOnly: args.generateOnly,
libVersion: args.libVersion,
TEMPLATE: args.TEMPLATE,
};
break;
Expand Down Expand Up @@ -408,6 +409,7 @@ export function convertConfigToUserInput(config: any): UserInput {
language: config.init?.language,
list: config.init?.list,
generateOnly: config.init?.generateOnly,
libVersion: config.init?.libVersion,
};
const migrateOptions = {
stackName: config.migrate?.stackName,
Expand Down
6 changes: 6 additions & 0 deletions packages/aws-cdk/lib/cli/parse-command-line-arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,12 @@ export function parseCommandLineArguments(args: Array<string>): any {
default: false,
type: 'boolean',
desc: 'If true, only generates project files, without executing additional operations such as setting up a git repo, installing dependencies or compiling the project',
})
.option('lib-version', {
default: undefined,
type: 'string',
alias: 'V',
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.',
}),
)
.command('migrate', 'Migrate existing AWS resources into a CDK app', (yargs: Argv) =>
Expand Down
9 changes: 9 additions & 0 deletions packages/aws-cdk/lib/cli/user-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1182,6 +1182,15 @@ export interface InitOptions {
*/
readonly generateOnly?: boolean;

/**
* 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.
*
* aliases: V
*
* @default - undefined
*/
readonly libVersion?: string;

/**
* Positional argument for init
*/
Expand Down
21 changes: 16 additions & 5 deletions packages/aws-cdk/lib/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ export interface CliInitOptions {
readonly workDir?: string;
readonly stackName?: string;
readonly migrate?: boolean;

/**
* Override the built-in CDK version
*/
readonly libVersion?: string;
}

/**
Expand Down Expand Up @@ -64,6 +69,7 @@ export async function cliInit(options: CliInitOptions) {
workDir,
options.stackName,
options.migrate,
options.libVersion,
);
}

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

if (libVersion) {
projectInfo.versions['aws-cdk-lib'] = libVersion;
}

const sourceDirectory = path.join(this.basePath, language);

await this.installFiles(sourceDirectory, targetDirectory, language, projectInfo);
Expand Down Expand Up @@ -323,10 +333,11 @@ async function initializeProject(
workDir: string,
stackName?: string,
migrate?: boolean,
cdkVersion?: string,
) {
await assertIsEmptyDirectory(workDir);
info(`Applying project template ${chalk.green(template.name)} for ${chalk.blue(language)}`);
await template.install(language, workDir, stackName);
await template.install(language, workDir, stackName, cdkVersion);
if (migrate) {
await template.addMigrateContext(workDir);
}
Expand Down Expand Up @@ -490,8 +501,8 @@ interface Versions {
* This has been built into the CLI at build time.
*/
async function loadInitVersions(): Promise<Versions> {
const recommendedFlagsFile = path.join(__dirname, './init-templates/.init-version.json');
const contents = JSON.parse(await fs.readFile(recommendedFlagsFile, { encoding: 'utf-8' }));
const initVersionFile = path.join(__dirname, './init-templates/.init-version.json');
const contents = JSON.parse(await fs.readFile(initVersionFile, { encoding: 'utf-8' }));

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

Expand Down
13 changes: 13 additions & 0 deletions packages/aws-cdk/test/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ describe('constructs version', () => {
expect(await fs.pathExists(path.join(workDir, 'lib'))).toBeTruthy();
});

cliTest('can override requested version with environment variable', async (workDir) => {
await cliInit({
type: 'lib',
language: 'typescript',
workDir,
libVersion: '2.100',
});

// Check that package.json and lib/ got created in the current directory
const pj = JSON.parse(await fs.readFile(path.join(workDir, 'package.json'), 'utf-8'));
expect(Object.entries(pj.devDependencies)).toContainEqual(['aws-cdk-lib', '2.100']);
});

cliTest('asking for a nonexistent template fails', async (workDir) => {
await expect(cliInit({
type: 'banana',
Expand Down