@ui18n/cli
Version:
🌍 UI18n CLI工具 - 强大的国际化命令行工具
271 lines • 9.21 kB
JavaScript
import { Command } from 'commander';
import chalk from 'chalk';
import boxen from 'boxen';
import updateNotifier from 'update-notifier';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { InitCommand } from './commands/init.js';
import { ExtractCommand } from './commands/extract.js';
import { TranslateCommand } from './commands/translate.js';
import { ConfigCommand } from './commands/config.js';
import { StatsCommand } from './commands/stats.js';
import { HealthCheckCommand } from './commands/health-check.js';
import { ValidateCommand } from './commands/validate.js';
import { OptimizeCommand } from './commands/optimize.js';
import { Logger } from './utils/logger.js';
import { ConfigManager } from './utils/config-manager.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
/**
* UI18n CLI核心类
*/
export class CLI {
constructor() {
this.program = new Command();
this.logger = new Logger();
this.configManager = new ConfigManager();
// 读取版本信息
try {
const packagePath = join(__dirname, '../package.json');
const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
this.version = packageJson.version;
}
catch {
this.version = '0.1.0';
}
this.setupProgram();
this.checkForUpdates();
}
/**
* 异步初始化CLI
*/
async initialize() {
await this.setupCommands();
}
/**
* 设置主程序
*/
setupProgram() {
this.program
.name('ui18n')
.description('🌍 UI18n CLI工具 - 强大的国际化命令行工具')
.version(this.version, '-v, --version', '显示版本信息')
.option('-c, --config <path>', '指定配置文件路径')
.option('--verbose', '显示详细输出')
.option('--silent', '静默模式')
.option('--no-colors', '禁用颜色输出')
.hook('preAction', (thisCommand) => {
this.setupLogger(thisCommand.opts());
});
// 显示帮助信息时的自定义格式
this.program.configureHelp({
sortSubcommands: true,
subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage(),
});
// 显示欢迎信息
this.program.addHelpText('before', this.getWelcomeMessage());
}
/**
* 设置所有命令
*/
async setupCommands() {
// 初始化命令
const initCommand = new InitCommand(this.logger);
this.program.addCommand(await initCommand.getCommand());
// 提取命令
const extractCommand = new ExtractCommand(this.logger);
this.program.addCommand(await extractCommand.getCommand());
// 翻译命令
const translateCommand = new TranslateCommand(this.logger);
this.program.addCommand(await translateCommand.getCommand());
// 配置命令
const configCommand = new ConfigCommand(this.logger);
this.program.addCommand(await configCommand.getCommand());
// 统计命令
const statsCommand = new StatsCommand(this.logger);
this.program.addCommand(await statsCommand.getCommand());
// 健康检查命令
const healthCheckCommand = new HealthCheckCommand(this.logger);
this.program.addCommand(await healthCheckCommand.getCommand());
// 验证命令
const validateCommand = new ValidateCommand(this.logger);
this.program.addCommand(await validateCommand.getCommand());
// 优化命令
const optimizeCommand = new OptimizeCommand(this.logger);
this.program.addCommand(await optimizeCommand.getCommand());
// 添加示例命令
this.addExampleCommands();
}
/**
* 添加示例命令
*/
addExampleCommands() {
this.program
.command('examples')
.description('显示使用示例')
.action(() => {
this.showExamples();
});
}
/**
* 设置日志器
*/
setupLogger(options) {
let level = 'info';
if (options.verbose) {
level = 'debug';
}
else if (options.silent) {
level = 'silent';
}
this.logger.setLevel(level);
this.logger.setColors(!options.noColors);
}
/**
* 检查更新
*/
checkForUpdates() {
try {
const packagePath = join(__dirname, '../package.json');
const pkg = JSON.parse(readFileSync(packagePath, 'utf-8'));
const notifier = updateNotifier({
pkg,
updateCheckInterval: 1000 * 60 * 60 * 24 // 24小时检查一次
});
if (notifier.update) {
const message = `发现新版本 ${chalk.green(notifier.update.latest)}!\n` +
`当前版本: ${chalk.red(notifier.update.current)}\n\n` +
`运行 ${chalk.cyan('npm install -g @ui18n/cli')} 更新`;
console.log(boxen(message, {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'yellow',
backgroundColor: '#040404'
}));
}
}
catch {
// 忽略更新检查错误
}
}
/**
* 获取欢迎信息
*/
getWelcomeMessage() {
return boxen(chalk.bold.blue('🌍 UI18n CLI工具') + '\n\n' +
chalk.gray('强大的国际化命令行工具,支持:') + '\n' +
chalk.green('• 项目初始化和配置') + '\n' +
chalk.green('• 智能文本提取') + '\n' +
chalk.green('• AI驱动的批量翻译') + '\n' +
chalk.green('• 翻译质量管理') + '\n' +
chalk.green('• 详细的统计报告') + '\n\n' +
chalk.yellow('使用 ui18n <command> --help 查看具体命令帮助'), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'blue',
backgroundColor: '#001122'
}) + '\n';
}
/**
* 显示使用示例
*/
showExamples() {
const examples = [
{
title: '🚀 快速开始',
commands: [
'ui18n init my-project',
'cd my-project',
'ui18n extract',
'ui18n translate --to en,ja,ko'
]
},
{
title: '📝 文本提取',
commands: [
'ui18n extract --output ./i18n/texts.json',
'ui18n extract --format yaml --watch',
'ui18n extract --merge --output ./locales/source.json'
]
},
{
title: '🌐 批量翻译',
commands: [
'ui18n translate --languages en,ja,ko',
'ui18n translate --input ./texts.json --languages en,ja,ko',
'ui18n translate --force --batch-size 50'
]
},
{
title: '⚙️ 配置管理',
commands: [
'ui18n config --list',
'ui18n config aiProvider.apiKey "your-api-key"',
'ui18n config extract.outputFormat yaml'
]
},
{
title: '📊 统计报告',
commands: [
'ui18n stats',
'ui18n stats --format html --output ./report.html',
'ui18n stats --detailed --format json'
]
}
];
console.log(chalk.bold.blue('\n🌍 UI18n CLI 使用示例\n'));
examples.forEach(({ title, commands }) => {
console.log(chalk.bold.yellow(title));
commands.forEach(cmd => {
console.log(chalk.gray(' $ ') + chalk.cyan(cmd));
});
console.log();
});
console.log(chalk.gray('更多信息请访问: ') + chalk.blue('https://github.com/iron-wayne/UI18N-OSS'));
}
/**
* 运行CLI
*/
async run(argv) {
try {
// 先初始化所有命令
await this.initialize();
// 然后解析命令行参数
await this.program.parseAsync(argv);
}
catch (error) {
this.logger.error('CLI执行失败:', error);
process.exit(1);
}
}
/**
* 获取程序实例
*/
getProgram() {
return this.program;
}
/**
* 获取日志器
*/
getLogger() {
return this.logger;
}
/**
* 获取配置管理器
*/
getConfigManager() {
return this.configManager;
}
/**
* 获取版本信息
*/
getVersion() {
return this.version;
}
}
// 默认导出
export default CLI;
//# sourceMappingURL=cli-core.js.map