/** * Edit code with AI assistance */ import inquirer from 'inquirer'; import chalk from 'chalk'; import ora from 'ora'; import * as fs from 'fs/promises'; import { OllamaClient, CodeAnalyzer } from '@fsfalmansour/neohub-core'; import { ConfigManager } from '../config'; interface EditOptions { file: string; instruction: string; backup?: boolean; } export async function editCommand(options: EditOptions): Promise { const config = new ConfigManager(); const ollama = new OllamaClient(config.getOllamaConfig()); try { // Read the file const spinner = ora('Reading file...').start(); const context = await CodeAnalyzer.readFile(options.file); spinner.succeed(chalk.green(`Loaded ${options.file}`)); // Create backup if requested if (options.backup) { await fs.copyFile(options.file, `${options.file}.backup`); console.log(chalk.gray(`Backup created: ${options.file}.backup`)); } // Generate edit with AI spinner.start('Generating edit...'); const prompt = `You are editing the file: ${context.filePath} Current content: \`\`\`${context.language} ${context.content} \`\`\` Instruction: ${options.instruction} Please provide the complete modified file content. Only output the code, no explanations.`; const response = await ollama.complete(prompt, { temperature: 0.1, num_predict: 4096, }); spinner.succeed(chalk.green('Edit generated')); // Extract code from response let newContent = response.trim(); // Remove markdown code blocks if present const codeBlockMatch = newContent.match(/```[\w]*\n([\s\S]*?)\n```/); if (codeBlockMatch) { newContent = codeBlockMatch[1]; } // Show diff preview console.log(chalk.bold('\nProposed changes:\n')); console.log(chalk.gray('─'.repeat(80))); console.log(newContent); console.log(chalk.gray('─'.repeat(80))); // Confirm before saving const { confirm } = await inquirer.prompt<{ confirm: boolean }>([ { type: 'confirm', name: 'confirm', message: 'Apply these changes?', default: true, }, ]); if (confirm) { await fs.writeFile(options.file, newContent, 'utf-8'); console.log(chalk.bold.green(`\nāœ“ Changes saved to ${options.file}\n`)); } else { console.log(chalk.yellow('\nChanges discarded\n')); } } catch (error) { console.error(chalk.red('Error: ' + (error as Error).message)); process.exit(1); } }