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

adds check command #2452

Open
wants to merge 3 commits 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
6 changes: 6 additions & 0 deletions .changeset/fair-cobras-carry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@aws-amplify/backend-deployer': minor
'@aws-amplify/backend-cli': minor
---

adds check command
1 change: 1 addition & 0 deletions packages/backend-deployer/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export type DeployProps = {
secretLastUpdated?: Date;
validateAppSources?: boolean;
profile?: string;
dryRun?: boolean;
};

// @public (undocumented)
Expand Down
64 changes: 64 additions & 0 deletions packages/backend-deployer/src/cdk_deployer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,70 @@ void describe('invokeCDKCommand', () => {
]);
});

void it('stops after synthesis when dryRun is true', async () => {
executeCommandMock.mock.mockImplementation(() => Promise.resolve());

// Perform dry run deployment
const result = await invoker.deploy(sandboxBackendId, {
dryRun: true,
validateAppSources: true,
...sandboxDeployProps,
});

assert.strictEqual(executeCommandMock.mock.callCount(), 3);

// Call 0 -> synth
assert.deepStrictEqual(executeCommandMock.mock.calls[0].arguments[0], [
'cdk',
'synth',
'--ci',
'--app',
"'npx tsx amplify/backend.ts'",
'--all',
'--output',
'.amplify/artifacts/cdk.out',
'--context',
'amplify-backend-namespace=foo',
'--context',
'amplify-backend-name=bar',
'--context',
'amplify-backend-type=sandbox',
'--hotswap-fallback',
'--method=direct',
'--context',
`secretLastUpdated=${
sandboxDeployProps.secretLastUpdated?.getTime() as number
}`,
'--quiet',
]);

// Call 1 -> tsc showConfig
assert.deepStrictEqual(executeCommandMock.mock.calls[1].arguments[0], [
'tsc',
'--showConfig',
'--project',
'amplify',
]);

// Call 2 -> tsc
assert.deepStrictEqual(executeCommandMock.mock.calls[2].arguments[0], [
'tsc',
'--noEmit',
'--skipLibCheck',
'--project',
'amplify',
]);

// return structure contains only synthesis metrics and should be same
assert.ok(result.deploymentTimes);
assert.ok(typeof result.deploymentTimes.synthesisTime === 'number');
assert.strictEqual(
result.deploymentTimes.totalTime,
result.deploymentTimes.synthesisTime,
'Total time should equal synthesis time for dry runs'
);
});

void it('returns human readable errors', async () => {
mock.method(invoker, 'executeCommand', () => {
throw new Error('Access Denied');
Expand Down
10 changes: 10 additions & 0 deletions packages/backend-deployer/src/cdk_deployer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ export class CDKDeployer implements BackendDeployer {
throw synthError;
}

// If this is a dry run, don't proceed with deployment
if (deployProps?.dryRun) {
return {
deploymentTimes: {
synthesisTime: synthTimeSeconds,
totalTime: synthTimeSeconds,
},
};
}

// then deploy with the cloud assembly that was generated during synth
const deployResult = await this.tryInvokeCdk(
InvokableCommand.DEPLOY,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type DeployProps = {
secretLastUpdated?: Date;
validateAppSources?: boolean;
profile?: string;
dryRun?: boolean;
};

export type DestroyProps = {
Expand Down
72 changes: 72 additions & 0 deletions packages/cli/src/commands/check/check_command.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { BackendDeployer } from '@aws-amplify/backend-deployer';
import { format, printer } from '@aws-amplify/cli-core';
import assert from 'node:assert';
import { beforeEach, describe, it, mock } from 'node:test';
import { CheckCommand } from './check_command.js';

void describe('check command', () => {
const deployMock = mock.fn<typeof backendDeployerMock.deploy>();
const backendDeployerMock = {
deploy: deployMock,
} as unknown as BackendDeployer;

const printerMock = {
print: mock.fn(),
indicateProgress: mock.fn(
async (message: string, action: () => Promise<void>) => {
await action();
}
),
};

mock.method(printer, 'print', printerMock.print);
mock.method(printer, 'indicateProgress', printerMock.indicateProgress);

beforeEach(() => {
deployMock.mock.resetCalls();
printerMock.print.mock.resetCalls();
printerMock.indicateProgress.mock.resetCalls();
});

void it('runs type checking and CDK synthesis without deployment', async () => {
const command = new CheckCommand(backendDeployerMock);
const synthesisTime = 1.23;

deployMock.mock.mockImplementation(async () => ({
deploymentTimes: {
synthesisTime,
},
}));

await command.handler();

// Verify deploy was called with correct arguments
assert.strictEqual(deployMock.mock.callCount(), 1);
assert.deepStrictEqual(deployMock.mock.calls[0].arguments[0], {
namespace: 'sandbox',
name: 'dev',
type: 'sandbox',
});
assert.deepStrictEqual(deployMock.mock.calls[0].arguments[1], {
validateAppSources: true,
dryRun: true,
});

// Verify progress indicator was shown
assert.strictEqual(printerMock.indicateProgress.mock.callCount(), 1);
assert.strictEqual(
printerMock.indicateProgress.mock.calls[0].arguments[0],
'Running type checks and CDK synthesis...'
);

// Verify success message was printed
assert.strictEqual(printerMock.print.mock.callCount(), 1);
assert.strictEqual(
printerMock.print.mock.calls[0].arguments[0],
format.success(
`✔ Type checking and CDK synthesis completed successfully ` +
format.highlight(`(${synthesisTime}s)`)
)
);
});
});
48 changes: 48 additions & 0 deletions packages/cli/src/commands/check/check_command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { BackendDeployer } from '@aws-amplify/backend-deployer';
import { format, printer } from '@aws-amplify/cli-core';
import { BackendIdentifier } from '@aws-amplify/plugin-types';
import { Argv, CommandModule } from 'yargs';

/**
* Command that runs type checking and CDK synthesis without deployment
*/
export class CheckCommand implements CommandModule {
command = 'check';
Copy link
Contributor

Choose a reason for hiding this comment

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

Not a big fan of the command name check. It's more closely related to build and perhaps --dryRun isn't bad either for the existing sandbox command. This way customers can utilize the watch nature of sandbox for builds as well.

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree that it's more of a "build", though the check name was inspired by other projects that provide similar functionality with the intent of a sort of "preflight" task before merging changes. There is another request to provide a "diff" function and integrate cdk-nag to perform diagnostics and/or highlight best practices that I think would fit nicely with the "check" theme

https://docs.astro.build/en/reference/cli-reference/#astro-check
https://svelte.dev/docs/cli/sv-check

Copy link
Contributor

Choose a reason for hiding this comment

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

There is definitely overlap between check and build. We might be slightly different in the sense that we "synth" as well. We discussed offline to do an API review of this change will all the proposals.

Copy link

Choose a reason for hiding this comment

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

Have you considered the option of synth too?

I was looking for both diff and synth commands as a long time user of CDK alongside Amplify gen1. Given that CDK does type checking with tsc during synth too it seems functionally similar, and perhaps nice to have consistency in naming across the two services.

describe = 'Run type checking and CDK synthesis without deployment';

/**
* Creates a new instance of CheckCommand
* @param backendDeployer - The deployer used to run CDK synthesis
*/
constructor(private readonly backendDeployer: BackendDeployer) {}

handler = async () => {
const backendId: BackendIdentifier = {
namespace: 'sandbox',
name: 'dev',
type: 'sandbox',
};

let result: { deploymentTimes: { synthesisTime?: number } } = {
deploymentTimes: {},
};
await printer.indicateProgress(
'Running type checks and CDK synthesis...',
async () => {
result = await this.backendDeployer.deploy(backendId, {
validateAppSources: true,
dryRun: true,
});
}
);

printer.print(
format.success(
`✔ Type checking and CDK synthesis completed successfully ` +
format.highlight(`(${result.deploymentTimes.synthesisTime ?? 0}s)`)
)
);
};

builder = (yargs: Argv) => yargs;
}
16 changes: 16 additions & 0 deletions packages/cli/src/commands/check/check_command_factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { BackendDeployerFactory } from '@aws-amplify/backend-deployer';
import { PackageManagerControllerFactory, format } from '@aws-amplify/cli-core';
import { CheckCommand } from './check_command.js';

/**
* Creates Check command.
*/
export const createCheckCommand = (): CheckCommand => {
const packageManagerControllerFactory = new PackageManagerControllerFactory();
const backendDeployerFactory = new BackendDeployerFactory(
packageManagerControllerFactory.getPackageManagerController(),
format
);
const backendDeployer = backendDeployerFactory.getInstance();
return new CheckCommand(backendDeployer);
};
2 changes: 2 additions & 0 deletions packages/cli/src/main_parser_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createSandboxCommand } from './commands/sandbox/sandbox_command_factory
import { createPipelineDeployCommand } from './commands/pipeline-deploy/pipeline_deploy_command_factory.js';
import { createConfigureCommand } from './commands/configure/configure_command_factory.js';
import { createInfoCommand } from './commands/info/info_command_factory.js';
import { createCheckCommand } from './commands/check/check_command_factory.js';
import * as path from 'path';

/**
Expand All @@ -28,6 +29,7 @@ export const createMainParser = (libraryVersion: string): Argv => {
.command(createPipelineDeployCommand())
.command(createConfigureCommand())
.command(createInfoCommand())
.command(createCheckCommand())
.help()
.alias('h', 'help')
.alias('v', 'version')
Expand Down
Loading