UNPKG

@mashakujou/autofix-cli

Version:

Autocorrector inteligente para comandos mal escritos en terminal

61 lines (50 loc) 1.8 kB
import leven from 'leven'; import { execSync } from 'child_process'; import readline from 'readline'; const knownCommands = [ 'cd', 'ls', 'cat', 'touch', 'node', 'npm', 'npx', 'git', 'python', 'python3', 'bash', 'sh', 'clear', 'micro', 'neofetch', 'curl', 'wget', 'mkdir', 'rmdir', 'rm', 'mv', 'cp', 'exit', 'whoami', 'top', 'ps', 'kill', 'ifconfig', 'ping', 'chmod', 'chown', 'su', 'sudo', 'apt', 'pkg', 'termux-setup-storage', 'service', 'systemctl', 'passwd', 'nano', 'vim', 'scp', 'ssh', 'zip', 'unzip' ]; const protected = ['type', 'exit', 'alias', 'source']; function askConfirm(question) { return new Promise(resolve => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question(question, answer => { rl.close(); resolve(answer.trim().toLowerCase()); }); }); } export async function fixCommand(input) { if (!input.trim()) return; const [cmd, ...args] = input.trim().split(/\s+/); if (protected.includes(cmd)) { console.log(`No se corregirá el comando protegido: "${cmd}"`); return; } const bestMatch = knownCommands .map(k => ({ cmd: k, dist: leven(cmd, k) })) .sort((a, b) => a.dist - b.dist)[0]; const suggestion = bestMatch?.dist <= 2 && bestMatch.cmd !== cmd ? `${bestMatch.cmd} ${args.join(' ')}` : input; if (suggestion !== input) { console.log(`?? Sugerencia: ${cmd}${bestMatch.cmd}`); const confirm = await askConfirm('¿Deseas ejecutar el comando corregido? (s/n): '); if (confirm !== 's') { console.log('❌ Comando cancelado.'); return; } } try { execSync(suggestion, { stdio: 'inherit', shell: true }); } catch (err) { console.error(`⚠️ Error al ejecutar: "${suggestion}"`); } }