import inquirer from 'inquirer'; import chalk from 'chalk'; import { getAvailableTemplates } from '../utils/templateManager'; import { syncRules, RulesSyncResult } from '../utils/rulesManager'; import { TemplateNotFoundError, FileSystemError, RulesNotFoundError, getErrorMessage } from '../errors'; /** * 模板选择项接口 */ interface TemplateChoice { name: string; value: string; } /** * 获取模板选择列表 * @returns 模板选择项数组 */ function getTemplateChoices(): TemplateChoice[] { const templates = getAvailableTemplates(); return templates.map(template => ({ name: `${template.name} - ${template.description}`, value: template.name })); } /** * 显示同步结果摘要 * @param result 同步结果 */ function displaySyncSummary(result: RulesSyncResult): void { console.log(chalk.green('\n✔ 规则文件同步完成!\n')); console.log(chalk.blue('同步摘要:')); console.log(` 新增文件: ${chalk.green(result.added.length)} 个`); console.log(` 更新文件: ${chalk.yellow(result.updated.length)} 个`); console.log(` 未变更文件: ${chalk.gray(result.unchanged.length)} 个`); if (result.added.length > 0) { console.log(chalk.green('\n新增的文件:')); result.added.forEach(file => { console.log(chalk.green(` + ${file}`)); }); } if (result.updated.length > 0) { console.log(chalk.yellow('\n更新的文件:')); result.updated.forEach(file => { console.log(chalk.yellow(` ~ ${file}`)); }); } } /** * 更新规则文件命令 * 使用交互式提示让用户选择模板,然后同步规则文件到当前目录 */ export async function updateRules(): 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 } ]); const selectedTemplate = answers.template; const targetDir = process.cwd(); console.log(chalk.blue(`正在从 ${selectedTemplate} 模板同步规则文件...`)); // 同步规则文件 const result = await syncRules(selectedTemplate, targetDir); // 显示同步结果摘要 displaySyncSummary(result); } catch (error) { handleUpdateRulesError(error); process.exit(1); } } /** * 处理更新规则过程中的错误 * @param error 错误对象 */ function handleUpdateRulesError(error: unknown): void { if (error instanceof TemplateNotFoundError) { console.log(chalk.red(`错误: ${error.message}`)); console.log(chalk.yellow('提示: 使用 uniboot updateRules 查看可用模板列表')); } else if (error instanceof RulesNotFoundError) { console.log(chalk.yellow(`提示: ${error.message}`)); } 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)}`)); } }