UNPKG

anyig

Version:

A powerful and extensible tool for generating ignore files for various development tools and environments

261 lines 11.3 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CLI = void 0; const inquirer_1 = __importDefault(require("inquirer")); const commander_1 = require("commander"); const templates_1 = require("./templates"); const file_1 = require("./utils/file"); const logger_1 = require("./utils/logger"); const config_1 = require("./config"); class CLI { program; config; constructor() { this.program = new commander_1.Command(); this.config = config_1.ConfigManager.loadConfig(); this.setupCommands(); } setupCommands() { this.program .name('anyig') .description('A powerful tool for generating ignore files') .version('2.0.0'); this.program .option('-m, --multiple', 'Select multiple templates') .option('-o, --output <dir>', 'Output directory') .option('-t, --template <name>', 'Generate specific template directly') .option('-l, --list', 'List all available templates') .option('--categories', 'List templates by categories') .option('--init-config', 'Create example configuration file') .option('--config <path>', 'Use specific configuration file') .option('--no-backup', 'Disable automatic backup of existing files') .option('--force', 'Force overwrite without confirmation') .action(async (options) => { await this.handleCommand(options); }); } async run() { await this.program.parseAsync(); } async handleCommand(options) { try { if (options.initConfig) { config_1.ConfigManager.createExampleConfig(); logger_1.Logger.success('Created example configuration file .anyigrc.json'); return; } if (options.config) { try { const customConfig = JSON.parse(file_1.FileUtils.readFile(options.config)); this.config = { ...this.config, ...customConfig }; } catch (error) { logger_1.Logger.error(`Failed to load config file: ${error.message}`); return; } } if (options.list) { this.listTemplates(); return; } if (options.categories) { this.listTemplatesByCategories(); return; } if (options.template) { await this.generateSpecificTemplate(options.template, options.output, options); return; } const userChoice = await this.promptUser(options); await this.generateFiles(userChoice); } catch (error) { logger_1.Logger.error(`Failed to generate ignore files: ${error.message}`); throw error; } } listTemplates() { logger_1.Logger.info('Available ignore file templates:'); console.log(); const customTemplates = this.config.customTemplates || []; const allAvailableTemplates = [...templates_1.allTemplates, ...customTemplates]; allAvailableTemplates.forEach(template => { logger_1.Logger.log(`• ${template.name} - ${template.description || template.filename}`); }); if (customTemplates.length > 0) { console.log(); logger_1.Logger.info(`Found ${customTemplates.length} custom template(s) from configuration.`); } } listTemplatesByCategories() { logger_1.Logger.info('Available ignore file templates by category:'); console.log(); templates_1.templateCategories.forEach(category => { logger_1.Logger.log(`📁 ${category.description} (${category.name})`); category.templates.forEach(template => { logger_1.Logger.log(` • ${template.name} - ${template.description || template.filename}`); }); console.log(); }); const customTemplates = this.config.customTemplates || []; if (customTemplates.length > 0) { logger_1.Logger.log('📁 Custom Templates'); customTemplates.forEach(template => { logger_1.Logger.log(` • ${template.name} - ${template.description || template.filename}`); }); } } async generateSpecificTemplate(templateName, outputDir, options) { let template = (0, templates_1.getTemplateByName)(templateName); if (!template && this.config.customTemplates) { template = this.config.customTemplates.find(t => t.name === templateName || t.filename === templateName); } if (!template) { throw new Error(`Template '${templateName}' not found. Use --list to see available templates.`); } const targetDir = outputDir || this.config.outputDir || process.cwd(); const filePath = file_1.FileUtils.getFullPath(template.filename, targetDir); if (file_1.FileUtils.willOverwrite(filePath)) { const force = options?.force; const shouldConfirm = this.config.confirmOverwrite && !force; if (shouldConfirm) { const { confirm } = await inquirer_1.default.prompt([{ type: 'confirm', name: 'confirm', message: `File ${template.filename} already exists. Overwrite?`, default: false }]); if (!confirm) { logger_1.Logger.info('Operation cancelled.'); return; } } if (this.config.autoBackup && !options?.noBackup) { try { const backupPath = file_1.FileUtils.backup(filePath); logger_1.Logger.info(`Backed up existing file to ${backupPath}`); } catch (error) { logger_1.Logger.warning(`Failed to backup file: ${error.message}`); } } } file_1.FileUtils.writeFile(filePath, template.content); logger_1.Logger.success(`Generated ${template.filename} successfully!`); } async promptUser(options) { const questions = []; if (options.multiple) { questions.push({ type: 'checkbox', name: 'templates', message: 'Select ignore files to generate:', choices: templates_1.allTemplates.map(template => ({ name: `${template.name} - ${template.description || template.filename}`, value: template.name, checked: false })), validate: (input) => { if (input.length === 0) { return 'Please select at least one template.'; } return true; } }); } else { questions.push({ type: 'list', name: 'templates', message: 'Select an ignore file to generate:', choices: [ ...templates_1.templateCategories.map(category => ({ name: `── ${category.description} ──`, disabled: true })), ...templates_1.templateCategories.flatMap(category => category.templates.map(template => ({ name: `${template.name} - ${template.description || template.filename}`, value: [template.name] }))) ] }); } if (options.output) { return { templates: options.multiple ? [] : [''], outputDir: options.output }; } const answers = await inquirer_1.default.prompt(questions); return { templates: Array.isArray(answers.templates) ? answers.templates : [answers.templates], outputDir: options.output }; } async generateFiles(userChoice) { const { templates, outputDir } = userChoice; const filesToGenerate = []; const existingFiles = []; for (const templateName of templates) { const template = (0, templates_1.getTemplateByName)(templateName); if (template) { filesToGenerate.push(template); const filePath = file_1.FileUtils.getFullPath(template.filename, outputDir); if (file_1.FileUtils.willOverwrite(filePath)) { existingFiles.push(template.filename); } } } if (existingFiles.length > 0) { const { action } = await inquirer_1.default.prompt([{ type: 'list', name: 'action', message: `The following files already exist: ${existingFiles.join(', ')}. What would you like to do?`, choices: [ { name: 'Overwrite all', value: 'overwrite' }, { name: 'Skip existing files', value: 'skip' }, { name: 'Backup and overwrite', value: 'backup' }, { name: 'Cancel', value: 'cancel' } ] }]); if (action === 'cancel') { logger_1.Logger.info('Operation cancelled.'); return; } if (action === 'backup') { for (const filename of existingFiles) { const filePath = file_1.FileUtils.getFullPath(filename, outputDir); const backupPath = file_1.FileUtils.backup(filePath); logger_1.Logger.info(`Backed up ${filename} to ${backupPath}`); } } else if (action === 'skip') { const existingFilenames = new Set(existingFiles); filesToGenerate.splice(0, filesToGenerate.length, ...filesToGenerate.filter(template => !existingFilenames.has(template.filename))); } } let generatedCount = 0; for (const template of filesToGenerate) { try { const filePath = file_1.FileUtils.getFullPath(template.filename, outputDir); file_1.FileUtils.writeFile(filePath, template.content); logger_1.Logger.success(`Generated ${template.filename}`); generatedCount++; } catch (error) { logger_1.Logger.error(`Failed to generate ${template.filename}: ${error.message}`); } } if (generatedCount > 0) { logger_1.Logger.success(`Successfully generated ${generatedCount} ignore file(s)!`); } else { logger_1.Logger.warning('No files were generated.'); } } } exports.CLI = CLI; //# sourceMappingURL=cli.js.map