const fs = require('fs'); const path = require('path'); const db = require('./knowledge-db'); const ts = require('typescript'); const configManager = require('./src/config-manager'); class CodeParser { /** * 프로젝트 내 .gitignore 패턴 조회 */ static loadGitignorePatterns(srcPath) { const gitignorePath = path.join(srcPath, '.gitignore'); const patterns = []; if (fs.existsSync(gitignorePath)) { try { const content = fs.readFileSync(gitignorePath, 'utf-8'); content.split('\n').forEach(line => { const trimmed = line.trim(); if (trimmed && !trimmed.startsWith('#')) { patterns.push(trimmed); } }); } catch (e) { console.error('[CodeParser] Failed to load .gitignore:', e); } } return patterns; } /** * 파일 경로가 무시 패턴에 매칭되는지 확인 */ static shouldIgnore(itemPath, patterns) { const normalized = itemPath.replace(/\\/g, '/'); for (const pattern of patterns) { let cleanPattern = pattern.replace(/^\//, ''); const isDirOnly = cleanPattern.endsWith('/'); if (isDirOnly) { cleanPattern = cleanPattern.slice(0, -1); } let regexStr = cleanPattern .replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') .replace(/\\\*/g, '.*'); const regex = new RegExp('^' + regexStr + '(/.*)?$'); if (regex.test(normalized)) { return true; } } return false; } /** * JS/TS 파일 AST 파싱 */ static parseJsTs(filePath, content) { const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true); const entities = []; const imports = []; function visit(node) { // 클래스 선언 if (ts.isClassDeclaration(node) && node.name) { const className = node.name.text; const startPos = node.getStart(sourceFile); const endPos = node.getEnd(); const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line + 1; const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line + 1; entities.push({ type: 'class', name: className, startLine, endLine }); // 클래스 메서드 node.members.forEach(member => { if (ts.isMethodDeclaration(member) && member.name) { const methodName = member.name.getText(sourceFile); const mStart = member.getStart(sourceFile); const mEnd = member.getEnd(); const mStartLine = sourceFile.getLineAndCharacterOfPosition(mStart).line + 1; const mEndLine = sourceFile.getLineAndCharacterOfPosition(mEnd).line + 1; entities.push({ type: 'function', name: `${className}.${methodName}`, startLine: mStartLine, endLine: mEndLine }); } }); } // 일반 함수 선언 else if (ts.isFunctionDeclaration(node) && node.name) { const funcName = node.name.text; const startPos = node.getStart(sourceFile); const endPos = node.getEnd(); const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line + 1; const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line + 1; entities.push({ type: 'function', name: funcName, startLine, endLine }); } // 변수 할당 함수 (const myFunction = () => {}) else if (ts.isVariableDeclaration(node) && node.name && node.initializer) { const init = node.initializer; if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) { const funcName = node.name.getText(sourceFile); const startPos = node.getStart(sourceFile); const endPos = node.getEnd(); const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line + 1; const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line + 1; entities.push({ type: 'function', name: funcName, startLine, endLine }); } } // ES6 임포트 else if (ts.isImportDeclaration(node) && node.moduleSpecifier) { const moduleSpecifier = node.moduleSpecifier.getText(sourceFile).replace(/['"]/g, ''); imports.push(moduleSpecifier); } // CommonJS require 호출 else if (ts.isCallExpression(node) && node.expression.getText(sourceFile) === 'require') { if (node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) { imports.push(node.arguments[0].text); } } ts.forEachChild(node, visit); } visit(sourceFile); return { entities, imports }; } /** * Python 파일 들여쓰기 기반 라인 파싱 */ static parsePython(content) { const lines = content.split(/\r?\n/); const entities = []; const imports = []; let inTripleQuotes = false; let tripleQuotesChar = ''; const classStack = []; const funcStack = []; for (let i = 0; i < lines.length; i++) { const rawLine = lines[i]; const trimmed = rawLine.trim(); const lineNum = i + 1; // 1. 트리플 쿼트 처리 (주석/독스트링 블록) if (inTripleQuotes) { if (trimmed.includes(tripleQuotesChar)) { inTripleQuotes = false; } continue; } if (trimmed.startsWith('"""') || trimmed.startsWith("'''")) { const q = trimmed.slice(0, 3); if (trimmed.slice(3).includes(q)) { continue; } inTripleQuotes = true; tripleQuotesChar = q; continue; } // 일반 주석 및 빈 라인 스킵 if (trimmed.startsWith('#') || trimmed === '') { continue; } const indentMatch = rawLine.match(/^([ \t]*)/); const indent = indentMatch ? indentMatch[1].length : 0; // 2. 들여쓰기 수준에 따른 클래스/함수 스택 팝 (블록 종료 감지) while (funcStack.length > 0 && indent <= funcStack[funcStack.length - 1].indent) { const closed = funcStack.pop(); entities.push({ type: 'function', name: closed.parentClass ? `${closed.parentClass}.${closed.name}` : closed.name, startLine: closed.startLine, endLine: Math.max(closed.startLine, lineNum - 1) }); } while (classStack.length > 0 && ( indent < classStack[classStack.length - 1].indent || (indent === classStack[classStack.length - 1].indent && ( trimmed.startsWith('class ') || trimmed.startsWith('def ') || !trimmed.startsWith(' ') )) )) { const closed = classStack.pop(); entities.push({ type: 'class', name: closed.name, startLine: closed.startLine, endLine: Math.max(closed.startLine, lineNum - 1) }); } // 3. 클래스 선언 매칭 const classMatch = trimmed.match(/^class\s+(\w+)/); if (classMatch) { classStack.push({ name: classMatch[1], indent: indent, startLine: lineNum }); continue; } // 4. 함수/메서드 선언 매칭 const funcMatch = trimmed.match(/^def\s+(\w+)\s*\(/); if (funcMatch) { const parentClass = classStack.length > 0 ? classStack[classStack.length - 1].name : null; funcStack.push({ name: funcMatch[1], indent: indent, startLine: lineNum, parentClass: parentClass }); continue; } // 5. 임포트 선언 매칭 const importMatch = trimmed.match(/^(?:import\s+([\w.]+))|(?:from\s+([\w.]+)\s+import)/); if (importMatch) { const mod = importMatch[1] || importMatch[2]; if (mod) { imports.push(mod.split('.')[0]); } } } const lastLineNum = lines.length; while (funcStack.length > 0) { const closed = funcStack.pop(); entities.push({ type: 'function', name: closed.parentClass ? `${closed.parentClass}.${closed.name}` : closed.name, startLine: closed.startLine, endLine: lastLineNum }); } while (classStack.length > 0) { const closed = classStack.pop(); entities.push({ type: 'class', name: closed.name, startLine: closed.startLine, endLine: lastLineNum }); } return { entities, imports }; } /** * codegraph 백그라운드 인덱싱 비동기 가동 */ static runCodegraphIndex(srcPath) { try { const configManager = require('./src/config-manager'); const kConfig = configManager.getKnowledgeConfig(); if (!kConfig.graphfyEnabled) { return; } const { exec } = require('child_process'); const graphfyPath = kConfig.graphfyPath; let cmd = 'codegraph init --yes'; if (graphfyPath && fs.existsSync(graphfyPath)) { cmd = `"${graphfyPath}" init --yes`; } else { cmd = 'npx -y @colbymchenry/codegraph init --yes'; } console.log(`[CodeParser] Starting CodeGraph background indexing at ${srcPath} with command: ${cmd}`); exec(cmd, { cwd: srcPath }, (error, stdout, stderr) => { if (error) { console.error(`[CodeParser] CodeGraph indexing failed: ${error.message}`); return; } console.log(`[CodeParser] CodeGraph indexing completed successfully for ${srcPath}`); }); } catch (e) { console.error('[CodeParser] Failed to run codegraph index helper:', e.message); } } /** * 프로젝트 코드베이스를 스캔하여 구조적 관계를 SQLite DB에 적재 */ static async analyze(projectId, srcPath, customExcludes = []) { if (!fs.existsSync(srcPath)) { return { success: false, error: 'Source directory does not exist' }; } // codegraph 인덱싱 비동기 가동 this.runCodegraphIndex(srcPath); const stats = { filesScanned: 0, functionsFound: 0, classesFound: 0, dependenciesFound: 0 }; try { const gitignorePatterns = this.loadGitignorePatterns(srcPath); let excludesArray = []; if (Array.isArray(customExcludes)) { excludesArray = customExcludes; } else if (typeof customExcludes === 'string') { excludesArray = customExcludes.split(',').map(s => s.trim()).filter(Boolean); } const allPatterns = [...gitignorePatterns, ...excludesArray]; const files = this.scanDirRecursive(srcPath, srcPath, 0, allPatterns); const config = configManager.getKnowledgeConfig(); const codeIntelEnabled = config.codeIntelEnabled !== false; for (const fileRelPath of files) { // Yield to the event loop to keep the Electron UI responsive await new Promise(resolve => setImmediate(resolve)); const fullPath = path.join(srcPath, fileRelPath); const fileExt = path.extname(fileRelPath).toLowerCase(); // 정적 분석 가능한 파일 확장자 필터링 if (!['.js', '.jsx', '.ts', '.tsx', '.py'].includes(fileExt)) continue; stats.filesScanned++; const fileNodeId = 'file-' + fullPath; const fileName = path.basename(fileRelPath); // 1. 파일 노드 확보 db.saveNode(projectId, { id: fileNodeId, type: 'file', label: fileName, properties: { fullPath, size: fs.statSync(fullPath).size, analyzedAt: new Date().toISOString() } }); if (codeIntelEnabled) { db.saveCodeSymbol(projectId, { id: fileNodeId, symbol_type: 'file', name: fileName, file_path: fullPath, start_line: 0, end_line: 0 }); } try { const content = fs.readFileSync(fullPath, 'utf-8'); let parsedData = { entities: [], imports: [] }; if (['.js', '.jsx', '.ts', '.tsx'].includes(fileExt)) { parsedData = this.parseJsTs(fullPath, content); } else if (fileExt === '.py') { parsedData = this.parsePython(content); } // 2. 임포트 / 의존성 분석 for (const depPath of parsedData.imports) { if (depPath && !depPath.startsWith('.')) { // 외장 라이브러리 의존성 const depId = 'library-' + depPath; db.saveNode(projectId, { id: depId, type: 'library', label: depPath }); db.saveEdge(projectId, { source: fileNodeId, target: depId, label: 'imports' }); stats.dependenciesFound++; if (codeIntelEnabled) { db.saveCodeSymbol(projectId, { id: depId, symbol_type: 'library', name: depPath, file_path: '', start_line: 0, end_line: 0 }); db.saveCodeRelation(projectId, { source_symbol_id: fileNodeId, target_symbol_id: depId, relation_type: 'imports' }); } } else if (depPath && depPath.startsWith('.')) { // 내장 파일 간 의존성 try { const resolvedPath = this.resolveLocalImport(path.dirname(fullPath), depPath, fileExt); if (resolvedPath && fs.existsSync(resolvedPath)) { const targetFileId = 'file-' + resolvedPath; db.saveNode(projectId, { id: targetFileId, type: 'file', label: path.basename(resolvedPath), properties: { fullPath: resolvedPath } }); db.saveEdge(projectId, { source: fileNodeId, target: targetFileId, label: 'depends_on' }); stats.dependenciesFound++; if (codeIntelEnabled) { db.saveCodeSymbol(projectId, { id: targetFileId, symbol_type: 'file', name: path.basename(resolvedPath), file_path: resolvedPath, start_line: 0, end_line: 0 }); db.saveCodeRelation(projectId, { source_symbol_id: fileNodeId, target_symbol_id: targetFileId, relation_type: 'depends_on' }); } } } catch (e) { // 파일 탐색 실패 무시 } } } // 3. 클래스 및 함수 적재 for (const entity of parsedData.entities) { const entityId = `code-${fullPath}#${entity.name}`; db.saveNode(projectId, { id: entityId, type: 'code', label: entity.type === 'class' ? `class ${entity.name}` : `${entity.name}()`, properties: { file: fullPath, entityType: entity.type, name: entity.name, startLine: entity.startLine, endLine: entity.endLine } }); db.saveEdge(projectId, { source: fileNodeId, target: entityId, label: entity.type === 'class' ? 'defines_class' : 'defines_function' }); if (codeIntelEnabled) { db.saveCodeSymbol(projectId, { id: entityId, symbol_type: entity.type, name: entity.name, file_path: fullPath, start_line: entity.startLine, end_line: entity.endLine }); db.saveCodeRelation(projectId, { source_symbol_id: fileNodeId, target_symbol_id: entityId, relation_type: entity.type === 'class' ? 'defines_class' : 'defines_function' }); } if (entity.type === 'class') { stats.classesFound++; } else { stats.functionsFound++; } } } catch (e) { console.error(`[CodeParser] Error scanning contents of ${fileRelPath}:`, e); } } return { success: true, stats }; } catch (e) { console.error('[CodeParser] Codebase analysis failed:', e); return { success: false, error: e.message }; } } /** * 로컬 모듈 임포트 경로 해석 */ static resolveLocalImport(baseDir, importPath, referrerExt) { const fullImport = path.resolve(baseDir, importPath); const extensions = ['.js', '.jsx', '.ts', '.tsx', '.py']; // 1. 단일 파일 확장자 대응 if (fs.existsSync(fullImport) && fs.statSync(fullImport).isFile()) { return fullImport; } for (const ext of extensions) { if (fs.existsSync(fullImport + ext)) { return fullImport + ext; } } // 2. 폴더 임포트 대응 (index.js 등) if (fs.existsSync(fullImport) && fs.statSync(fullImport).isDirectory()) { for (const ext of extensions) { const indexFile = path.join(fullImport, 'index' + ext); if (fs.existsSync(indexFile)) { return indexFile; } } } return null; } /** * 디렉토리 재귀 스캔 (무시 폴더 필터링) */ static scanDirRecursive(dir, rootDir = dir, depth = 0, ignorePatterns = [], filesAcc = []) { if (depth > 8 || filesAcc.length >= 1000) return filesAcc; const ignoreFolders = [ 'node_modules', '.git', 'dist', 'build', 'coverage', '.gemini', '.output', 'bin', 'obj', '.next', '.nuxt', '.venv', 'venv', 'env', '__pycache__', '.sass-cache', '.eslintcache', 'vendor', '.idea', '.vscode', '.cache', 'out', 'target' ]; try { const items = fs.readdirSync(dir); const slicedItems = items.slice(0, 300); for (const item of slicedItems) { if (filesAcc.length >= 1000) break; const fullPath = path.join(dir, item); const relPath = path.relative(rootDir, fullPath); if (this.shouldIgnore(relPath, ignorePatterns)) { continue; } let stat; try { stat = fs.statSync(fullPath); } catch (e) { continue; } if (stat.isDirectory()) { if (ignoreFolders.includes(item) || item.startsWith('.')) continue; this.scanDirRecursive(fullPath, rootDir, depth + 1, ignorePatterns, filesAcc); } else if (stat.isFile()) { filesAcc.push(relPath); } } } catch (e) { console.error(`[CodeParser] Error scanning directory ${dir}:`, e); } return filesAcc; } /** * AST 기반 코드 요약 (시그니처만 보존하고 함수/클래스 본문 생략) */ static summarizeCode(filePath, content, minLines = 4) { const ext = path.extname(filePath).toLowerCase(); // JS / TS 요약 if (['.js', '.jsx', '.ts', '.tsx'].includes(ext)) { try { const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true); const replacements = []; function visit(node) { if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { const body = node.body; if (body && ts.isBlock(body)) { const startPos = body.getStart(sourceFile); const endPos = body.getEnd(); const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line; const linesCount = endLine - startLine; if (linesCount >= minLines) { replacements.push({ start: startPos + 1, end: endPos - 1, text: `\n // [Body omitted: ${linesCount} lines]\n ` }); } } } ts.forEachChild(node, visit); } visit(sourceFile); replacements.sort((a, b) => b.start - a.start); let summarized = content; for (const rep of replacements) { summarized = summarized.slice(0, rep.start) + rep.text + summarized.slice(rep.end); } return summarized; } catch (e) { console.error('[CodeParser] JS/TS AST summarization failed:', e); return content; } } // Python 요약 (들여쓰기 및 parsePython 구문 엔티티 활용) if (ext === '.py') { try { const lines = content.split(/\r?\n/); const summarizedLines = []; let skipUntil = -1; const pythonData = this.parsePython(content); const functions = pythonData.entities.filter(e => e.type === 'function' && (e.endLine - e.startLine) >= minLines); for (let i = 0; i < lines.length; i++) { const lineNum = i + 1; if (lineNum <= skipUntil) { continue; } const func = functions.find(f => f.startLine === lineNum); if (func) { const defLine = lines[i]; summarizedLines.push(defLine); const indentMatch = defLine.match(/^([ \t]*)/); const indentStr = indentMatch ? indentMatch[1] : ''; summarizedLines.push(`${indentStr} # [Body omitted: ${func.endLine - func.startLine} lines]`); skipUntil = func.endLine; } else { summarizedLines.push(lines[i]); } } return summarizedLines.join('\n'); } catch (e) { console.error('[CodeParser] Python AST summarization failed:', e); return content; } } return content; } } module.exports = CodeParser;