import fs from "fs-extra"; import path from "path"; import chalk from "chalk"; import inquirer from "inquirer"; import validateProjectName from "validate-npm-package-name"; import { clearConsole, stopSpinner } from "luban-cli-shared-utils"; import { CliOptions } from "../types"; import { Creator } from "./creator"; import { PromptModuleAPI } from "./promptModuleAPI"; function getPromptModules(): Array<(api: PromptModuleAPI) => void> { return ["babel", "typescript", "cssPreprocessor", "linter", "stylelint"].map( (file) => require(`./promptModules/${file}`).default, ); } /** * * @param {string} projectName * @param {import("./../types").CliOptions} options */ async function create(projectName: string, options: CliOptions): Promise { const cwd = process.cwd(); const inCurrent = projectName === "."; // 项目名称为 "." 则项目名称取当前目录的上级目录名称作为项目名称 const name = inCurrent ? path.relative("../", cwd) : projectName; const targetDir = path.resolve(cwd, projectName || "."); const result = validateProjectName(name); if (!result.validForNewPackages) { console.error(chalk.red(`Invalid project name: "${name}"`)); result.errors && result.errors.forEach((err) => { console.error(chalk.red.dim("Error: " + err)); }); result.warnings && result.warnings.forEach((warn) => { console.error(chalk.red.dim("Warning: " + warn)); }); process.exit(1); } if (fs.existsSync(targetDir)) { if (options.force) { await fs.remove(targetDir); } else { clearConsole(); if (inCurrent) { const { ok } = await inquirer.prompt([ { name: "ok", type: "confirm", message: `Generate project in current directory?`, }, ]); if (!ok) { return; } } else { const { action } = await inquirer.prompt([ { name: "action", type: "list", message: `Target directory ${chalk.cyan(targetDir)} already exists. Pick an action:`, choices: [ { name: "Overwrite", value: "overwrite" }, { name: "Merge", value: "merge" }, { name: "Cancel", value: false }, ], }, ]); if (!action) { return; } else if (action === "overwrite") { console.log(`\nRemoving ${chalk.cyan(targetDir)}...`); await fs.remove(targetDir); console.log(); } } } } const creator = new Creator(name, targetDir, options, getPromptModules()); await creator.create(); } export default function(projectName: string, options: CliOptions): Promise { return create(projectName, options).catch((error) => { stopSpinner(false); console.log(chalk.red(error)); }); }