File size: 5,508 Bytes
d739b1b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
class CodeDiffEngine {
constructor(db) {
this.db = db;
}
/**
* Capture a snapshot of code symbols and relations at a specific commit.
* @param {string} projectId
* @param {string} commitHash
* @returns {Object} The snapshot data
*/
async captureSnapshot(projectId, commitHash) {
// 1. Get code symbols
const symbols = await this.db.searchCodeSymbols(projectId, '');
// 2. Get relations (we can load all relations by querying with empty symbol ID if we support it,
// or we can query for each symbol, or query direct relations)
// Wait, let's make sure getCodeRelations supports retrieving all relations if we pass empty string or if we fetch all.
// Let's check getCodeRelations implementation in sqlite-db.js:
// It queries: SELECT * FROM code_relations WHERE project_id = ? AND (source_symbol_id = ? OR target_symbol_id = ?)
// To get all relations, we can implement a helper or query directly.
// Let's implement a simple query helper in our diff engine if we have direct access to database instance,
// or just fetch relations for each symbol.
// Wait! Since SqliteDb is used, if we use the JSON database fallback, we can access the data directly.
// Let's design a clean way:
const relations = [];
const symbolIds = symbols.map(s => s.id);
const seenRels = new Set();
for (const symId of symbolIds) {
const rels = await this.db.getCodeRelations(projectId, symId);
for (const r of rels) {
const key = `${r.source_symbol_id}->${r.target_symbol_id}[${r.relation_type}]`;
if (!seenRels.has(key)) {
seenRels.add(key);
relations.push(r);
}
}
}
return {
commitHash,
timestamp: new Date().toISOString(),
symbols,
relations
};
}
/**
* Diff two codebase snapshots.
* @param {Object} fromSnapshot
* @param {Object} toSnapshot
* @returns {Object} { added: Array, removed: Array, modified: Array }
*/
diffSnapshots(fromSnapshot, toSnapshot) {
const fromSymbols = fromSnapshot.symbols || [];
const toSymbols = toSnapshot.symbols || [];
const fromMap = new Map(fromSymbols.map(s => [s.id, s]));
const toMap = new Map(toSymbols.map(s => [s.id, s]));
const added = [];
const removed = [];
const modified = [];
// Check for added or modified
for (const [id, toSym] of toMap.entries()) {
if (!fromMap.has(id)) {
added.push(toSym);
} else {
const fromSym = fromMap.get(id);
// Basic check for modification: line range, signature, or properties changed
if (
fromSym.signature !== toSym.signature ||
fromSym.start_line !== toSym.start_line ||
fromSym.end_line !== toSym.end_line ||
JSON.stringify(fromSym.properties) !== JSON.stringify(toSym.properties)
) {
modified.push(toSym);
}
}
}
// Check for removed
for (const [id, fromSym] of fromMap.entries()) {
if (!toMap.has(id)) {
removed.push(fromSym);
}
}
return {
added,
removed,
modified
};
}
/**
* Install the post-commit git hook to trigger incremental updates.
* @param {string} projectPath
*/
setupGitHook(projectPath) {
const gitDir = path.join(projectPath, '.git');
if (!fs.existsSync(gitDir)) {
return false; // Not a git repository
}
const hooksDir = path.join(gitDir, 'hooks');
if (!fs.existsSync(hooksDir)) {
fs.mkdirSync(hooksDir, { recursive: true });
}
const hookPath = path.join(hooksDir, 'post-commit');
const hookScript = `#!/usr/bin/env node
const net = require('net');
const path = require('path');
const projectPath = path.resolve(__dirname, '../..');
// ์ธ์ฆ๊ฐ์ด ์๋ ์ธ๋ถ Git ์คํ์ ์ฑ์ ์ฝ๋ ๋ถ์ ๊ถํ์ ์ป์ง ์๋๋ค.
const token = process.env.BADA_MCP_TOKEN;
if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)) process.exit(0);
const request = {
jsonrpc: '2.0',
id: Date.now(),
method: 'tools/call',
params: {
name: 'bada_code_analyze',
arguments: {
project_path: projectPath,
incremental: true
}
}
};
const client = net.createConnection({ port: 55055, host: '127.0.0.1' }, () => {
client.write(JSON.stringify({ badaAuth: token }) + '\\n' + JSON.stringify(request) + '\\n');
});
let responseBuffer = '';
client.setEncoding('utf8');
client.on('data', chunk => {
responseBuffer += chunk;
let boundary;
while ((boundary = responseBuffer.indexOf('\\n')) >= 0) {
const line = responseBuffer.slice(0, boundary); responseBuffer = responseBuffer.slice(boundary + 1);
try {
const response = JSON.parse(line);
if (response.id === request.id) { client.end(); process.exit(0); }
} catch { client.end(); process.exit(0); }
}
});
client.on('error', () => {
process.exit(0);
});
setTimeout(() => {
process.exit(0);
}, 2000);
`;
fs.writeFileSync(hookPath, hookScript, { encoding: 'utf-8', mode: 0o755 });
// On macOS/Linux, ensure it's executable via chmod
if (process.platform !== 'win32') {
try {
execSync(`chmod +x "${hookPath}"`);
} catch (e) {
console.error('[CodeDiffEngine] Failed to chmod post-commit hook:', e.message);
}
}
return true;
}
}
module.exports = CodeDiffEngine;
|