UNPKG

scai

Version:

> AI-powered CLI tool for commit messages **and** pull request reviews — using local models.

42 lines (41 loc) 2.01 kB
import fs from 'fs/promises'; import path from 'path'; import { runModulePipeline } from '../pipeline/runModulePipeline.js'; import { addCommentsModule } from '../pipeline/modules/commentModule.js'; import { cleanupModule } from '../pipeline/modules/cleanupModule.js'; export async function handleRefactor(filepath, options = {}) { try { // Normalize path: add ./ prefix if no directory specified if (!filepath.startsWith('./') && !filepath.startsWith('/') && !filepath.includes('\\')) { filepath = `./${filepath}`; } const { dir, name, ext } = path.parse(filepath); const refactoredPath = path.join(dir, `${name}.refactored${ext}`); // --apply flag: use existing refactored file and overwrite original if (options.apply) { try { const refactoredCode = await fs.readFile(refactoredPath, 'utf-8'); await fs.writeFile(filepath, refactoredCode, 'utf-8'); await fs.unlink(refactoredPath); console.log(`♻️ Applied refactor: Overwrote ${filepath} and removed ${refactoredPath}`); } catch { console.error(`❌ No saved refactor found at ${refactoredPath}`); } return; } // Read source code const content = await fs.readFile(filepath, 'utf-8'); // Run through pipeline modules const response = await runModulePipeline([addCommentsModule, cleanupModule], { content }); if (!response.content.trim()) throw new Error('⚠️ Model returned empty result'); // Save refactored output await fs.writeFile(refactoredPath, response.content, 'utf-8'); console.log(`✅ Refactored code saved to: ${refactoredPath}`); console.log(`ℹ️ Run again with '--apply' to overwrite the original.`); } catch (err) { console.error('❌ Error in refactor command:', err instanceof Error ? err.message : err); } }