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): --project-name init option #29695

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
3 changes: 2 additions & 1 deletion packages/aws-cdk/lib/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,8 @@ async function parseCommandLineArguments(args: string[]) {
.command('init [TEMPLATE]', 'Create a new, empty CDK project from a template.', (yargs: Argv) => yargs
.option('language', { type: 'string', alias: 'l', desc: 'The language to be used for the new project (default can be configured in ~/.cdk.json)', choices: initTemplateLanguages })
.option('list', { type: 'boolean', desc: 'List the available templates' })
.option('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' }),
.option('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' })
.option('project-name', { type: 'string', desc: 'Name of the generated project (defaults to current directory name)', requiresArg: true }),
)
.command('migrate', false /* hidden from "cdk --help" */, (yargs: Argv) => yargs
.option('stack-name', { type: 'string', alias: 'n', desc: 'The name assigned to the stack created in the new project. The name of the app will be based off this name as well.', requiresArg: true })
Expand Down
48 changes: 37 additions & 11 deletions packages/aws-cdk/lib/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface CliInitOptions {
readonly language?: string;
readonly canUseNetwork?: boolean;
readonly generateOnly?: boolean;
readonly projectName?: string;
readonly workDir?: string;
readonly stackName?: string;
readonly migrate?: boolean;
Expand Down Expand Up @@ -52,7 +53,16 @@ export async function cliInit(options: CliInitOptions) {
throw new Error('No language was selected');
}

await initializeProject(template, options.language, canUseNetwork, generateOnly, workDir, options.stackName, options.migrate);
await initializeProject({
template,
language: options.language,
canUseNetwork,
generateOnly,
projectName: options.projectName,
workDir,
stackName: options.stackName,
migrate: options.migrate,
});
}

/**
Expand Down Expand Up @@ -102,16 +112,18 @@ export class InitTemplate {
*
* @param language the language to instantiate this template with
* @param targetDirectory the directory where the template is to be instantiated into
* @param stackName the output project stack name
* @param projectName the output project name
*/
public async install(language: string, targetDirectory: string, stackName?: string) {
public async install(language: string, targetDirectory: string, stackName?: string, projectName?: string) {
if (this.languages.indexOf(language) === -1) {
error(`The ${chalk.blue(language)} language is not supported for ${chalk.green(this.name)} `
+ `(it supports: ${this.languages.map(l => chalk.blue(l)).join(', ')})`);
throw new Error(`Unsupported language: ${language}`);
}

const projectInfo: ProjectInfo = {
name: decamelize(path.basename(path.resolve(targetDirectory))),
name: projectName ?? decamelize(path.basename(path.resolve(targetDirectory))),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there any validation we need to do here? for example, are spaces allowed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing is currently stopping a user from doing this:

mkdir "test folder with spaces"
cd "test folder with spaces"
npx cdk init --language=typescript

Which the CDK doesn't handle particularly well out of the box:
cdk.json

  "app": "npx ts-node --prefer-ts-exts bin/test folder with spaces.ts",
npm run cdk deploy

> test folder with spaces@0.1.0 cdk
> cdk deploy

node:internal/modules/cjs/loader:1147
  throw err;
  ^

Error: Cannot find module './test'

Manually quoting the path in "app" does seem to result in the deploy and destroy working

stackName,
};

Expand Down Expand Up @@ -280,18 +292,32 @@ export async function printAvailableTemplates(language?: string) {
}
}

interface InitializeProjectOptions {
template: InitTemplate;
language: string;
canUseNetwork: boolean;
generateOnly: boolean;
projectName?: string;
workDir: string;
stackName?: string;
migrate?: boolean;
}

async function initializeProject(
template: InitTemplate,
language: string,
canUseNetwork: boolean,
generateOnly: boolean,
workDir: string,
stackName?: string,
migrate?: boolean,
{
template,
language,
canUseNetwork,
generateOnly,
projectName,
workDir,
stackName,
migrate,
}: InitializeProjectOptions,
) {
await assertIsEmptyDirectory(workDir);
print(`Applying project template ${chalk.green(template.name)} for ${chalk.blue(language)}`);
await template.install(language, workDir, stackName);
await template.install(language, workDir, stackName, projectName);
if (migrate) {
await template.addMigrateContext(workDir);
}
Expand Down
32 changes: 32 additions & 0 deletions packages/aws-cdk/test/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,38 @@ describe('constructs version', () => {
expect(await fs.pathExists(path.join(workDir, '.git'))).toBeFalsy();
});

cliTest('--project-name should change the output directory', async (workDir) => {
const projectName = 'custom_project-name';
await cliInit({
type: 'app',
language: 'javascript',
canUseNetwork: false,
generateOnly: true,
workDir,
projectName,
});

// Check that lib/, bin/ and test/ files have been set correctly
expect(await fs.pathExists(path.join(workDir, 'bin', `${projectName}.js`))).toBeTruthy();
expect(await fs.pathExists(path.join(workDir, 'lib', `${projectName}-stack.js`))).toBeTruthy();
expect(await fs.pathExists(path.join(workDir, 'test', `${projectName}.test.js`))).toBeTruthy();

// Check that the package.json "name" and "bin" properties have been set correctly
const packageJsonFile = path.join(workDir, 'package.json');
expect(await fs.pathExists(packageJsonFile)).toBeTruthy();

const packageJson = JSON.parse(await fs.readFile(packageJsonFile, 'utf8'));
expect(packageJson.name).toEqual(projectName);
expect(packageJson.bin).toEqual({ [projectName]: `bin/${projectName}.js` });

// Check that the cdk.json "app" property has been set correctly
const cdkJsonFile = path.join(workDir, 'cdk.json');
expect(await fs.pathExists(cdkJsonFile)).toBeTruthy();

const cdkJson = JSON.parse(await fs.readFile(cdkJsonFile, 'utf8'));
expect(cdkJson.app).toEqual(`node bin/${projectName}.js`);
});

cliTest('git directory does not throw off the initer!', async (workDir) => {
fs.mkdirSync(path.join(workDir, '.git'));

Expand Down
Loading