diff --git a/src/cli/commands/create.js b/src/cli/commands/create.js index 0f998965fa..fb9926b3eb 100644 --- a/src/cli/commands/create.js +++ b/src/cli/commands/create.js @@ -16,6 +16,42 @@ export function hasWrapper(commander: Object, args: Array): boolean { return true; } +const coerceName = (name = '') => (name === '' ? 'create' : `create-${name}`); +const coerceScope = (scope = '') => (scope === '@' ? '' : scope); +const coerceFullName = (scope, name) => [coerceScope(scope), coerceName(name)].filter(Boolean).join('/'); + +/** + * # Tests + * + * ## basic + * parseBuilderName('name').packageName === 'create-name' + * parseBuilderName('@scope/name').packageName === '@scope/create-name' + * + * ## not adding "-" if name is empty + * parseBuilderName('@scope/').packageName === '@scope/create' + * parseBuilderName('@scope').packageName === '@scope/create' + * + * ## edge cases + * parseBuilderName('@/name').packageName === 'create-name' + * parseBuilderName('/name').packageName === 'create-name' + * parseBuilderName('@/').packageName === 'create' + */ +const parseBuilderName = str => { + const parts = str.split('/'); + if (parts.length === 1 && !str.includes('@')) { + return { + packageName: coerceName(str), + packageDir: '', + commandName: coerceName(str), + }; + } + return { + packageName: coerceFullName(parts[0], parts[1]), + packageDir: coerceScope(parts[0]), + commandName: coerceName(parts[1]), + }; +}; + export async function run(config: Config, reporter: Reporter, flags: Object, args: Array): Promise { const [builderName, ...rest] = args; @@ -23,10 +59,7 @@ export async function run(config: Config, reporter: Reporter, flags: Object, arg throw new MessageError(reporter.lang('invalidPackageName')); } - const packageName = builderName.replace(/^(@[^\/]+\/)?/, '$1create-'); - const packageDir = packageName.replace(/^(?:(@[^\/]+)\/)?.*/, '$1'); - const commandName = packageName.replace(/^@[^\/]+\//, ''); - + const {packageName, packageDir, commandName} = parseBuilderName(builderName); await runGlobal(config, reporter, {}, ['add', packageName]); const binFolder = await getBinFolder(config, {});