Skip to content

Commit

Permalink
fix: use prompter and handle deletions (#10122)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: package name update requires version bump in order to keep in sync with lerna.
  • Loading branch information
johnpc committed Apr 4, 2022
1 parent f634754 commit 5c0e290
Show file tree
Hide file tree
Showing 13 changed files with 79 additions and 33 deletions.
1 change: 1 addition & 0 deletions .circleci/config.base.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1031,6 +1031,7 @@ commands:
steps:
- run:
name: Scan E2E artifacts
no_output_timeout: 90m
command: |
if ! yarn ts-node .circleci/scan_artifacts.ts; then
echo "Cleaning the repository"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,11 @@
" response.send(event, context, response.SUCCESS, {'message': `Successfully deleted pinpoint project`});",
" })",
" .catch(e=>{",
" response.send(event, context, response.FAILED, {'message': `Failed to deleted Pinpoint project`, 'exception': e});",
" if (e.code !== 'ParameterNotFound') {",
" response.send(event, context, response.FAILED, {'message': `Failed to deleted Pinpoint project`, 'exception': e});",
" } else {",
" response.send(event, context, response.SUCCESS, {'message': `Successfully deleted pinpoint project`});",
" }",
" }); ",
" }",
" if (event.RequestType == 'Update') {",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { $TSContext, $TSObject, exitOnNextTick, ResourceCredentialsNotFoundError, ResourceDoesNotExistError } from 'amplify-cli-core';
import { printer } from 'amplify-prompts';
import { printer, prompter } from 'amplify-prompts';
import chalk from 'chalk';
import { DataApiParams } from 'graphql-relational-schema-transformer';
import inquirer from 'inquirer';
import ora from 'ora';

const spinner = ora('');
Expand Down Expand Up @@ -237,16 +236,13 @@ async function selectDatabase(context: $TSContext, inputs, clusterArn, secretArn
* @param {*} choicesList
*/
async function promptWalkthroughQuestion(inputs, questionNumber, choicesList) {
const question = [
{
const question = {
type: inputs[questionNumber].type,
name: inputs[questionNumber].key,
message: inputs[questionNumber].question,
choices: choicesList,
},
];

const answer = await inquirer.prompt(question);
};
const answer = await prompter.pick(question.message, choicesList)
return answer[inputs[questionNumber].key];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
getGraphQLTransformerAuthDocLink,
} from 'amplify-cli-core';
import { UpdateApiRequest } from 'amplify-headless-interface';
import { printer } from 'amplify-prompts';
import { printer, prompter } from 'amplify-prompts';
import chalk from 'chalk';
import * as fs from 'fs-extra';
import { collectDirectivesByTypeNames, readProjectConfiguration } from 'graphql-transformer-core';
Expand Down Expand Up @@ -817,7 +817,7 @@ async function askUserPoolQuestions(context: $TSContext) {
export async function askApiKeyQuestions(authSettings: $TSObject = undefined) {
let defaultValues = {
apiKeyExpirationDays: 7,
description: undefined,
description: '',
};
Object.assign(defaultValues, authSettings?.apiKeyConfig);

Expand Down Expand Up @@ -845,9 +845,13 @@ export async function askApiKeyQuestions(authSettings: $TSObject = undefined) {
},
];

const apiKeyConfig = await inquirer.prompt(apiKeyQuestions);
const apiKeyConfig: $TSObject = {};
for (const apiKeyQuestion of apiKeyQuestions) {
apiKeyConfig[apiKeyQuestion.name] = await prompter.input(apiKeyQuestion.message, { initial: apiKeyQuestion.default as string })
}
const apiKeyExpirationDaysNum = Number(apiKeyConfig.apiKeyExpirationDays);
apiKeyConfig.apiKeyExpirationDate = Expiration.after(Duration.days(apiKeyExpirationDaysNum)).date;
apiKeyConfig.apiKeyExpirationDays = apiKeyExpirationDaysNum;

return {
authenticationType: 'API_KEY',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,17 @@ export class SSMClientWrapper {
};

/**
* Delets all secrets in secretNames
* Deletes all secrets in secretNames
*/
deleteSecrets = async (secretNames: string[]) => {
await this.ssmClient.deleteParameters({ Names: secretNames }).promise();
try {
await this.ssmClient.deleteParameters({ Names: secretNames }).promise();
} catch (err) {
// if the value didn't exist in the first place, consider it deleted
if (err.code !== 'ParameterNotFound') {
throw err;
}
}
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,17 @@ exports.handler = function(event, context) {
if(process.env.ENV && process.env.ENV !== "NONE") {
botName = botName + '_' + process.env.ENV;
}
lex.deleteBot({name: botName}).promise();
response.send(event, context, response.SUCCESS);
lex.deleteBot({name: botName}).promise()
.then(() => {
response.send(event, context, response.SUCCESS);
})
.catch((err) => {
if (err.code !== 'ParameterNotFound') {
response.send(event, context, response.FAILED);
} else {
response.send(event, context, response.SUCCESS);
}
});
return;
}
let newSlotTypeParams = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,12 @@ function generateLambdaAccessForRekognition(identifyCFNFile, functionName, s3Res
' console.log("delete" + res);',
' console.log("response data" + JSON.stringify(res));',
' response.send(event, context, response.SUCCESS, res);',
' }).catch(err => {',
' if (err.code !== \'ParameterNotFound\') {',
' response.send(event, context, response.FAILED);',
' } else {',
' response.send(event, context, response.SUCCESS);',
' }',
' });',
' }',
" if (event.RequestType == 'Update' || event.RequestType == 'Create') {",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,12 @@
" console.log(\"delete\" + res);",
" console.log(\"response data\" + JSON.stringify(res));",
" response.send(event, context, response.SUCCESS, res);",
" }).catch(err => {",
" if (err.code !== 'ParameterNotFound') {",
" response.send(event, context, response.FAILED);",
" } else {",
" response.send(event, context, response.SUCCESS);",
" }",
" });",
" }",
" if (event.RequestType == 'Update' || event.RequestType == 'Create') {",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { $TSAny, $TSContext, $TSObject, exitOnNextTick, JSONUtilities } from 'amplify-cli-core';
import { prompter } from 'amplify-prompts';
import chalk from 'chalk';
import * as fs from 'fs-extra';
import * as inquirer from 'inquirer';
Expand Down Expand Up @@ -499,8 +500,14 @@ export const getTriggerEnvInputs = async (context, triggerPath, triggerKey, trig
(Object.keys(currentEnvVars) && Object.keys(currentEnvVars).length === 0) ||
!currentEnvVars[questions[j].key]
) {
const answer: any = await inquirer.prompt(questions[j].question);
answers[questions[j].key] = answer[questions[j].key];
const prompterTypeMapping = {
input: 'input',
list: 'pick',
confirm: 'yesOrNo',
}
const prompterFunction = prompterTypeMapping[questions[j].question.type];
const answer: any = await prompter[prompterFunction](questions[j].question.message);
answers[questions[j].key] = answer;
}
}
}
Expand Down
19 changes: 7 additions & 12 deletions packages/amplify-e2e-core/src/categories/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,7 @@ export function addAuthWithGroupTrigger(cwd: string, settings: any): Promise<voi
.send(' ')
.sendCarriageReturn()
.wait('Enter the name of the group to which users will be added.')
.send('mygroup')
.sendCarriageReturn()
.sendLine('mygroup')
.wait('Do you want to edit your add-to-group function now?')
.sendConfirmNo()
.run((err: Error) => {
Expand Down Expand Up @@ -159,8 +158,7 @@ export function addAuthViaAPIWithTrigger(cwd: string, opts: Partial<AddApiOption
.send(' ')
.sendCarriageReturn()
.wait('Enter the name of the group to which users will be added.')
.send('mygroup')
.sendCarriageReturn()
.sendLine('mygroup')
.wait('Do you want to edit your add-to-group function now?')
.sendConfirmNo()
.wait(/.*Configure additional auth types.*/)
Expand Down Expand Up @@ -249,8 +247,7 @@ export function addAuthwithUserPoolGroupsViaAPIWithTrigger(cwd: string, opts: Pa
.wait('What functionality do you want to use for Post Confirmation')
.sendCarriageReturn()
.wait('Enter the name of the group to which users will be added.')
.send('mygroup')
.sendCarriageReturn()
.sendLine('mygroup')
.wait('Do you want to edit your add-to-group function now?')
.sendConfirmNo()
.wait(/.*Configure additional auth types.*/)
Expand Down Expand Up @@ -337,13 +334,12 @@ export function addAuthWithCustomTrigger(cwd: string, settings: any): Promise<vo
.send(' ')
.sendCarriageReturn()
.wait('Enter a comma-delimited list of disallowed email domains')
.send('amazon.com')
.sendCarriageReturn()
.sendLine('amazon.com')
.wait('Successfully')
.wait(`Do you want to edit your email-filter-denylist${settings.useInclusiveTerminology === false ? '-legacy' : ''} function now?`)
.sendLine('n')
.sendConfirmNo()
.wait('Do you want to edit your custom function now')
.sendLine('n')
.sendConfirmNo()
.run((err: Error) => {
if (!err) {
resolve();
Expand Down Expand Up @@ -496,8 +492,7 @@ export function addAuthWithRecaptchaTrigger(cwd: string, settings: any): Promise
.wait('Do you want to edit your captcha-create-challenge function now?')
.sendConfirmNo()
.wait('Enter the Google reCaptcha secret key:')
.send('dummykey')
.sendCarriageReturn()
.sendLine('dummykey')
.wait('Do you want to edit your captcha-verify function now?')
.sendConfirmNo()
.run((err: Error) => {
Expand Down
5 changes: 4 additions & 1 deletion packages/amplify-e2e-core/src/categories/hosting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,10 @@ export function amplifyPublishWithUpdate(cwd: string): Promise<void> {

export function amplifyPublishWithoutUpdate(cwd: string): Promise<void> {
return new Promise((resolve, reject) => {
spawn(getCLIPath(), ['publish'], { cwd, stripColors: true }).run((err: Error) => {
spawn(getCLIPath(), ['publish'], { cwd, stripColors: true })
.wait('Do you still want to publish the frontend')
.sendConfirmYes()
.run((err: Error) => {
if (!err) {
resolve();
} else {
Expand Down
2 changes: 1 addition & 1 deletion packages/amplify-prompts/src/prompter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class AmplifyPrompter implements Prompter {
input = async <RS extends ReturnSize = 'one', T = string>(message: string, ...options: MaybeOptionalInputOptions<RS, T>) => {
const opts = options?.[0] ?? ({} as InputOptions<RS, T>);
if (isYes) {
if (opts.initial) {
if (opts.initial !== undefined) {
return opts.initial as PromptReturn<RS, T>;
} else {
throw new Error(`Cannot prompt for [${message}] when '--yes' flag is set`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,15 @@ export class Lambda {
const deletionPromises = [];
for (const version of versions) {
params.VersionNumber = version;
deletionPromises.push(this.lambda.deleteLayerVersion(params).promise());
deletionPromises.push(async () => {
try {
await this.lambda.deleteLayerVersion(params).promise();
} catch (err) {
if (err.code !== 'ParameterNotFound') {
throw err;
}
}
});
}

try {
Expand Down

0 comments on commit 5c0e290

Please sign in to comment.