Skip to content

Commit

Permalink
fix: test fixes (#8647)
Browse files Browse the repository at this point in the history
  • Loading branch information
ammarkarachi authored and sachscode committed Nov 11, 2021
1 parent c88744f commit af1d446
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 35 deletions.
6 changes: 6 additions & 0 deletions packages/amplify-cli-core/src/state-manager/pathManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ export const PathConstants = {
CfnFileName: (resourceName: string) => `${resourceName}-awscloudformation-template.json`,

CustomPoliciesFilename: 'custom-policies.json',

DefaultFrontEndExportFolder: './exported-amplify-front-end-config',
DefaultExportFolder: './export-amplify-stack',
ExportManifestJsonFilename: 'amplify-export-manifest.json',
ExportTagsJsonFileName: 'export-tags.json',
ExportCategoryStackMappingJsonFilename: 'category-stack-mapping.json',
};

export class PathManager {
Expand Down
23 changes: 12 additions & 11 deletions packages/amplify-cli-core/src/utils/validate-path.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import * as fs from 'fs-extra';
import { ExportPathValidationError } from '../errors';

import * as path from 'path';
/**
* Validates whether the path is a directory
* @throws {ExportPathValidationError} if path not valid
* @param directoryPath to validate
*/
export function validateExportDirectoryPath(directoryPath: any) {
if (typeof directoryPath !== 'string') {
throw new ExportPathValidationError(`${directoryPath} is not a valid path specified by --out`);
}
export function validateExportDirectoryPath(directoryPath: any, defaultPath: string): string {
const exportPath = directoryPath || defaultPath;
const resolvedDir = path.resolve(exportPath);

if (!fs.existsSync(directoryPath)) {
throw new ExportPathValidationError(`${directoryPath} does not exist`);
if (!fs.existsSync(resolvedDir)) {
fs.ensureDirSync(resolvedDir);
} else {
const stat = fs.lstatSync(exportPath);
if (!stat.isDirectory()) {
throw new ExportPathValidationError(`${exportPath} is not a valid directory`);
}
}

const stat = fs.lstatSync(directoryPath);
if (!stat.isDirectory()) {
throw new ExportPathValidationError(`${directoryPath} is not a valid directory`);
}
return resolvedDir;
}
36 changes: 26 additions & 10 deletions packages/amplify-cli/src/commands/export.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
import { $TSContext, IAmplifyResource, stateManager, UnrecognizedFrontendError, validateExportDirectoryPath } from 'amplify-cli-core';
import {
$TSContext,
IAmplifyResource,
stateManager,
UnrecognizedFrontendError,
validateExportDirectoryPath,
PathConstants,
} from 'amplify-cli-core';
import { printer } from 'amplify-prompts';
import chalk from 'chalk';
import { getResourceOutputs } from '../extensions/amplify-helpers/get-resource-outputs';
import Ora from 'ora';
import { getResources } from './build-override';
import * as _ from 'lodash';

export const run = async (context: $TSContext) => {
const options = context.input.options;
const subCommands = context.input.subCommands;
const showHelp = !options || options.help || !options.out;
const showHelp = getSafeInputOptionsFlag(context, 'help') || false;
const isPull = !!(subCommands && subCommands.includes('pull'));
const showPullHelp = (showHelp || !options.frontend || !options.rootStackName) && isPull;
const frontend = getSafeInputOptionsFlag(context, 'frontend');
const rootStackName = getSafeInputOptionsFlag(context, 'rootStackName');
const showPullHelp = (showHelp || frontend || rootStackName) && isPull;

if (showHelp && !showPullHelp) {
printer.blankLine();
printer.info("'amplify export', Allows you to integrate your backend into an external deployment tool");
printer.info("'amplify export', exports your Amplify backend into CDK app");
printer.blankLine();
printer.info(`${chalk.yellow('--cdk')} Export all resources with cdk comatibility`);
printer.info(`${chalk.yellow('--out')} Root directory of cdk project`);
printer.info(`${chalk.yellow('--cdk')} Exports all Amplify-generated resources as CDK`);
printer.info(`${chalk.yellow('--out')} Folder to export stack to`);
printer.blankLine();
printer.info(`Example: ${chalk.green('amplify export --cdk --out ~/myCDKApp')}`);
printer.blankLine();
Expand Down Expand Up @@ -46,7 +55,7 @@ export const run = async (context: $TSContext) => {
printer.blankLine();
return;
}
const exportPath = context.input.options['out'];
const exportPath = _.get(context, ['input', 'options', 'out']);
if (isPull) {
await createFrontEndConfigFile(context, exportPath);
} else {
Expand Down Expand Up @@ -93,8 +102,13 @@ async function createFrontEndConfigFile(context: $TSContext, exportPath: string)
const cloudMeta = stateManager.getCurrentMeta();
const frontendPlugins = context.amplify.getFrontendPlugins(context);
const frontendHandlerModule = require(frontendPlugins[frontend]);
validateExportDirectoryPath(exportPath);
await frontendHandlerModule.createFrontendConfigsAtPath(context, getResourceOutputs(meta), getResourceOutputs(cloudMeta), exportPath);
const validatedExportPath = validateExportDirectoryPath(exportPath, PathConstants.DefaultFrontEndExportFolder);
await frontendHandlerModule.createFrontendConfigsAtPath(
context,
getResourceOutputs(meta),
getResourceOutputs(cloudMeta),
validatedExportPath,
);
spinner.succeed('Successfully generated frontend config files');
} catch (ex: any) {
spinner.fail('Failed to generate frontend config files ' + ex.message);
Expand All @@ -103,3 +117,5 @@ async function createFrontEndConfigFile(context: $TSContext, exportPath: string)
spinner.stop();
}
}

const getSafeInputOptionsFlag = (context: $TSContext, flag: string) => _.get(context, ['input', 'options', flag]);
26 changes: 12 additions & 14 deletions packages/amplify-provider-awscloudformation/src/export-resources.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { $TSAny, $TSContext, JSONUtilities, stateManager } from 'amplify-cli-core';
import { $TSAny, $TSContext, JSONUtilities, PathConstants, stateManager } from 'amplify-cli-core';
import { ResourceExport } from './resource-package/resource-export';
import { ResourceDefinition, StackIncludeDetails, StackParameters } from './resource-package/types';
import * as path from 'path';
Expand All @@ -9,21 +9,17 @@ const backup = 'backup';
import _ from 'lodash';
import rimraf from 'rimraf';
import { validateExportDirectoryPath } from 'amplify-cli-core';
// don't change file names ever ever
const AMPLIFY_EXPORT_MANIFEST_JSON_FILE = 'amplify-export-manifest.json';
const AMPLIFY_EXPORT_TAGS_JSON_FILE = 'export-tags.json';
const AMPLIFY_EXPORT_CATEGORY_STACK_MAPPING_FILE = 'category-stack-mapping.json';
/**
* Walks through
* @param context
* @param resourceDefinition
* @param exportPath is the path to export to
*/
export async function run(context: $TSContext, resourceDefinition: $TSAny[], exportPath: string) {
validateExportDirectoryPath(exportPath);
const resolvedExportDir = validateExportDirectoryPath(exportPath, PathConstants.DefaultExportFolder);

const { projectName } = stateManager.getProjectConfig();
const amplifyExportFolder = path.join(path.resolve(exportPath), `amplify-export-${projectName}`);
const amplifyExportFolder = path.join(resolvedExportDir, `amplify-export-${projectName}`);
const proceed = await checkForExistingExport(amplifyExportFolder);

if (proceed) {
Expand Down Expand Up @@ -54,7 +50,7 @@ export async function run(context: $TSContext, resourceDefinition: $TSAny[], exp
const parameters = resourceExport.fixNestedStackParameters(transformedResources, extractedParameters);

spinner.text = `Generating export manifest`;
writeExportManifest(parameters, exportPath, amplifyExportFolder);
writeExportManifest(parameters, resolvedExportDir, amplifyExportFolder);

spinner.text = `Generating category stack mappings`;
createCategoryStackMapping(transformedResources, amplifyExportFolder);
Expand All @@ -64,12 +60,14 @@ export async function run(context: $TSContext, resourceDefinition: $TSAny[], exp

spinner.text = 'Setting permissions';
await setPermissions(amplifyExportFolder);
spinner.succeed('Done Exporting');
spinner.succeed();
printer.blankLine();
printer.success('Successfully exported');
printer.info('Some Next steps:');
printer.info('Next steps:');
printer.info('You can now integrate your Amplify Backend into your CDK App');
printer.info('By installing the Amplify Backend Export Construct by running npm i @aws-amplify/amplify-export-backend in your CDK app');
printer.info(
'Install the "Amplify Exported Backend" CDK Construct by running "npm i @aws-amplify/amplify-exported-backend" in your CDK app',
);
printer.info('For more information: docs.amplify.aws/cli/export');
printer.blankLine();
} catch (ex) {
Expand Down Expand Up @@ -98,7 +96,7 @@ function createTagsFile(exportPath: string) {
const hydratedTags = stateManager.getHydratedTags(undefined, true);

JSONUtilities.writeJson(
path.join(exportPath, AMPLIFY_EXPORT_TAGS_JSON_FILE),
path.join(exportPath, PathConstants.ExportTagsJsonFileName),
hydratedTags.map(tag => ({
key: tag.Key,
value: tag.Value,
Expand All @@ -113,7 +111,7 @@ function createTagsFile(exportPath: string) {
*/
function createCategoryStackMapping(resources: ResourceDefinition[], amplifyExportFolder: string) {
JSONUtilities.writeJson(
path.join(amplifyExportFolder, AMPLIFY_EXPORT_CATEGORY_STACK_MAPPING_FILE),
path.join(amplifyExportFolder, PathConstants.ExportCategoryStackMappingJsonFilename),
resources.map(r => {
return _.pick(r, ['category', 'resourceName', 'service']);
}),
Expand Down Expand Up @@ -170,7 +168,7 @@ function writeExportManifest(stackParameters: StackParameters, exportPath: strin
stackName: rootStackParametersKey,
props: transformManifestParameters(stackParameters[rootStackParametersKey], exportPath),
};
JSONUtilities.writeJson(path.join(amplifyExportFolder, AMPLIFY_EXPORT_MANIFEST_JSON_FILE), manifestJson);
JSONUtilities.writeJson(path.join(amplifyExportFolder, PathConstants.ExportManifestJsonFilename), manifestJson);
}

function transformManifestParameters(stackParameters: StackIncludeDetails, exportPath: string) {
Expand Down

0 comments on commit af1d446

Please sign in to comment.