import inquirer from 'inquirer'; import chalk from 'chalk'; import * as path from 'path'; import { getAvailableTemplates, copyTemplate, templateExists } from '../utils/templateManager'; import { TemplateNotFoundError, FileSystemError, ConfigurationError, getErrorMessage } from '../errors'; /** * 模板选择项接口 */ interface TemplateChoice { name: string; value: string; description: string; } /** * 获取模板选择列表 * @returns 模板选择项数组 */ function getTemplateChoices(): TemplateChoice[] { const templates = getAvailableTemplates(); return templates.map(template => ({ name: `${template.name} - ${template.description}`, value: template.name, description: template.description })); } /** * 初始化项目命令 * 使用交互式提示让用户选择模板,然后复制模板到当前目录 */ export async function initProject(): Promise { try { const choices = getTemplateChoices(); if (choices.length === 0) { console.log(chalk.red('错误: 没有可用的模板')); process.exit(1); } // 交互式选择模板 const answers = await inquirer.prompt([ { type: 'list', name: 'template', message: '请选择项目模板:', choices: choices.map(c => ({ name: c.name, value: c.value })) } ]); const selectedTemplate = answers.template; const targetDir = process.cwd(); // 检查模板是否存在 if (!templateExists(selectedTemplate)) { console.log(chalk.red(`错误: 模板 '${selectedTemplate}' 不存在,请选择有效的模板`)); process.exit(1); } console.log(chalk.blue(`正在初始化 ${selectedTemplate} 项目...`)); // 复制模板到目标目录 await copyTemplate(selectedTemplate, targetDir); console.log(chalk.green(`✔ 项目初始化成功!`)); console.log(chalk.gray(`模板 '${selectedTemplate}' 已复制到当前目录`)); } catch (error) { handleInitError(error); process.exit(1); } } /** * 处理初始化过程中的错误 * @param error 错误对象 */ function handleInitError(error: unknown): void { if (error instanceof TemplateNotFoundError) { console.log(chalk.red(`错误: ${error.message}`)); console.log(chalk.yellow('提示: 使用 uniboot init 查看可用模板列表')); } else if (error instanceof ConfigurationError) { console.log(chalk.red(`配置错误: ${error.message}`)); console.log(chalk.yellow('提示: 请尝试重新安装 uniboot 工具')); } else if (error instanceof FileSystemError) { console.log(chalk.red(`文件系统错误: ${error.message}`)); if (error.originalError) { console.log(chalk.gray(`详细信息: ${error.originalError.message}`)); } } else { console.log(chalk.red(`错误: ${getErrorMessage(error)}`)); } }