Files
api-codegen/src/cli.ts

71 lines
2.8 KiB
TypeScript
Raw Normal View History

#!/usr/bin/env node
import { Command } from 'commander';
import chalk from 'chalk';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { validateConfig, type GeneratorConfig } from './config.js';
import { generate } from './generator.js';
import { fileExists } from './utils/file.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkg = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'));
const program = new Command();
const translateCommanderError = (message: string): string => {
return message
.replace(/^error:/, 'ошибка:')
.replace('unknown option', 'неизвестная опция')
.replace('too many arguments', 'слишком много аргументов')
.replace('option', 'опция');
};
program
.name('api-codegen')
.configureOutput({
writeErr: (message) => process.stderr.write(translateCommanderError(message)),
})
.description('Генерация TypeScript API клиента из OpenAPI спецификации')
.version(pkg.version)
.option('-i, --input <path>', 'Путь к OpenAPI спецификации (JSON/YAML файл или URL)')
.option('-o, --output <path>', 'Директория для сохранения сгенерированных файлов')
.option('-n, --name <name>', 'Имя монолитного клиента без расширения .ts')
.option('--mode <mode>', 'Режим генерации: single, split, both', 'single')
.option('--single-file', 'Устаревший алиас для --mode single')
.action(async (options) => {
try {
// Создание конфигурации
const config: Partial<GeneratorConfig> = {
inputPath: options.input,
outputPath: options.output,
fileName: options.name,
mode: options.singleFile ? 'single' : options.mode,
};
// Валидация конфигурации
validateConfig(config);
// Проверка существования входного файла (только для локальных файлов)
if (!config.inputPath!.startsWith('http://') && !config.inputPath!.startsWith('https://')) {
if (!(await fileExists(config.inputPath!))) {
console.error(chalk.red(`\n❌ Ошибка: входной файл не найден: ${config.inputPath}\n`));
process.exit(1);
}
}
// Генерация API
await generate(config as GeneratorConfig);
console.log(chalk.green('\n✨ API клиент успешно сгенерирован!\n'));
} catch (error) {
console.error(chalk.red('\n❌ Ошибка:'), error instanceof Error ? error.message : error);
console.error();
process.exit(1);
}
});
program.parse();