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
2 changes: 2 additions & 0 deletions lang/en.lyaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ 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 }}"
project:
subcommands:
watch:
Expand Down
152 changes: 125 additions & 27 deletions modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,16 +174,76 @@ const isModuleHTMLFile = filePath => MODULE_HTML_EXTENSION_REGEX.test(filePath);
*/
const isModuleCSSFile = filePath => MODULE_CSS_EXTENSION_REGEX.test(filePath);

/**
* 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;

// Ascertain the module's dest path based on module type
const parseDestPath = (name, dest, isReactModule) => {
TanyaScales marked this conversation as resolved.
Show resolved Hide resolved
const folderName = name.endsWith('.module') ? name : `${name}.module`;

const modulePath = !isReactModule
? path.join(dest, folderName)
: path.join(dest, `${name}`);

return modulePath;
};

const destPath = parseDestPath(name, dest, isReactModule);

// Create module directory
const createModuleDirectory = (allowExistingDir, destPath) => {
if (!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,
})
);
};

createModuleDirectory(options.allowExistingDir, destPath);

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

fs.writeJSONSync(dest, metaData, { spaces: 2 });
if (!reactType) {
fs.writeJSONSync(dest, metaData, { spaces: 2 });
} else {
const globalImportString = getInternalVersion
? 'import "./global-samplejsr.css";'
: '';
const defaultconfigString = getInternalVersion
? `export const defaultModuleConfig = {
moduleName: "sample_jsr",
version: 0,
};
`
: '';
TanyaScales marked this conversation as resolved.
Show resolved Hide resolved

fs.readFile(`${destPath}/index.tsx`, 'utf8', function(err, data) {
if (err) {
logger.error(
i18n(`${i18nKey}.errors.fileReadFailure`, {
path: `${dest}/index.tsx`,
})
);
return;
}

const result = data
.replace(/\/\* import global styles \*\//g, globalImportString)
.replace(/\/\* Default config \*\//g, defaultconfigString);

fs.writeFile(`${destPath}/index.tsx`, result, 'utf8', function(err) {
if (err) return console.log(err);
});
TanyaScales marked this conversation as resolved.
Show resolved Hide resolved

fs.appendFile(
`${dest}/index.tsx`,
'export const meta = ' + JSON.stringify(metaData, null, ' '),
err => {
if (err) {
logger.error(
i18n(`${i18nKey}.errors.failedToWrite`, {
path: `${dest}/index.tsx`,
})
);
return;
}
}
);
});
}
TanyaScales marked this conversation as resolved.
Show resolved Hide resolved
};

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

Expand All @@ -214,42 +322,32 @@ 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' : 'SampleJSR';
TanyaScales marked this conversation as resolved.
Show resolved Hide resolved

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