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

Adding logic for React modules in create command #44

Closed
wants to merge 8 commits into from
3 changes: 3 additions & 0 deletions lang/en.lyaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ en:
creatingPath: "Creating {{ path }}"
errors:
pathExists: "The {{ path }} path already exists"
failedToWriteMeta: "There was an problem writing the module's meta data at {{ path }}"
fileReadFailure: "Failed to read file at {{ path }}"
failedToWrite: "failed to write to file at {{ path }}"
project:
subcommands:
watch:
Expand Down
167 changes: 140 additions & 27 deletions modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,16 +174,132 @@ const isModuleHTMLFile = filePath => MODULE_HTML_EXTENSION_REGEX.test(filePath);
*/
const isModuleCSSFile = filePath => MODULE_CSS_EXTENSION_REGEX.test(filePath);

// Strings to replace in React module files
const MODULE_STRING_TRANSFORMATIONS = [
{
regex: /\/\* import global styles \*\//g,
string: 'import "./global-samplejsr.css";',
fallback: '',
},
{
regex: /\/\* Default config \*\//g,
string:
'export const defaultModuleConfig = { \n moduleName: "sample_jsr", \n version: 0, \n};',
fallback: '',
},
];
/**
* createModule() helper - Takes a file and uses the constants above to transform the contents
* @param {string} file - the file being manipulated
* @param {object} metaData - an object containing the module's metadata
*/

const transformFileContents = (file, metaData, getInternalVersion) => {
Copy link

Choose a reason for hiding this comment

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

Is there an issue here where this function is doing async callbacky things bu there is no returned promise of async/await handling?

const i18nKey = 'cli.commands.create.subcommands.module.errors';
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
logger.error(
i18n(`${i18nKey}.fileReadFailure`, {
path: file,
})
);
return;
}

let results = data;

MODULE_STRING_TRANSFORMATIONS.forEach(entry => {
const replacementString = getInternalVersion
? entry.string
: entry.fallback;

results = results.replace(entry.regex, replacementString);
});

fs.writeFile(file, results, 'utf8', err => {
if (err) {
logger.error(
i18n(`${i18nKey}.failedToWrite`, {
path: file,
})
);
return;
}
});

fs.appendFile(
file,
'export const meta = ' + JSON.stringify(metaData, null, ' '),
err => {
if (err) {
logger.error(
i18n(`${i18nKey}.failedToWrite`, {
path: `${dest}/index.tsx`,
})
);
return;
}
}
);
});
};

/**
* Creates a sample module in the specified destination locally
* @param {object} moduleDefinition
* @param {string} moduleDefinition.moduleLabel - Label for the module
* @param {boolean} moduleDefinition.reactType - Identifies if the module is a JSR type
* @param {Array<String>} moduleDefinition.contentTypes - List of content types that the module can be used with
* @param {boolean} moduleDefinition.global - Identifies if the module is global
* @param {string} name
* @param {string} dest
* @param {boolean} getInternalVersion - flag to get internal spec of module
* @param {object} options
*/

const createModule = async (
moduleDefinition,
name,
dest,
getInternalVersion,
options = {
allowExistingDir: false,
}
) => {
const i18nKey = 'cli.commands.create.subcommands.module';
const writeModuleMeta = ({ contentTypes, moduleLabel, global }, dest) => {
const { reactType: isReactModule } = moduleDefinition;
const folderName = name.endsWith('.module') ? name : `${name}.module`;
const destPath = !isReactModule
? path.join(dest, folderName)
: path.join(dest, `${name}`);

if (!options.allowExistingDir && fs.existsSync(destPath)) {
logger.error(
i18n(`${i18nKey}.errors.pathExists`, {
path: destPath,
})
);
return;
} else {
logger.log(
i18n(`${i18nKey}.creatingPath`, {
path: destPath,
})
);
fs.ensureDirSync(destPath);
}

logger.log(
i18n(`${i18nKey}.creatingModule`, {
path: destPath,
})
);

// Write module meta
const writeModuleMeta = (
{ moduleLabel, contentTypes, global, reactType },
dest
) => {
const metaData = {
label: moduleLabel,
css_assets: [],
Expand All @@ -198,9 +314,14 @@ const createModule = async (
is_available_for_new_content: false,
};

fs.writeJSONSync(dest, metaData, { spaces: 2 });
if (!reactType) {
fs.writeJSONSync(dest, metaData, { spaces: 2 });
} else {
transformFileContents(`${dest}/index.tsx`, metaData, getInternalVersion);
}
TanyaScales marked this conversation as resolved.
Show resolved Hide resolved
};

// Filter out certain fetched files from the response
const moduleFileFilter = (src, dest) => {
const emailEnabled = moduleDefinition.contentTypes.includes('EMAIL');

Expand All @@ -214,42 +335,34 @@ const createModule = async (
return false;
}
return true;
case 'global-samplejsr.css':
case 'stories':
case 'tests':
if (getInternalVersion) {
return true;
}
return false;
default:
return true;
}
};

const folderName =
!name || name.endsWith('.module') ? name : `${name}.module`;
const destPath = path.join(dest, folderName);
if (!options.allowExistingDir && fs.existsSync(destPath)) {
logger.error(
i18n(`${i18nKey}.errors.pathExists`, {
path: destPath,
})
);
return;
} else {
logger.log(
i18n(`${i18nKey}.creatingPath`, {
path: destPath,
})
);
fs.ensureDirSync(destPath);
}

logger.log(
i18n(`${i18nKey}.creatingModule`, {
path: destPath,
})
);
// Download gitHub contents to the dest directory
const sampleAssetPath = !isReactModule
? 'Sample.module'
: 'SampleReactModule';

await downloadGitHubRepoContents(
'HubSpot/cms-sample-assets',
'modules/Sample.module',
`modules/${sampleAssetPath}`,
destPath,
{ filter: moduleFileFilter }
);

// Mutating React module files after fetch
if (isReactModule) {
writeModuleMeta(moduleDefinition, destPath);
}
};

module.exports = {
Expand Down
Loading