bada-terminal / code-parser.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
22.3 kB
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;