203 lines
6.3 KiB
JavaScript
Raw Normal View History

'use strict';
const { resolve, join, basename } = require('path');
const os = require('os');
const fse = require('fs-extra');
const ora = require('ora');
const ciEnv = require('ci-info');
const chalk = require('chalk');
2021-04-29 13:51:12 +02:00
const generateNewApp = require('@strapi/generate-new');
const hasYarn = require('./has-yarn');
const { runInstall, runApp, initGit } = require('./child-process');
2021-11-18 17:39:40 +01:00
const { getStarterPackageInfo, downloadNpmStarter } = require('./fetch-npm-starter');
const logger = require('./logger');
const stopProcess = require('./stop-process');
/**
* @param {string} - filePath Path to starter.json file
*/
2021-11-18 17:39:40 +01:00
function readStarterJson(filePath, starter) {
try {
const data = fse.readFileSync(filePath);
return JSON.parse(data);
} catch (err) {
2021-11-18 17:39:40 +01:00
stopProcess(`Could not find ${chalk.yellow('starter.json')} in ${chalk.yellow(starter)}`);
}
}
/**
2021-11-23 19:09:56 +01:00
* @param {string} rootPath - Path to the project directory
* @param {string} projectName - Name of the project
2021-11-23 16:58:16 +01:00
* @param {Object} options
* @param {boolean} options.useYarn - Use yarn instead of npm
*/
2021-11-23 19:09:56 +01:00
async function initPackageJson(rootPath, projectName, { useYarn } ) {
2021-11-23 12:57:53 +01:00
const packageManager = useYarn ? 'yarn --cwd' : 'npm run --prefix';
try {
await fse.writeJson(
join(rootPath, 'package.json'),
{
name: projectName,
private: true,
version: '0.0.0',
scripts: {
'develop:backend': `${packageManager} backend develop`,
'develop:frontend': `wait-on http://localhost:1337/admin && ${packageManager} frontend develop`,
2021-03-26 15:41:13 +01:00
develop: 'cross-env FORCE_COLOR=1 npm-run-all -l -p develop:*',
},
devDependencies: {
'npm-run-all': '4.1.5',
'wait-on': '5.2.1',
2021-03-26 15:41:13 +01:00
'cross-env': '7.0.3',
},
},
{
spaces: 2,
}
);
} catch (err) {
stopProcess(`Failed to create ${chalk.yellow(`package.json`)} in ${chalk.yellow(rootPath)}`);
}
}
/**
2021-11-23 19:09:56 +01:00
* @param {string} path The directory path for install
2021-11-23 16:58:16 +01:00
* @param {Object} options
* @param {boolean} options.useYarn Use yarn instead of npm
*/
2021-11-23 19:09:56 +01:00
async function installWithLogs(path, options) {
const installPrefix = chalk.yellow('Installing dependencies:');
const loader = ora(installPrefix).start();
const logInstall = (chunk = '') => {
loader.text = `${installPrefix} ${chunk
.toString()
.split('\n')
.join(' ')}`;
};
2021-11-23 19:09:56 +01:00
const runner = runInstall(path, options);
runner.stdout.on('data', logInstall);
runner.stderr.on('data', logInstall);
await runner;
loader.stop();
console.log(`Dependencies installed ${chalk.green('successfully')}.`);
}
2021-11-23 12:57:53 +01:00
/**
2021-11-23 19:09:56 +01:00
* @param {string} starter The name of the starter as provided by the user
2021-11-23 16:58:16 +01:00
* @param {Object} options
* @param {boolean} options.useYarn Use yarn instead of npm
2021-11-23 12:57:53 +01:00
*/
2021-11-23 19:09:56 +01:00
async function getStarterInfo(starter, { useYarn }) {
2021-11-23 10:32:04 +01:00
const isLocalStarter = ['./', '../', '/'].some(filePrefix => starter.startsWith(filePrefix));
2021-11-23 12:57:53 +01:00
2021-11-18 17:39:40 +01:00
let starterPath;
let starterParentPath;
let starterPackageInfo = {};
2021-11-18 17:39:40 +01:00
if (isLocalStarter) {
// Starter is a local directory
console.log('Installing local starter.');
2021-11-23 10:32:04 +01:00
starterPath = resolve(starter);
2021-11-18 17:39:40 +01:00
} else {
// Starter should be an npm package. Fetch starter info
2021-11-23 12:57:53 +01:00
starterPackageInfo = await getStarterPackageInfo(starter, useYarn);
2021-11-18 17:39:40 +01:00
console.log(`Installing ${chalk.yellow(starterPackageInfo.name)} starter.`);
// Download starter repository to a temporary directory
starterParentPath = await fse.mkdtemp(join(os.tmpdir(), 'strapi-'));
2021-11-23 12:57:53 +01:00
starterPath = await downloadNpmStarter(starterPackageInfo, starterParentPath, useYarn);
2021-11-18 17:39:40 +01:00
}
2021-11-23 10:32:04 +01:00
return { isLocalStarter, starterPath, starterParentPath, starterPackageInfo };
}
/**
2021-11-23 12:57:53 +01:00
* @param {Object} projectArgs - The arguments for create a project
2021-11-23 10:32:04 +01:00
* @param {string|null} projectArgs.projectName - The name/path of project
* @param {string|null} projectArgs.starter - The npm package of the starter
2021-11-23 12:57:53 +01:00
* @param {Object} program - Commands for generating new application
2021-11-23 10:32:04 +01:00
*/
module.exports = async function buildStarter({ projectName, starter }, program) {
2021-11-23 16:58:16 +01:00
const hasYarnInstalled = await hasYarn();
2021-11-23 12:57:53 +01:00
const {
isLocalStarter,
starterPath,
starterParentPath,
starterPackageInfo,
2021-11-23 19:09:56 +01:00
} = await getStarterInfo(starter, { useYarn: hasYarnInstalled });
2021-11-23 10:32:04 +01:00
// Project directory
const rootPath = resolve(projectName);
const projectBasename = basename(rootPath);
2021-11-18 17:39:40 +01:00
const starterJson = readStarterJson(join(starterPath, 'starter.json'), starter);
try {
await fse.ensureDir(rootPath);
} catch (error) {
stopProcess(`Failed to create ${chalk.yellow(rootPath)}: ${error.message}`);
}
// Copy the downloaded frontend folder to the project folder
const frontendPath = join(rootPath, 'frontend');
try {
2021-11-18 17:39:40 +01:00
await fse.copy(join(starterPath, 'starter'), frontendPath, {
overwrite: true,
recursive: true,
});
} catch (error) {
stopProcess(`Failed to create ${chalk.yellow(frontendPath)}: ${error.message}`);
}
2021-11-18 17:39:40 +01:00
// Delete the starter directory if it was downloaded
if (!isLocalStarter) {
await fse.remove(starterParentPath);
}
// Set command options for Strapi app
const generateStrapiAppOptions = {
...program,
2021-11-18 17:39:40 +01:00
starter: starterPackageInfo.name,
run: false,
};
2021-11-23 12:57:53 +01:00
if (starterPackageInfo.version) {
starterPackageInfo.template = `${starterJson.template.name}@${starterJson.template.version}`;
} else {
starterPackageInfo.template = starterJson.template.name;
}
// Create strapi app using the template
await generateNewApp(join(rootPath, 'backend'), generateStrapiAppOptions);
// Install frontend dependencies
2021-11-23 10:32:04 +01:00
console.log(`Creating Strapi starter frontend at ${chalk.yellow(frontendPath)}.`);
console.log('Installing frontend dependencies');
2021-11-23 19:09:56 +01:00
await installWithLogs(frontendPath, { useYarn: hasYarnInstalled });
// Setup monorepo
2021-11-23 19:09:56 +01:00
initPackageJson(rootPath, projectBasename, { useYarn: hasYarnInstalled });
// Add gitignore
try {
const gitignore = join(__dirname, '..', 'resources', 'gitignore');
await fse.copy(gitignore, join(rootPath, '.gitignore'));
} catch (err) {
logger.warn(`Failed to create file: ${chalk.yellow('.gitignore')}`);
}
2021-11-23 19:09:56 +01:00
await installWithLogs(rootPath, { useYarn: hasYarnInstalled });
if (!ciEnv.isCI) {
await initGit(rootPath);
}
console.log(chalk.green('Starting the app'));
2021-11-23 19:09:56 +01:00
await runApp(rootPath, { useYarn: hasYarnInstalled });
};