-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathimpact.js
More file actions
675 lines (615 loc) · 21.5 KB
/
Copy pathimpact.js
File metadata and controls
675 lines (615 loc) · 21.5 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import {
findDbPath,
findDistinctCallers,
findFileNodes,
findImplementors,
findImportDependents,
findNodeById,
openReadonlyOrFail,
} from '../../db/index.js';
import { evaluateBoundaries } from '../../features/boundaries.js';
import { coChangeForFiles } from '../../features/cochange.js';
import { ownersForFiles } from '../../features/owners.js';
import { loadConfig } from '../../infrastructure/config.js';
import { debug } from '../../infrastructure/logger.js';
import { isTestFile } from '../../infrastructure/test-filter.js';
import { normalizeSymbol } from '../../shared/normalize.js';
import { paginateResult } from '../../shared/paginate.js';
import { findMatchingNodes } from './symbol-lookup.js';
// ─── Shared BFS: transitive callers ────────────────────────────────────
const INTERFACE_LIKE_KINDS = new Set(['interface', 'trait']);
/**
* Check whether the graph contains any 'implements' edges.
* Cached per db handle so the query runs at most once per connection.
*/
const _hasImplementsCache = new WeakMap();
function hasImplementsEdges(db) {
if (_hasImplementsCache.has(db)) return _hasImplementsCache.get(db);
const row = db.prepare("SELECT 1 FROM edges WHERE kind = 'implements' LIMIT 1").get();
const result = !!row;
_hasImplementsCache.set(db, result);
return result;
}
/**
* BFS traversal to find transitive callers of a node.
* When an interface/trait node is encountered (either as the start node or
* during traversal), its concrete implementors are also added to the frontier
* so that changes to an interface signature propagate to all implementors.
*
* @param {import('better-sqlite3').Database} db - Open read-only SQLite database handle (not a Repository)
* @param {number} startId - Starting node ID
* @param {{ noTests?: boolean, maxDepth?: number, includeImplementors?: boolean, onVisit?: (caller: object, parentId: number, depth: number) => void }} options
* @returns {{ totalDependents: number, levels: Record<number, Array<{name:string, kind:string, file:string, line:number}>> }}
*/
export function bfsTransitiveCallers(
db,
startId,
{ noTests = false, maxDepth = 3, includeImplementors = true, onVisit } = {},
) {
// Skip all implementor lookups when the graph has no implements edges
const resolveImplementors = includeImplementors && hasImplementsEdges(db);
const visited = new Set([startId]);
const levels = {};
let frontier = [startId];
// Seed: if start node is an interface/trait, include its implementors at depth 1.
// Implementors go into a separate list so their callers appear at depth 2, not depth 1.
const implNextFrontier = [];
if (resolveImplementors) {
const startNode = findNodeById(db, startId);
if (startNode && INTERFACE_LIKE_KINDS.has(startNode.kind)) {
const impls = findImplementors(db, startId);
for (const impl of impls) {
if (!visited.has(impl.id) && (!noTests || !isTestFile(impl.file))) {
visited.add(impl.id);
implNextFrontier.push(impl.id);
if (!levels[1]) levels[1] = [];
levels[1].push({
name: impl.name,
kind: impl.kind,
file: impl.file,
line: impl.line,
viaImplements: true,
});
if (onVisit) onVisit({ ...impl, viaImplements: true }, startId, 1);
}
}
}
}
for (let d = 1; d <= maxDepth; d++) {
// On the first wave, merge seeded implementors so their callers appear at d=2
if (d === 1 && implNextFrontier.length > 0) {
frontier = [...frontier, ...implNextFrontier];
}
const nextFrontier = [];
for (const fid of frontier) {
const callers = findDistinctCallers(db, fid);
for (const c of callers) {
if (!visited.has(c.id) && (!noTests || !isTestFile(c.file))) {
visited.add(c.id);
nextFrontier.push(c.id);
if (!levels[d]) levels[d] = [];
levels[d].push({ name: c.name, kind: c.kind, file: c.file, line: c.line });
if (onVisit) onVisit(c, fid, d);
}
// If a caller is an interface/trait, also pull in its implementors
// Implementors are one extra hop away, so record at d+1
if (resolveImplementors && INTERFACE_LIKE_KINDS.has(c.kind)) {
const impls = findImplementors(db, c.id);
for (const impl of impls) {
if (!visited.has(impl.id) && (!noTests || !isTestFile(impl.file))) {
visited.add(impl.id);
nextFrontier.push(impl.id);
const implDepth = d + 1;
if (!levels[implDepth]) levels[implDepth] = [];
levels[implDepth].push({
name: impl.name,
kind: impl.kind,
file: impl.file,
line: impl.line,
viaImplements: true,
});
if (onVisit) onVisit({ ...impl, viaImplements: true }, c.id, implDepth);
}
}
}
}
}
frontier = nextFrontier;
if (frontier.length === 0) break;
}
return { totalDependents: visited.size - 1, levels };
}
export function impactAnalysisData(file, customDbPath, opts = {}) {
const db = openReadonlyOrFail(customDbPath);
try {
const noTests = opts.noTests || false;
const fileNodes = findFileNodes(db, `%${file}%`);
if (fileNodes.length === 0) {
return { file, sources: [], levels: {}, totalDependents: 0 };
}
const visited = new Set();
const queue = [];
const levels = new Map();
for (const fn of fileNodes) {
visited.add(fn.id);
queue.push(fn.id);
levels.set(fn.id, 0);
}
while (queue.length > 0) {
const current = queue.shift();
const level = levels.get(current);
const dependents = findImportDependents(db, current);
for (const dep of dependents) {
if (!visited.has(dep.id) && (!noTests || !isTestFile(dep.file))) {
visited.add(dep.id);
queue.push(dep.id);
levels.set(dep.id, level + 1);
}
}
}
const byLevel = {};
for (const [id, level] of levels) {
if (level === 0) continue;
if (!byLevel[level]) byLevel[level] = [];
const node = findNodeById(db, id);
if (node) byLevel[level].push({ file: node.file });
}
return {
file,
sources: fileNodes.map((f) => f.file),
levels: byLevel,
totalDependents: visited.size - fileNodes.length,
};
} finally {
db.close();
}
}
export function fnImpactData(name, customDbPath, opts = {}) {
const db = openReadonlyOrFail(customDbPath);
try {
const config = opts.config || loadConfig();
const maxDepth = opts.depth || config.analysis?.fnImpactDepth || 5;
const noTests = opts.noTests || false;
const hc = new Map();
const nodes = findMatchingNodes(db, name, { noTests, file: opts.file, kind: opts.kind });
if (nodes.length === 0) {
return { name, results: [] };
}
const includeImplementors = opts.includeImplementors !== false;
const results = nodes.map((node) => {
const { levels, totalDependents } = bfsTransitiveCallers(db, node.id, {
noTests,
maxDepth,
includeImplementors,
});
return {
...normalizeSymbol(node, db, hc),
levels,
totalDependents,
};
});
const base = { name, results };
return paginateResult(base, 'results', { limit: opts.limit, offset: opts.offset });
} finally {
db.close();
}
}
// ─── diffImpactData helpers ─────────────────────────────────────────────
/**
* Walk up from repoRoot until a .git directory is found.
* Returns true if a git root exists, false otherwise.
*
* @param {string} repoRoot
* @returns {boolean}
*/
function findGitRoot(repoRoot) {
let checkDir = repoRoot;
while (checkDir) {
if (fs.existsSync(path.join(checkDir, '.git'))) {
return true;
}
const parent = path.dirname(checkDir);
if (parent === checkDir) break;
checkDir = parent;
}
return false;
}
/**
* Execute git diff and return the raw output string.
* Returns `{ output: string }` on success or `{ error: string }` on failure.
*
* @param {string} repoRoot
* @param {{ staged?: boolean, ref?: string }} opts
* @returns {{ output: string } | { error: string }}
*/
function runGitDiff(repoRoot, opts) {
try {
const args = opts.staged
? ['diff', '--cached', '--unified=0', '--no-color']
: ['diff', opts.ref || 'HEAD', '--unified=0', '--no-color'];
const output = execFileSync('git', args, {
cwd: repoRoot,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024,
stdio: ['pipe', 'pipe', 'pipe'],
});
return { output };
} catch (e) {
return { error: `Failed to run git diff: ${e.message}` };
}
}
/**
* Parse raw git diff output into a changedRanges map and newFiles set.
*
* @param {string} diffOutput
* @returns {{ changedRanges: Map<string, Array<{start: number, end: number}>>, newFiles: Set<string> }}
*/
function parseGitDiff(diffOutput) {
const changedRanges = new Map();
const newFiles = new Set();
let currentFile = null;
let prevIsDevNull = false;
for (const line of diffOutput.split('\n')) {
if (line.startsWith('--- /dev/null')) {
prevIsDevNull = true;
continue;
}
if (line.startsWith('--- ')) {
prevIsDevNull = false;
continue;
}
const fileMatch = line.match(/^\+\+\+ b\/(.+)/);
if (fileMatch) {
currentFile = fileMatch[1];
if (!changedRanges.has(currentFile)) changedRanges.set(currentFile, []);
if (prevIsDevNull) newFiles.add(currentFile);
prevIsDevNull = false;
continue;
}
const hunkMatch = line.match(/^@@ .+ \+(\d+)(?:,(\d+))? @@/);
if (hunkMatch && currentFile) {
const start = parseInt(hunkMatch[1], 10);
const count = parseInt(hunkMatch[2] || '1', 10);
changedRanges.get(currentFile).push({ start, end: start + count - 1 });
}
}
return { changedRanges, newFiles };
}
/**
* Find all function/method/class nodes whose line ranges overlap any changed range.
*
* @param {import('better-sqlite3').Database} db
* @param {Map<string, Array<{start: number, end: number}>} changedRanges
* @param {boolean} noTests
* @returns {Array<object>}
*/
function findAffectedFunctions(db, changedRanges, noTests) {
const affectedFunctions = [];
for (const [file, ranges] of changedRanges) {
if (noTests && isTestFile(file)) continue;
const defs = db
.prepare(
`SELECT * FROM nodes WHERE file = ? AND kind IN ('function', 'method', 'class') ORDER BY line`,
)
.all(file);
for (let i = 0; i < defs.length; i++) {
const def = defs[i];
const endLine = def.end_line || (defs[i + 1] ? defs[i + 1].line - 1 : 999999);
for (const range of ranges) {
if (range.start <= endLine && range.end >= def.line) {
affectedFunctions.push(def);
break;
}
}
}
}
return affectedFunctions;
}
/**
* Run BFS per affected function, collecting per-function results and the full affected set.
*
* @param {import('better-sqlite3').Database} db
* @param {Array<object>} affectedFunctions
* @param {boolean} noTests
* @param {number} maxDepth
* @returns {{ functionResults: Array<object>, allAffected: Set<string> }}
*/
function buildFunctionImpactResults(
db,
affectedFunctions,
noTests,
maxDepth,
includeImplementors = true,
) {
const allAffected = new Set();
const functionResults = affectedFunctions.map((fn) => {
const edges = [];
const idToKey = new Map();
idToKey.set(fn.id, `${fn.file}::${fn.name}:${fn.line}`);
const { levels, totalDependents } = bfsTransitiveCallers(db, fn.id, {
noTests,
maxDepth,
includeImplementors,
onVisit(c, parentId) {
allAffected.add(`${c.file}:${c.name}`);
const callerKey = `${c.file}::${c.name}:${c.line}`;
idToKey.set(c.id, callerKey);
edges.push({ from: idToKey.get(parentId), to: callerKey });
},
});
return {
name: fn.name,
kind: fn.kind,
file: fn.file,
line: fn.line,
transitiveCallers: totalDependents,
levels,
edges,
};
});
return { functionResults, allAffected };
}
/**
* Look up historically co-changed files for the set of changed files.
* Returns an empty array if the co_changes table is unavailable.
*
* @param {import('better-sqlite3').Database} db
* @param {Map<string, any>} changedRanges
* @param {Set<string>} affectedFiles
* @param {boolean} noTests
* @returns {Array<object>}
*/
function lookupCoChanges(db, changedRanges, affectedFiles, noTests) {
try {
db.prepare('SELECT 1 FROM co_changes LIMIT 1').get();
const changedFilesList = [...changedRanges.keys()];
const coResults = coChangeForFiles(changedFilesList, db, {
minJaccard: 0.3,
limit: 20,
noTests,
});
return coResults.filter((r) => !affectedFiles.has(r.file));
} catch (e) {
debug(`co_changes lookup skipped: ${e.message}`);
return [];
}
}
/**
* Look up CODEOWNERS for changed and affected files.
* Returns null if no owners are found or lookup fails.
*
* @param {Map<string, any>} changedRanges
* @param {Set<string>} affectedFiles
* @param {string} repoRoot
* @returns {{ owners: object, affectedOwners: Array<string>, suggestedReviewers: Array<string> } | null}
*/
function lookupOwnership(changedRanges, affectedFiles, repoRoot) {
try {
const allFilePaths = [...new Set([...changedRanges.keys(), ...affectedFiles])];
const ownerResult = ownersForFiles(allFilePaths, repoRoot);
if (ownerResult.affectedOwners.length > 0) {
return {
owners: Object.fromEntries(ownerResult.owners),
affectedOwners: ownerResult.affectedOwners,
suggestedReviewers: ownerResult.suggestedReviewers,
};
}
return null;
} catch (e) {
debug(`CODEOWNERS lookup skipped: ${e.message}`);
return null;
}
}
/**
* Check manifesto boundary violations scoped to the changed files.
* Returns `{ boundaryViolations, boundaryViolationCount }`.
*
* @param {import('better-sqlite3').Database} db
* @param {Map<string, any>} changedRanges
* @param {boolean} noTests
* @param {object} opts — full diffImpactData opts (may contain `opts.config`)
* @param {string} repoRoot
* @returns {{ boundaryViolations: Array<object>, boundaryViolationCount: number }}
*/
function checkBoundaryViolations(db, changedRanges, noTests, opts, repoRoot) {
try {
const cfg = opts.config || loadConfig(repoRoot);
const boundaryConfig = cfg.manifesto?.boundaries;
if (boundaryConfig) {
const result = evaluateBoundaries(db, boundaryConfig, {
scopeFiles: [...changedRanges.keys()],
noTests,
});
return {
boundaryViolations: result.violations,
boundaryViolationCount: result.violationCount,
};
}
} catch (e) {
debug(`boundary check skipped: ${e.message}`);
}
return { boundaryViolations: [], boundaryViolationCount: 0 };
}
// ─── diffImpactData ─────────────────────────────────────────────────────
/**
* Fix #2: Shell injection vulnerability.
* Uses execFileSync instead of execSync to prevent shell interpretation of user input.
*/
export function diffImpactData(customDbPath, opts = {}) {
const db = openReadonlyOrFail(customDbPath);
try {
const noTests = opts.noTests || false;
const config = opts.config || loadConfig();
const maxDepth = opts.depth || config.analysis?.impactDepth || 3;
const dbPath = findDbPath(customDbPath);
const repoRoot = path.resolve(path.dirname(dbPath), '..');
if (!findGitRoot(repoRoot)) {
return { error: `Not a git repository: ${repoRoot}` };
}
const gitResult = runGitDiff(repoRoot, opts);
if (gitResult.error) return { error: gitResult.error };
if (!gitResult.output.trim()) {
return {
changedFiles: 0,
newFiles: [],
affectedFunctions: [],
affectedFiles: [],
summary: null,
};
}
const { changedRanges, newFiles } = parseGitDiff(gitResult.output);
if (changedRanges.size === 0) {
return {
changedFiles: 0,
newFiles: [],
affectedFunctions: [],
affectedFiles: [],
summary: null,
};
}
const affectedFunctions = findAffectedFunctions(db, changedRanges, noTests);
const includeImplementors = opts.includeImplementors !== false;
const { functionResults, allAffected } = buildFunctionImpactResults(
db,
affectedFunctions,
noTests,
maxDepth,
includeImplementors,
);
const affectedFiles = new Set();
for (const key of allAffected) affectedFiles.add(key.split(':')[0]);
const historicallyCoupled = lookupCoChanges(db, changedRanges, affectedFiles, noTests);
const ownership = lookupOwnership(changedRanges, affectedFiles, repoRoot);
const { boundaryViolations, boundaryViolationCount } = checkBoundaryViolations(
db,
changedRanges,
noTests,
opts,
repoRoot,
);
const base = {
changedFiles: changedRanges.size,
newFiles: [...newFiles],
affectedFunctions: functionResults,
affectedFiles: [...affectedFiles],
historicallyCoupled,
ownership,
boundaryViolations,
boundaryViolationCount,
summary: {
functionsChanged: affectedFunctions.length,
callersAffected: allAffected.size,
filesAffected: affectedFiles.size,
historicallyCoupledCount: historicallyCoupled.length,
ownersAffected: ownership ? ownership.affectedOwners.length : 0,
boundaryViolationCount,
},
};
return paginateResult(base, 'affectedFunctions', { limit: opts.limit, offset: opts.offset });
} finally {
db.close();
}
}
export function diffImpactMermaid(customDbPath, opts = {}) {
const data = diffImpactData(customDbPath, opts);
if (data.error) return data.error;
if (data.changedFiles === 0 || data.affectedFunctions.length === 0) {
return 'flowchart TB\n none["No impacted functions detected"]';
}
const newFileSet = new Set(data.newFiles || []);
const lines = ['flowchart TB'];
// Assign stable Mermaid node IDs
let nodeCounter = 0;
const nodeIdMap = new Map();
const nodeLabels = new Map();
function nodeId(key, label) {
if (!nodeIdMap.has(key)) {
nodeIdMap.set(key, `n${nodeCounter++}`);
if (label) nodeLabels.set(key, label);
}
return nodeIdMap.get(key);
}
// Register all nodes (changed functions + their callers)
for (const fn of data.affectedFunctions) {
nodeId(`${fn.file}::${fn.name}:${fn.line}`, fn.name);
for (const callers of Object.values(fn.levels || {})) {
for (const c of callers) {
nodeId(`${c.file}::${c.name}:${c.line}`, c.name);
}
}
}
// Collect all edges and determine blast radius
const allEdges = new Set();
const edgeFromNodes = new Set();
const edgeToNodes = new Set();
const changedKeys = new Set();
for (const fn of data.affectedFunctions) {
changedKeys.add(`${fn.file}::${fn.name}:${fn.line}`);
for (const edge of fn.edges || []) {
const edgeKey = `${edge.from}|${edge.to}`;
if (!allEdges.has(edgeKey)) {
allEdges.add(edgeKey);
edgeFromNodes.add(edge.from);
edgeToNodes.add(edge.to);
}
}
}
// Blast radius: caller nodes that are never a source (leaf nodes of the impact tree)
const blastRadiusKeys = new Set();
for (const key of edgeToNodes) {
if (!edgeFromNodes.has(key) && !changedKeys.has(key)) {
blastRadiusKeys.add(key);
}
}
// Intermediate callers: not changed, not blast radius
const intermediateKeys = new Set();
for (const key of edgeToNodes) {
if (!changedKeys.has(key) && !blastRadiusKeys.has(key)) {
intermediateKeys.add(key);
}
}
// Group changed functions by file
const fileGroups = new Map();
for (const fn of data.affectedFunctions) {
if (!fileGroups.has(fn.file)) fileGroups.set(fn.file, []);
fileGroups.get(fn.file).push(fn);
}
// Emit changed-file subgraphs
let sgCounter = 0;
for (const [file, fns] of fileGroups) {
const isNew = newFileSet.has(file);
const tag = isNew ? 'new' : 'modified';
const sgId = `sg${sgCounter++}`;
lines.push(` subgraph ${sgId}["${file} **(${tag})**"]`);
for (const fn of fns) {
const key = `${fn.file}::${fn.name}:${fn.line}`;
lines.push(` ${nodeIdMap.get(key)}["${fn.name}"]`);
}
lines.push(' end');
const style = isNew ? 'fill:#e8f5e9,stroke:#4caf50' : 'fill:#fff3e0,stroke:#ff9800';
lines.push(` style ${sgId} ${style}`);
}
// Emit intermediate caller nodes (outside subgraphs)
for (const key of intermediateKeys) {
lines.push(` ${nodeIdMap.get(key)}["${nodeLabels.get(key)}"]`);
}
// Emit blast radius subgraph
if (blastRadiusKeys.size > 0) {
const sgId = `sg${sgCounter++}`;
lines.push(` subgraph ${sgId}["Callers **(blast radius)**"]`);
for (const key of blastRadiusKeys) {
lines.push(` ${nodeIdMap.get(key)}["${nodeLabels.get(key)}"]`);
}
lines.push(' end');
lines.push(` style ${sgId} fill:#f3e5f5,stroke:#9c27b0`);
}
// Emit edges (impact flows from changed fn toward callers)
for (const edgeKey of allEdges) {
const [from, to] = edgeKey.split('|');
lines.push(` ${nodeIdMap.get(from)} --> ${nodeIdMap.get(to)}`);
}
return lines.join('\n');
}