strapi/packages/generators/app/lib/utils/fetch-npm-template.js

61 lines
2.0 KiB
JavaScript
Raw Normal View History

'use strict';
const path = require('path');
2021-10-26 20:01:26 +02:00
const execa = require('execa');
const chalk = require('chalk');
/**
* Gets the package version on npm. Will fail if the package does not exist
* @param {string} packageName - Name to look up on npm, may include a specific version
* @returns {Object}
*/
2021-10-27 16:37:30 +02:00
async function getPackageInfo(packageName) {
2022-02-24 11:12:08 +01:00
const { stdout } = await execa('npm', ['view', packageName, 'name', 'version', '--silent']);
// Use regex to parse name and version from CLI result
2021-10-26 20:01:26 +02:00
const [name, version] = stdout.match(/(?<=')(.*?)(?=')/gm);
return { name, version };
}
/**
2021-09-30 11:42:24 +02:00
* @param {string} template - The name of the template as provided by the user.
* @returns {Object} - The full name of the template package's name on npm
*/
async function getTemplatePackageInfo(template) {
2021-09-30 11:42:24 +02:00
// Check if template is a shorthand
try {
const longhand = `@strapi/template-${template}`;
2021-10-27 16:37:30 +02:00
const packageInfo = await getPackageInfo(longhand);
// Hasn't crashed so it is indeed a shorthand
return packageInfo;
} catch (error) {
// Ignore error, we now know it's not a shorthand
}
// Fetch version of the non-shorthand package
try {
return getPackageInfo(template);
} catch (error) {
2021-11-23 10:32:04 +01:00
throw new Error(`Could not find package ${chalk.yellow(template)} on npm`);
}
}
/**
* @param {Object} packageInfo - Template's npm package information
* @param {string} packageInfo.name
* @param {string} packageInfo.version
* @param {string} parentDir - Path inside of which we install the template.
*/
2021-10-27 16:37:30 +02:00
async function downloadNpmTemplate({ name, version }, parentDir) {
// Download from npm
2022-02-24 11:12:08 +01:00
await execa('npm', ['install', `${name}@${version}`, '--no-save', '--silent'], {
2021-10-26 20:01:26 +02:00
cwd: parentDir,
});
// Return the path of the actual template
2021-11-04 12:42:37 +01:00
const exactTemplatePath = path.dirname(
2021-11-04 14:01:02 +01:00
require.resolve(`${name}/package.json`, { paths: [parentDir] })
2021-11-04 12:42:37 +01:00
);
return exactTemplatePath;
}
module.exports = { getTemplatePackageInfo, downloadNpmTemplate };