import { readFileSync, existsSync } from "node:fs"; import { resolve } from "node:path"; import { execSync } from "node:child_process"; import { generateReport, formatReport } from "../../checker/engine.js"; export async function checkCode(target: string, root: string): Promise { const absRoot = resolve(root); console.log(`Checking code: ${target}\n`); let fileAnalyses: Array<{ path: string; content: string; language?: string }> = []; // Check if target is a file path const filePath = resolve(absRoot, target); if (existsSync(filePath)) { const content = readFileSync(filePath, "utf-8"); const lang = detectLanguage(filePath); fileAnalyses.push({ path: target, content, language: lang }); } else if (target.includes("..") || target.includes("HEAD")) { // Git diff range try { const diffFiles = execSync(`git diff --name-only ${target}`, { cwd: absRoot, encoding: "utf-8", }) .trim() .split("\n") .filter(Boolean); for (const file of diffFiles) { const fPath = resolve(absRoot, file); if (existsSync(fPath)) { const content = readFileSync(fPath, "utf-8"); fileAnalyses.push({ path: file, content, language: detectLanguage(file) }); } } } catch { console.log(" ⚠ Could not read git diff. Make sure you're in a git repo with commits."); console.log(" Usage: agentlens check or agentlens check "); return; } } else { console.log(` ⚠ File not found: ${target}`); console.log(" Usage: agentlens check or agentlens check HEAD~1..HEAD"); return; } if (fileAnalyses.length === 0) { console.log(" No files to check."); return; } const report = generateReport(fileAnalyses); console.log(formatReport(report)); // Exit with non-zero if critical issues found if (report.summary.critical > 0) { console.log(` ❌ ${report.summary.critical} critical issue(s) found.\n`); } else if (report.summary.warning > 0) { console.log(` ⚠ ${report.summary.warning} warning(s) found.\n`); } else { console.log(" ✅ All clear.\n"); } } function detectLanguage(filePath: string): string | undefined { const ext = filePath.split(".").pop()?.toLowerCase(); const langMap: Record = { ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript", mjs: "javascript", py: "python", go: "go", rs: "rust", java: "java", rb: "ruby", php: "php", }; return ext ? langMap[ext] : undefined; }