scai
Version:
> AI-powered CLI tools for smart commit messages, auto generated comments, and readme files — all powered by local models.
42 lines (41 loc) • 1.99 kB
JavaScript
import fs from 'fs/promises';
import path from 'path';
import { runPromptPipeline } from '../pipeline/runPipeline.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 originalCode = await fs.readFile(filepath, 'utf-8');
// Run through pipeline modules
const refactored = await runPromptPipeline([addCommentsModule, cleanupModule], { code: originalCode });
if (!refactored.code.trim())
throw new Error('⚠️ Model returned empty result');
// Save refactored output
await fs.writeFile(refactoredPath, refactored.code, '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.message);
}
}