@eduardbar/drift 0.9.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish-vscode.yml +76 -0
- package/AGENTS.md +30 -12
- package/CHANGELOG.md +9 -0
- package/README.md +273 -168
- package/ROADMAP.md +130 -98
- package/dist/analyzer.d.ts +4 -38
- package/dist/analyzer.js +85 -1510
- package/dist/cli.js +47 -4
- package/dist/config.js +1 -1
- package/dist/fix.d.ts +13 -0
- package/dist/fix.js +120 -0
- package/dist/git/blame.d.ts +22 -0
- package/dist/git/blame.js +227 -0
- package/dist/git/helpers.d.ts +36 -0
- package/dist/git/helpers.js +152 -0
- package/dist/git/trend.d.ts +21 -0
- package/dist/git/trend.js +80 -0
- package/dist/git.d.ts +0 -4
- package/dist/git.js +2 -2
- package/dist/report.js +620 -293
- package/dist/rules/phase0-basic.d.ts +11 -0
- package/dist/rules/phase0-basic.js +176 -0
- package/dist/rules/phase1-complexity.d.ts +31 -0
- package/dist/rules/phase1-complexity.js +277 -0
- package/dist/rules/phase2-crossfile.d.ts +27 -0
- package/dist/rules/phase2-crossfile.js +122 -0
- package/dist/rules/phase3-arch.d.ts +31 -0
- package/dist/rules/phase3-arch.js +148 -0
- package/dist/rules/phase5-ai.d.ts +8 -0
- package/dist/rules/phase5-ai.js +262 -0
- package/dist/rules/phase8-semantic.d.ts +22 -0
- package/dist/rules/phase8-semantic.js +109 -0
- package/dist/rules/shared.d.ts +7 -0
- package/dist/rules/shared.js +27 -0
- package/package.json +8 -3
- package/packages/vscode-drift/.vscodeignore +9 -0
- package/packages/vscode-drift/LICENSE +21 -0
- package/packages/vscode-drift/README.md +64 -0
- package/packages/vscode-drift/images/icon.png +0 -0
- package/packages/vscode-drift/images/icon.svg +30 -0
- package/packages/vscode-drift/package-lock.json +485 -0
- package/packages/vscode-drift/package.json +119 -0
- package/packages/vscode-drift/src/analyzer.ts +38 -0
- package/packages/vscode-drift/src/diagnostics.ts +55 -0
- package/packages/vscode-drift/src/extension.ts +111 -0
- package/packages/vscode-drift/src/statusbar.ts +47 -0
- package/packages/vscode-drift/src/treeview.ts +108 -0
- package/packages/vscode-drift/tsconfig.json +18 -0
- package/packages/vscode-drift/vscode-drift-0.1.0.vsix +0 -0
- package/packages/vscode-drift/vscode-drift-0.1.1.vsix +0 -0
- package/src/analyzer.ts +124 -1726
- package/src/cli.ts +53 -4
- package/src/config.ts +1 -1
- package/src/fix.ts +154 -0
- package/src/git/blame.ts +279 -0
- package/src/git/helpers.ts +198 -0
- package/src/git/trend.ts +116 -0
- package/src/git.ts +2 -2
- package/src/report.ts +631 -296
- package/src/rules/phase0-basic.ts +187 -0
- package/src/rules/phase1-complexity.ts +302 -0
- package/src/rules/phase2-crossfile.ts +149 -0
- package/src/rules/phase3-arch.ts +179 -0
- package/src/rules/phase5-ai.ts +292 -0
- package/src/rules/phase8-semantic.ts +132 -0
- package/src/rules/shared.ts +39 -0
- package/tests/helpers.ts +45 -0
- package/tests/rules.test.ts +1269 -0
- package/vitest.config.ts +15 -0
package/dist/analyzer.js
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
import * as crypto from 'node:crypto';
|
|
1
|
+
// drift-ignore-file
|
|
3
2
|
import * as path from 'node:path';
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
3
|
+
import { Project } from 'ts-morph';
|
|
4
|
+
// Rules
|
|
5
|
+
import { isFileIgnored } from './rules/shared.js';
|
|
6
|
+
import { detectLargeFile, detectLargeFunctions, detectDebugLeftovers, detectDeadCode, detectDuplicateFunctionNames, detectAnyAbuse, detectCatchSwallow, detectMissingReturnTypes, } from './rules/phase0-basic.js';
|
|
7
|
+
import { detectHighComplexity, detectDeepNesting, detectTooManyParams, detectHighCoupling, detectPromiseStyleMix, detectMagicNumbers, detectCommentContradiction, } from './rules/phase1-complexity.js';
|
|
8
|
+
import { detectDeadFiles, detectUnusedExports, detectUnusedDependencies, } from './rules/phase2-crossfile.js';
|
|
9
|
+
import { detectCircularDependencies, detectLayerViolations, detectCrossBoundaryImports, } from './rules/phase3-arch.js';
|
|
10
|
+
import { detectOverCommented, detectHardcodedConfig, detectInconsistentErrorHandling, detectUnnecessaryAbstraction, detectNamingInconsistency, } from './rules/phase5-ai.js';
|
|
11
|
+
import { collectFunctions, fingerprintFunction, calculateScore, } from './rules/phase8-semantic.js';
|
|
12
|
+
// Git analyzers (re-exported as part of the public API)
|
|
13
|
+
export { TrendAnalyzer } from './git/trend.js';
|
|
14
|
+
export { BlameAnalyzer } from './git/blame.js';
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// Rule weights — single source of truth for severities and drift score weights
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
9
18
|
export const RULE_WEIGHTS = {
|
|
10
19
|
'large-file': { severity: 'error', weight: 20 },
|
|
11
20
|
'large-function': { severity: 'error', weight: 15 },
|
|
@@ -41,858 +50,8 @@ export const RULE_WEIGHTS = {
|
|
|
41
50
|
// Phase 8: semantic duplication
|
|
42
51
|
'semantic-duplication': { severity: 'warning', weight: 12 },
|
|
43
52
|
};
|
|
44
|
-
function hasIgnoreComment(file, line) {
|
|
45
|
-
const lines = file.getFullText().split('\n');
|
|
46
|
-
const currentLine = lines[line - 1] ?? '';
|
|
47
|
-
const prevLine = lines[line - 2] ?? '';
|
|
48
|
-
if (/\/\/\s*drift-ignore\b/.test(currentLine))
|
|
49
|
-
return true;
|
|
50
|
-
if (/\/\/\s*drift-ignore\b/.test(prevLine))
|
|
51
|
-
return true;
|
|
52
|
-
return false;
|
|
53
|
-
}
|
|
54
|
-
function isFileIgnored(file) {
|
|
55
|
-
const firstLines = file.getFullText().split('\n').slice(0, 10).join('\n');
|
|
56
|
-
return /\/\/\s*drift-ignore-file\b/.test(firstLines);
|
|
57
|
-
}
|
|
58
|
-
function getSnippet(node, file) {
|
|
59
|
-
const startLine = node.getStartLineNumber();
|
|
60
|
-
const lines = file.getFullText().split('\n');
|
|
61
|
-
return lines
|
|
62
|
-
.slice(Math.max(0, startLine - 1), startLine + 1)
|
|
63
|
-
.join('\n')
|
|
64
|
-
.trim()
|
|
65
|
-
.slice(0, 120);
|
|
66
|
-
}
|
|
67
|
-
function getFunctionLikeLines(node) {
|
|
68
|
-
return node.getEndLineNumber() - node.getStartLineNumber();
|
|
69
|
-
}
|
|
70
|
-
// ---------------------------------------------------------------------------
|
|
71
|
-
// Existing rules
|
|
72
|
-
// ---------------------------------------------------------------------------
|
|
73
|
-
function detectLargeFile(file) {
|
|
74
|
-
const lineCount = file.getEndLineNumber();
|
|
75
|
-
if (lineCount > 300) {
|
|
76
|
-
return [
|
|
77
|
-
{
|
|
78
|
-
rule: 'large-file',
|
|
79
|
-
severity: 'error',
|
|
80
|
-
message: `File has ${lineCount} lines (threshold: 300). Large files are the #1 sign of AI-generated structural drift.`,
|
|
81
|
-
line: 1,
|
|
82
|
-
column: 1,
|
|
83
|
-
snippet: `// ${lineCount} lines total`,
|
|
84
|
-
},
|
|
85
|
-
];
|
|
86
|
-
}
|
|
87
|
-
return [];
|
|
88
|
-
}
|
|
89
|
-
function detectLargeFunctions(file) {
|
|
90
|
-
const issues = [];
|
|
91
|
-
const fns = [
|
|
92
|
-
...file.getFunctions(),
|
|
93
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
94
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
95
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
96
|
-
];
|
|
97
|
-
for (const fn of fns) {
|
|
98
|
-
const lines = getFunctionLikeLines(fn);
|
|
99
|
-
const startLine = fn.getStartLineNumber();
|
|
100
|
-
if (lines > 50) {
|
|
101
|
-
if (hasIgnoreComment(file, startLine))
|
|
102
|
-
continue;
|
|
103
|
-
issues.push({
|
|
104
|
-
rule: 'large-function',
|
|
105
|
-
severity: 'error',
|
|
106
|
-
message: `Function spans ${lines} lines (threshold: 50). AI tends to dump logic into single functions.`,
|
|
107
|
-
line: startLine,
|
|
108
|
-
column: fn.getStartLinePos(),
|
|
109
|
-
snippet: getSnippet(fn, file),
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
return issues;
|
|
114
|
-
}
|
|
115
|
-
function detectDebugLeftovers(file) {
|
|
116
|
-
const issues = [];
|
|
117
|
-
for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
118
|
-
const expr = call.getExpression().getText();
|
|
119
|
-
const line = call.getStartLineNumber();
|
|
120
|
-
if (/^console\.(log|warn|error|debug|info)\b/.test(expr)) {
|
|
121
|
-
if (hasIgnoreComment(file, line))
|
|
122
|
-
continue;
|
|
123
|
-
issues.push({
|
|
124
|
-
rule: 'debug-leftover',
|
|
125
|
-
severity: 'warning',
|
|
126
|
-
message: `console.${expr.split('.')[1]} left in production code.`,
|
|
127
|
-
line,
|
|
128
|
-
column: call.getStartLinePos(),
|
|
129
|
-
snippet: getSnippet(call, file),
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
const lines = file.getFullText().split('\n');
|
|
134
|
-
lines.forEach((lineContent, i) => {
|
|
135
|
-
if (/\/\/\s*(TODO|FIXME|HACK|XXX|TEMP)\b/i.test(lineContent)) {
|
|
136
|
-
if (hasIgnoreComment(file, i + 1))
|
|
137
|
-
return;
|
|
138
|
-
issues.push({
|
|
139
|
-
rule: 'debug-leftover',
|
|
140
|
-
severity: 'warning',
|
|
141
|
-
message: `Unresolved marker found: ${lineContent.trim().slice(0, 60)}`,
|
|
142
|
-
line: i + 1,
|
|
143
|
-
column: 1,
|
|
144
|
-
snippet: lineContent.trim().slice(0, 120),
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
});
|
|
148
|
-
return issues;
|
|
149
|
-
}
|
|
150
|
-
function detectDeadCode(file) {
|
|
151
|
-
const issues = [];
|
|
152
|
-
for (const imp of file.getImportDeclarations()) {
|
|
153
|
-
for (const named of imp.getNamedImports()) {
|
|
154
|
-
const name = named.getName();
|
|
155
|
-
const refs = file.getDescendantsOfKind(SyntaxKind.Identifier).filter((id) => id.getText() === name && id !== named.getNameNode());
|
|
156
|
-
if (refs.length === 0) {
|
|
157
|
-
issues.push({
|
|
158
|
-
rule: 'dead-code',
|
|
159
|
-
severity: 'warning',
|
|
160
|
-
message: `Unused import '${name}'. AI often imports more than it uses.`,
|
|
161
|
-
line: imp.getStartLineNumber(),
|
|
162
|
-
column: imp.getStartLinePos(),
|
|
163
|
-
snippet: getSnippet(imp, file),
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return issues;
|
|
169
|
-
}
|
|
170
|
-
function detectDuplicateFunctionNames(file) {
|
|
171
|
-
const issues = [];
|
|
172
|
-
const seen = new Map();
|
|
173
|
-
const fns = file.getFunctions();
|
|
174
|
-
for (const fn of fns) {
|
|
175
|
-
const name = fn.getName();
|
|
176
|
-
if (!name)
|
|
177
|
-
continue;
|
|
178
|
-
const normalized = name.toLowerCase().replace(/[_-]/g, '');
|
|
179
|
-
if (seen.has(normalized)) {
|
|
180
|
-
issues.push({
|
|
181
|
-
rule: 'duplicate-function-name',
|
|
182
|
-
severity: 'error',
|
|
183
|
-
message: `Function '${name}' looks like a duplicate of a previously defined function. AI often generates near-identical helpers.`,
|
|
184
|
-
line: fn.getStartLineNumber(),
|
|
185
|
-
column: fn.getStartLinePos(),
|
|
186
|
-
snippet: getSnippet(fn, file),
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
else {
|
|
190
|
-
seen.set(normalized, fn.getStartLineNumber());
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
return issues;
|
|
194
|
-
}
|
|
195
|
-
function detectAnyAbuse(file) {
|
|
196
|
-
const issues = [];
|
|
197
|
-
for (const node of file.getDescendantsOfKind(SyntaxKind.AnyKeyword)) {
|
|
198
|
-
issues.push({
|
|
199
|
-
rule: 'any-abuse',
|
|
200
|
-
severity: 'warning',
|
|
201
|
-
message: `Explicit 'any' type detected. AI defaults to 'any' when it can't infer types properly.`,
|
|
202
|
-
line: node.getStartLineNumber(),
|
|
203
|
-
column: node.getStartLinePos(),
|
|
204
|
-
snippet: getSnippet(node, file),
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
return issues;
|
|
208
|
-
}
|
|
209
|
-
function detectCatchSwallow(file) {
|
|
210
|
-
const issues = [];
|
|
211
|
-
for (const tryCatch of file.getDescendantsOfKind(SyntaxKind.TryStatement)) {
|
|
212
|
-
const catchClause = tryCatch.getCatchClause();
|
|
213
|
-
if (!catchClause)
|
|
214
|
-
continue;
|
|
215
|
-
const block = catchClause.getBlock();
|
|
216
|
-
const stmts = block.getStatements();
|
|
217
|
-
if (stmts.length === 0) {
|
|
218
|
-
issues.push({
|
|
219
|
-
rule: 'catch-swallow',
|
|
220
|
-
severity: 'warning',
|
|
221
|
-
message: `Empty catch block silently swallows errors. Classic AI pattern to make code "not throw".`,
|
|
222
|
-
line: catchClause.getStartLineNumber(),
|
|
223
|
-
column: catchClause.getStartLinePos(),
|
|
224
|
-
snippet: getSnippet(catchClause, file),
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
return issues;
|
|
229
|
-
}
|
|
230
|
-
function detectMissingReturnTypes(file) {
|
|
231
|
-
const issues = [];
|
|
232
|
-
for (const fn of file.getFunctions()) {
|
|
233
|
-
if (!fn.getReturnTypeNode()) {
|
|
234
|
-
issues.push({
|
|
235
|
-
rule: 'no-return-type',
|
|
236
|
-
severity: 'info',
|
|
237
|
-
message: `Function '${fn.getName() ?? 'anonymous'}' has no explicit return type.`,
|
|
238
|
-
line: fn.getStartLineNumber(),
|
|
239
|
-
column: fn.getStartLinePos(),
|
|
240
|
-
snippet: getSnippet(fn, file),
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
return issues;
|
|
245
|
-
}
|
|
246
|
-
// ---------------------------------------------------------------------------
|
|
247
|
-
// Phase 1: complexity detection rules
|
|
248
|
-
// ---------------------------------------------------------------------------
|
|
249
|
-
/**
|
|
250
|
-
* Cyclomatic complexity: count decision points in a function.
|
|
251
|
-
* Each if/else if/ternary/?:/for/while/do/case/catch/&&/|| adds 1.
|
|
252
|
-
* Threshold: > 10 is considered high complexity.
|
|
253
|
-
*/
|
|
254
|
-
function getCyclomaticComplexity(fn) {
|
|
255
|
-
let complexity = 1; // base path
|
|
256
|
-
const incrementKinds = [
|
|
257
|
-
SyntaxKind.IfStatement,
|
|
258
|
-
SyntaxKind.ForStatement,
|
|
259
|
-
SyntaxKind.ForInStatement,
|
|
260
|
-
SyntaxKind.ForOfStatement,
|
|
261
|
-
SyntaxKind.WhileStatement,
|
|
262
|
-
SyntaxKind.DoStatement,
|
|
263
|
-
SyntaxKind.CaseClause,
|
|
264
|
-
SyntaxKind.CatchClause,
|
|
265
|
-
SyntaxKind.ConditionalExpression, // ternary
|
|
266
|
-
SyntaxKind.AmpersandAmpersandToken,
|
|
267
|
-
SyntaxKind.BarBarToken,
|
|
268
|
-
SyntaxKind.QuestionQuestionToken, // ??
|
|
269
|
-
];
|
|
270
|
-
for (const kind of incrementKinds) {
|
|
271
|
-
complexity += fn.getDescendantsOfKind(kind).length;
|
|
272
|
-
}
|
|
273
|
-
return complexity;
|
|
274
|
-
}
|
|
275
|
-
function detectHighComplexity(file) {
|
|
276
|
-
const issues = [];
|
|
277
|
-
const fns = [
|
|
278
|
-
...file.getFunctions(),
|
|
279
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
280
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
281
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
282
|
-
];
|
|
283
|
-
for (const fn of fns) {
|
|
284
|
-
const complexity = getCyclomaticComplexity(fn);
|
|
285
|
-
if (complexity > 10) {
|
|
286
|
-
const startLine = fn.getStartLineNumber();
|
|
287
|
-
if (hasIgnoreComment(file, startLine))
|
|
288
|
-
continue;
|
|
289
|
-
issues.push({
|
|
290
|
-
rule: 'high-complexity',
|
|
291
|
-
severity: 'error',
|
|
292
|
-
message: `Cyclomatic complexity is ${complexity} (threshold: 10). AI generates correct code, not simple code.`,
|
|
293
|
-
line: startLine,
|
|
294
|
-
column: fn.getStartLinePos(),
|
|
295
|
-
snippet: getSnippet(fn, file),
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
return issues;
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Deep nesting: count the maximum nesting depth of control flow inside a function.
|
|
303
|
-
* Counts: if, for, while, do, try, switch.
|
|
304
|
-
* Threshold: > 3 levels.
|
|
305
|
-
*/
|
|
306
|
-
function getMaxNestingDepth(fn) {
|
|
307
|
-
const nestingKinds = new Set([
|
|
308
|
-
SyntaxKind.IfStatement,
|
|
309
|
-
SyntaxKind.ForStatement,
|
|
310
|
-
SyntaxKind.ForInStatement,
|
|
311
|
-
SyntaxKind.ForOfStatement,
|
|
312
|
-
SyntaxKind.WhileStatement,
|
|
313
|
-
SyntaxKind.DoStatement,
|
|
314
|
-
SyntaxKind.TryStatement,
|
|
315
|
-
SyntaxKind.SwitchStatement,
|
|
316
|
-
]);
|
|
317
|
-
let maxDepth = 0;
|
|
318
|
-
function walk(node, depth) {
|
|
319
|
-
if (nestingKinds.has(node.getKind())) {
|
|
320
|
-
depth++;
|
|
321
|
-
if (depth > maxDepth)
|
|
322
|
-
maxDepth = depth;
|
|
323
|
-
}
|
|
324
|
-
for (const child of node.getChildren()) {
|
|
325
|
-
walk(child, depth);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
walk(fn, 0);
|
|
329
|
-
return maxDepth;
|
|
330
|
-
}
|
|
331
|
-
function detectDeepNesting(file) {
|
|
332
|
-
const issues = [];
|
|
333
|
-
const fns = [
|
|
334
|
-
...file.getFunctions(),
|
|
335
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
336
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
337
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
338
|
-
];
|
|
339
|
-
for (const fn of fns) {
|
|
340
|
-
const depth = getMaxNestingDepth(fn);
|
|
341
|
-
if (depth > 3) {
|
|
342
|
-
const startLine = fn.getStartLineNumber();
|
|
343
|
-
if (hasIgnoreComment(file, startLine))
|
|
344
|
-
continue;
|
|
345
|
-
issues.push({
|
|
346
|
-
rule: 'deep-nesting',
|
|
347
|
-
severity: 'warning',
|
|
348
|
-
message: `Maximum nesting depth is ${depth} (threshold: 3). Deep nesting is the #1 readability killer.`,
|
|
349
|
-
line: startLine,
|
|
350
|
-
column: fn.getStartLinePos(),
|
|
351
|
-
snippet: getSnippet(fn, file),
|
|
352
|
-
});
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
return issues;
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* Too many parameters: functions with more than 4 parameters.
|
|
359
|
-
* AI avoids refactoring parameters into objects/options bags.
|
|
360
|
-
*/
|
|
361
|
-
function detectTooManyParams(file) {
|
|
362
|
-
const issues = [];
|
|
363
|
-
const fns = [
|
|
364
|
-
...file.getFunctions(),
|
|
365
|
-
...file.getDescendantsOfKind(SyntaxKind.ArrowFunction),
|
|
366
|
-
...file.getDescendantsOfKind(SyntaxKind.FunctionExpression),
|
|
367
|
-
...file.getClasses().flatMap((c) => c.getMethods()),
|
|
368
|
-
];
|
|
369
|
-
for (const fn of fns) {
|
|
370
|
-
const paramCount = fn.getParameters().length;
|
|
371
|
-
if (paramCount > 4) {
|
|
372
|
-
const startLine = fn.getStartLineNumber();
|
|
373
|
-
if (hasIgnoreComment(file, startLine))
|
|
374
|
-
continue;
|
|
375
|
-
issues.push({
|
|
376
|
-
rule: 'too-many-params',
|
|
377
|
-
severity: 'warning',
|
|
378
|
-
message: `Function has ${paramCount} parameters (threshold: 4). AI avoids refactoring into options objects.`,
|
|
379
|
-
line: startLine,
|
|
380
|
-
column: fn.getStartLinePos(),
|
|
381
|
-
snippet: getSnippet(fn, file),
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
return issues;
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* High coupling: files with more than 10 distinct import sources.
|
|
389
|
-
* AI imports broadly without considering module cohesion.
|
|
390
|
-
*/
|
|
391
|
-
function detectHighCoupling(file) {
|
|
392
|
-
const imports = file.getImportDeclarations();
|
|
393
|
-
const sources = new Set(imports.map((i) => i.getModuleSpecifierValue()));
|
|
394
|
-
if (sources.size > 10) {
|
|
395
|
-
return [
|
|
396
|
-
{
|
|
397
|
-
rule: 'high-coupling',
|
|
398
|
-
severity: 'warning',
|
|
399
|
-
message: `File imports from ${sources.size} distinct modules (threshold: 10). High coupling makes refactoring dangerous.`,
|
|
400
|
-
line: 1,
|
|
401
|
-
column: 1,
|
|
402
|
-
snippet: `// ${sources.size} import sources`,
|
|
403
|
-
},
|
|
404
|
-
];
|
|
405
|
-
}
|
|
406
|
-
return [];
|
|
407
|
-
}
|
|
408
|
-
/**
|
|
409
|
-
* Promise style mix: async/await and .then()/.catch() used in the same file.
|
|
410
|
-
* AI generates both styles without consistency.
|
|
411
|
-
*/
|
|
412
|
-
function detectPromiseStyleMix(file) {
|
|
413
|
-
const text = file.getFullText();
|
|
414
|
-
// detect .then( or .catch( calls (property access on a promise)
|
|
415
|
-
const hasThen = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression).some((node) => {
|
|
416
|
-
const name = node.getName();
|
|
417
|
-
return name === 'then' || name === 'catch';
|
|
418
|
-
});
|
|
419
|
-
// detect async keyword usage
|
|
420
|
-
const hasAsync = file.getDescendantsOfKind(SyntaxKind.AsyncKeyword).length > 0 ||
|
|
421
|
-
/\bawait\b/.test(text);
|
|
422
|
-
if (hasThen && hasAsync) {
|
|
423
|
-
return [
|
|
424
|
-
{
|
|
425
|
-
rule: 'promise-style-mix',
|
|
426
|
-
severity: 'warning',
|
|
427
|
-
message: `File mixes async/await with .then()/.catch(). AI generates both styles without picking one.`,
|
|
428
|
-
line: 1,
|
|
429
|
-
column: 1,
|
|
430
|
-
snippet: `// mixed promise styles detected`,
|
|
431
|
-
},
|
|
432
|
-
];
|
|
433
|
-
}
|
|
434
|
-
return [];
|
|
435
|
-
}
|
|
436
|
-
/**
|
|
437
|
-
* Magic numbers: numeric literals used directly in logic outside of named constants.
|
|
438
|
-
* Excludes 0, 1, -1 (universally understood) and array indices in obvious patterns.
|
|
439
|
-
*/
|
|
440
|
-
function detectMagicNumbers(file) {
|
|
441
|
-
const issues = [];
|
|
442
|
-
const ALLOWED = new Set([0, 1, -1, 2, 100]);
|
|
443
|
-
for (const node of file.getDescendantsOfKind(SyntaxKind.NumericLiteral)) {
|
|
444
|
-
const value = Number(node.getLiteralValue());
|
|
445
|
-
if (ALLOWED.has(value))
|
|
446
|
-
continue;
|
|
447
|
-
// Skip: variable/const initializers at top level (those ARE the named constants)
|
|
448
|
-
const parent = node.getParent();
|
|
449
|
-
if (!parent)
|
|
450
|
-
continue;
|
|
451
|
-
const parentKind = parent.getKind();
|
|
452
|
-
if (parentKind === SyntaxKind.VariableDeclaration ||
|
|
453
|
-
parentKind === SyntaxKind.PropertyAssignment ||
|
|
454
|
-
parentKind === SyntaxKind.EnumMember ||
|
|
455
|
-
parentKind === SyntaxKind.Parameter)
|
|
456
|
-
continue;
|
|
457
|
-
const line = node.getStartLineNumber();
|
|
458
|
-
if (hasIgnoreComment(file, line))
|
|
459
|
-
continue;
|
|
460
|
-
issues.push({
|
|
461
|
-
rule: 'magic-number',
|
|
462
|
-
severity: 'info',
|
|
463
|
-
message: `Magic number ${value} used directly in logic. Extract to a named constant.`,
|
|
464
|
-
line,
|
|
465
|
-
column: node.getStartLinePos(),
|
|
466
|
-
snippet: getSnippet(node, file),
|
|
467
|
-
});
|
|
468
|
-
}
|
|
469
|
-
return issues;
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* Comment contradiction: comments that restate exactly what the code does.
|
|
473
|
-
* Classic AI pattern — documents the obvious instead of the why.
|
|
474
|
-
* Detects: "// increment counter" above counter++, "// return x" above return x, etc.
|
|
475
|
-
*/
|
|
476
|
-
function detectCommentContradiction(file) {
|
|
477
|
-
const issues = [];
|
|
478
|
-
const lines = file.getFullText().split('\n');
|
|
479
|
-
// Patterns: comment that is a near-literal restatement of the next line
|
|
480
|
-
const trivialCommentPatterns = [
|
|
481
|
-
// "// return ..." above a return statement
|
|
482
|
-
{ comment: /\/\/\s*return\b/i, code: /^\s*return\b/ },
|
|
483
|
-
// "// increment ..." or "// increase ..." above x++ or x += 1
|
|
484
|
-
{ comment: /\/\/\s*(increment|increase|add\s+1|plus\s+1)\b/i, code: /\+\+|(\+= ?1)\b/ },
|
|
485
|
-
// "// decrement ..." above x-- or x -= 1
|
|
486
|
-
{ comment: /\/\/\s*(decrement|decrease|subtract\s+1|minus\s+1)\b/i, code: /--|(-= ?1)\b/ },
|
|
487
|
-
// "// log ..." above console.log
|
|
488
|
-
{ comment: /\/\/\s*log\b/i, code: /console\.(log|warn|error)/ },
|
|
489
|
-
// "// set ... to ..." or "// assign ..." above assignment
|
|
490
|
-
{ comment: /\/\/\s*(set|assign)\b/i, code: /^\s*\w[\w.[\]]*\s*=(?!=)/ },
|
|
491
|
-
// "// call ..." above a function call
|
|
492
|
-
{ comment: /\/\/\s*call\b/i, code: /^\s*\w[\w.]*\(/ },
|
|
493
|
-
// "// declare ..." or "// define ..." or "// create ..." above const/let/var
|
|
494
|
-
{ comment: /\/\/\s*(declare|define|create|initialize)\b/i, code: /^\s*(const|let|var)\b/ },
|
|
495
|
-
// "// check if ..." above an if statement
|
|
496
|
-
{ comment: /\/\/\s*check\s+if\b/i, code: /^\s*if\s*\(/ },
|
|
497
|
-
// "// loop ..." or "// iterate ..." above for/while
|
|
498
|
-
{ comment: /\/\/\s*(loop|iterate|for each|foreach)\b/i, code: /^\s*(for|while)\b/ },
|
|
499
|
-
// "// import ..." above an import
|
|
500
|
-
{ comment: /\/\/\s*import\b/i, code: /^\s*import\b/ },
|
|
501
|
-
];
|
|
502
|
-
for (let i = 0; i < lines.length - 1; i++) {
|
|
503
|
-
const commentLine = lines[i].trim();
|
|
504
|
-
const nextLine = lines[i + 1];
|
|
505
|
-
for (const { comment, code } of trivialCommentPatterns) {
|
|
506
|
-
if (comment.test(commentLine) && code.test(nextLine)) {
|
|
507
|
-
if (hasIgnoreComment(file, i + 1))
|
|
508
|
-
continue;
|
|
509
|
-
issues.push({
|
|
510
|
-
rule: 'comment-contradiction',
|
|
511
|
-
severity: 'warning',
|
|
512
|
-
message: `Comment restates what the code already says. AI documents the obvious instead of the why.`,
|
|
513
|
-
line: i + 1,
|
|
514
|
-
column: 1,
|
|
515
|
-
snippet: `${commentLine.slice(0, 60)}\n${nextLine.trim().slice(0, 60)}`,
|
|
516
|
-
});
|
|
517
|
-
break; // one issue per comment line max
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
return issues;
|
|
522
|
-
}
|
|
523
53
|
// ---------------------------------------------------------------------------
|
|
524
|
-
//
|
|
525
|
-
// ---------------------------------------------------------------------------
|
|
526
|
-
function detectOverCommented(file) {
|
|
527
|
-
const issues = [];
|
|
528
|
-
for (const fn of file.getFunctions()) {
|
|
529
|
-
const body = fn.getBody();
|
|
530
|
-
if (!body)
|
|
531
|
-
continue;
|
|
532
|
-
const bodyText = body.getText();
|
|
533
|
-
const lines = bodyText.split('\n');
|
|
534
|
-
const totalLines = lines.length;
|
|
535
|
-
if (totalLines < 6)
|
|
536
|
-
continue;
|
|
537
|
-
let commentLines = 0;
|
|
538
|
-
for (const line of lines) {
|
|
539
|
-
const trimmed = line.trim();
|
|
540
|
-
if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*') || trimmed.startsWith('*/')) {
|
|
541
|
-
commentLines++;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
const ratio = commentLines / totalLines;
|
|
545
|
-
if (ratio >= 0.4) {
|
|
546
|
-
issues.push({
|
|
547
|
-
rule: 'over-commented',
|
|
548
|
-
severity: 'info',
|
|
549
|
-
message: `Function has ${Math.round(ratio * 100)}% comment density (${commentLines}/${totalLines} lines). AI documents the obvious instead of the why.`,
|
|
550
|
-
line: fn.getStartLineNumber(),
|
|
551
|
-
column: fn.getStartLinePos(),
|
|
552
|
-
snippet: fn.getName() ? `function ${fn.getName()}` : '(anonymous function)',
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
for (const cls of file.getClasses()) {
|
|
557
|
-
for (const method of cls.getMethods()) {
|
|
558
|
-
const body = method.getBody();
|
|
559
|
-
if (!body)
|
|
560
|
-
continue;
|
|
561
|
-
const bodyText = body.getText();
|
|
562
|
-
const lines = bodyText.split('\n');
|
|
563
|
-
const totalLines = lines.length;
|
|
564
|
-
if (totalLines < 6)
|
|
565
|
-
continue;
|
|
566
|
-
let commentLines = 0;
|
|
567
|
-
for (const line of lines) {
|
|
568
|
-
const trimmed = line.trim();
|
|
569
|
-
if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*') || trimmed.startsWith('*/')) {
|
|
570
|
-
commentLines++;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
const ratio = commentLines / totalLines;
|
|
574
|
-
if (ratio >= 0.4) {
|
|
575
|
-
issues.push({
|
|
576
|
-
rule: 'over-commented',
|
|
577
|
-
severity: 'info',
|
|
578
|
-
message: `Method '${method.getName()}' has ${Math.round(ratio * 100)}% comment density (${commentLines}/${totalLines} lines). AI documents the obvious instead of the why.`,
|
|
579
|
-
line: method.getStartLineNumber(),
|
|
580
|
-
column: method.getStartLinePos(),
|
|
581
|
-
snippet: `${cls.getName()}.${method.getName()}`,
|
|
582
|
-
});
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
return issues;
|
|
587
|
-
}
|
|
588
|
-
function detectHardcodedConfig(file) {
|
|
589
|
-
const issues = [];
|
|
590
|
-
const CONFIG_PATTERNS = [
|
|
591
|
-
{ pattern: /^https?:\/\//i, label: 'HTTP/HTTPS URL' },
|
|
592
|
-
{ pattern: /^wss?:\/\//i, label: 'WebSocket URL' },
|
|
593
|
-
{ pattern: /^mongodb(\+srv)?:\/\//i, label: 'MongoDB connection string' },
|
|
594
|
-
{ pattern: /^postgres(?:ql)?:\/\//i, label: 'PostgreSQL connection string' },
|
|
595
|
-
{ pattern: /^mysql:\/\//i, label: 'MySQL connection string' },
|
|
596
|
-
{ pattern: /^redis:\/\//i, label: 'Redis connection string' },
|
|
597
|
-
{ pattern: /^amqps?:\/\//i, label: 'AMQP connection string' },
|
|
598
|
-
{ pattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, label: 'IP address' },
|
|
599
|
-
{ pattern: /^:[0-9]{2,5}$/, label: 'Port number in string' },
|
|
600
|
-
{ pattern: /^\/[a-z]/i, label: 'Absolute file path' },
|
|
601
|
-
{ pattern: /localhost(:[0-9]+)?/i, label: 'localhost reference' },
|
|
602
|
-
];
|
|
603
|
-
const filePath = file.getFilePath().replace(/\\/g, '/');
|
|
604
|
-
if (filePath.includes('.test.') || filePath.includes('.spec.') || filePath.includes('__tests__')) {
|
|
605
|
-
return issues;
|
|
606
|
-
}
|
|
607
|
-
for (const node of file.getDescendantsOfKind(SyntaxKind.StringLiteral)) {
|
|
608
|
-
const value = node.getLiteralValue();
|
|
609
|
-
if (!value || value.length < 4)
|
|
610
|
-
continue;
|
|
611
|
-
const parent = node.getParent();
|
|
612
|
-
if (!parent)
|
|
613
|
-
continue;
|
|
614
|
-
const parentKind = parent.getKindName();
|
|
615
|
-
if (parentKind === 'ImportDeclaration' ||
|
|
616
|
-
parentKind === 'ExportDeclaration' ||
|
|
617
|
-
(parentKind === 'CallExpression' && parent.getText().startsWith('import(')))
|
|
618
|
-
continue;
|
|
619
|
-
for (const { pattern, label } of CONFIG_PATTERNS) {
|
|
620
|
-
if (pattern.test(value)) {
|
|
621
|
-
issues.push({
|
|
622
|
-
rule: 'hardcoded-config',
|
|
623
|
-
severity: 'warning',
|
|
624
|
-
message: `Hardcoded ${label} detected. AI skips environment variables — extract to process.env or a config module.`,
|
|
625
|
-
line: node.getStartLineNumber(),
|
|
626
|
-
column: node.getStartLinePos(),
|
|
627
|
-
snippet: value.length > 60 ? value.slice(0, 60) + '...' : value,
|
|
628
|
-
});
|
|
629
|
-
break;
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
return issues;
|
|
634
|
-
}
|
|
635
|
-
function detectInconsistentErrorHandling(file) {
|
|
636
|
-
const issues = [];
|
|
637
|
-
let hasTryCatch = false;
|
|
638
|
-
let hasDotCatch = false;
|
|
639
|
-
let hasThenErrorHandler = false;
|
|
640
|
-
let firstLine = 0;
|
|
641
|
-
// Detectar try/catch
|
|
642
|
-
const tryCatches = file.getDescendantsOfKind(SyntaxKind.TryStatement);
|
|
643
|
-
if (tryCatches.length > 0) {
|
|
644
|
-
hasTryCatch = true;
|
|
645
|
-
firstLine = firstLine || tryCatches[0].getStartLineNumber();
|
|
646
|
-
}
|
|
647
|
-
// Detectar .catch(handler) en call expressions
|
|
648
|
-
for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
649
|
-
const expr = call.getExpression();
|
|
650
|
-
if (expr.getKindName() === 'PropertyAccessExpression') {
|
|
651
|
-
const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);
|
|
652
|
-
const propName = propAccess.getName();
|
|
653
|
-
if (propName === 'catch') {
|
|
654
|
-
// Verificar que tiene al menos un argumento (handler real, no .catch() vacío)
|
|
655
|
-
if (call.getArguments().length > 0) {
|
|
656
|
-
hasDotCatch = true;
|
|
657
|
-
if (!firstLine)
|
|
658
|
-
firstLine = call.getStartLineNumber();
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
// Detectar .then(onFulfilled, onRejected) — segundo argumento = error handler
|
|
662
|
-
if (propName === 'then' && call.getArguments().length >= 2) {
|
|
663
|
-
hasThenErrorHandler = true;
|
|
664
|
-
if (!firstLine)
|
|
665
|
-
firstLine = call.getStartLineNumber();
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
const stylesUsed = [hasTryCatch, hasDotCatch, hasThenErrorHandler].filter(Boolean).length;
|
|
670
|
-
if (stylesUsed >= 2) {
|
|
671
|
-
const styles = [];
|
|
672
|
-
if (hasTryCatch)
|
|
673
|
-
styles.push('try/catch');
|
|
674
|
-
if (hasDotCatch)
|
|
675
|
-
styles.push('.catch()');
|
|
676
|
-
if (hasThenErrorHandler)
|
|
677
|
-
styles.push('.then(_, handler)');
|
|
678
|
-
issues.push({
|
|
679
|
-
rule: 'inconsistent-error-handling',
|
|
680
|
-
severity: 'warning',
|
|
681
|
-
message: `Mixed error handling styles: ${styles.join(', ')}. AI uses whatever pattern it saw last — pick one and stick to it.`,
|
|
682
|
-
line: firstLine || 1,
|
|
683
|
-
column: 1,
|
|
684
|
-
snippet: styles.join(' + '),
|
|
685
|
-
});
|
|
686
|
-
}
|
|
687
|
-
return issues;
|
|
688
|
-
}
|
|
689
|
-
function detectUnnecessaryAbstraction(file) {
|
|
690
|
-
const issues = [];
|
|
691
|
-
const fileText = file.getFullText();
|
|
692
|
-
// Interfaces con un solo método
|
|
693
|
-
for (const iface of file.getInterfaces()) {
|
|
694
|
-
const methods = iface.getMethods();
|
|
695
|
-
const properties = iface.getProperties();
|
|
696
|
-
// Solo reportar si tiene exactamente 1 método y 0 propiedades (abstracción pura de comportamiento)
|
|
697
|
-
if (methods.length !== 1 || properties.length !== 0)
|
|
698
|
-
continue;
|
|
699
|
-
const ifaceName = iface.getName();
|
|
700
|
-
// Contar cuántas veces aparece el nombre en el archivo (excluyendo la declaración misma)
|
|
701
|
-
const usageCount = (fileText.match(new RegExp(`\\b${ifaceName}\\b`, 'g')) ?? []).length;
|
|
702
|
-
// La declaración misma cuenta como 1 uso, implementaciones cuentan como 1 cada una
|
|
703
|
-
// Si usageCount <= 2 (declaración + 1 uso), es candidata a innecesaria
|
|
704
|
-
if (usageCount <= 2) {
|
|
705
|
-
issues.push({
|
|
706
|
-
rule: 'unnecessary-abstraction',
|
|
707
|
-
severity: 'warning',
|
|
708
|
-
message: `Interface '${ifaceName}' has 1 method and is used only once. AI creates abstractions preemptively — YAGNI.`,
|
|
709
|
-
line: iface.getStartLineNumber(),
|
|
710
|
-
column: iface.getStartLinePos(),
|
|
711
|
-
snippet: `interface ${ifaceName} { ${methods[0].getName()}(...) }`,
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
// Clases abstractas con un solo método abstracto y sin implementaciones en el archivo
|
|
716
|
-
for (const cls of file.getClasses()) {
|
|
717
|
-
if (!cls.isAbstract())
|
|
718
|
-
continue;
|
|
719
|
-
const abstractMethods = cls.getMethods().filter(m => m.isAbstract());
|
|
720
|
-
const concreteMethods = cls.getMethods().filter(m => !m.isAbstract());
|
|
721
|
-
if (abstractMethods.length !== 1 || concreteMethods.length !== 0)
|
|
722
|
-
continue;
|
|
723
|
-
const clsName = cls.getName() ?? '';
|
|
724
|
-
const usageCount = (fileText.match(new RegExp(`\\b${clsName}\\b`, 'g')) ?? []).length;
|
|
725
|
-
if (usageCount <= 2) {
|
|
726
|
-
issues.push({
|
|
727
|
-
rule: 'unnecessary-abstraction',
|
|
728
|
-
severity: 'warning',
|
|
729
|
-
message: `Abstract class '${clsName}' has 1 abstract method and is extended nowhere in this file. AI over-engineers single-use code.`,
|
|
730
|
-
line: cls.getStartLineNumber(),
|
|
731
|
-
column: cls.getStartLinePos(),
|
|
732
|
-
snippet: `abstract class ${clsName}`,
|
|
733
|
-
});
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
return issues;
|
|
737
|
-
}
|
|
738
|
-
function detectNamingInconsistency(file) {
|
|
739
|
-
const issues = [];
|
|
740
|
-
const isCamelCase = (name) => /^[a-z][a-zA-Z0-9]*$/.test(name) && /[A-Z]/.test(name);
|
|
741
|
-
const isSnakeCase = (name) => /^[a-z][a-z0-9]*(_[a-z0-9]+)+$/.test(name);
|
|
742
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
743
|
-
function checkFunction(fn) {
|
|
744
|
-
const vars = fn.getVariableDeclarations();
|
|
745
|
-
if (vars.length < 3)
|
|
746
|
-
return; // muy pocas vars para ser significativo
|
|
747
|
-
let camelCount = 0;
|
|
748
|
-
let snakeCount = 0;
|
|
749
|
-
const snakeExamples = [];
|
|
750
|
-
const camelExamples = [];
|
|
751
|
-
for (const v of vars) {
|
|
752
|
-
const name = v.getName();
|
|
753
|
-
if (isCamelCase(name)) {
|
|
754
|
-
camelCount++;
|
|
755
|
-
if (camelExamples.length < 2)
|
|
756
|
-
camelExamples.push(name);
|
|
757
|
-
}
|
|
758
|
-
else if (isSnakeCase(name)) {
|
|
759
|
-
snakeCount++;
|
|
760
|
-
if (snakeExamples.length < 2)
|
|
761
|
-
snakeExamples.push(name);
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
if (camelCount >= 1 && snakeCount >= 1) {
|
|
765
|
-
issues.push({
|
|
766
|
-
rule: 'naming-inconsistency',
|
|
767
|
-
severity: 'warning',
|
|
768
|
-
message: `Mixed naming conventions: camelCase (${camelExamples.join(', ')}) and snake_case (${snakeExamples.join(', ')}) in the same scope. AI mixes conventions from different training examples.`,
|
|
769
|
-
line: fn.getStartLineNumber(),
|
|
770
|
-
column: fn.getStartLinePos(),
|
|
771
|
-
snippet: `camelCase: ${camelExamples[0]} / snake_case: ${snakeExamples[0]}`,
|
|
772
|
-
});
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
for (const fn of file.getFunctions()) {
|
|
776
|
-
checkFunction(fn);
|
|
777
|
-
}
|
|
778
|
-
for (const cls of file.getClasses()) {
|
|
779
|
-
for (const method of cls.getMethods()) {
|
|
780
|
-
checkFunction(method);
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
return issues;
|
|
784
|
-
}
|
|
785
|
-
// ---------------------------------------------------------------------------
|
|
786
|
-
// Score
|
|
787
|
-
// ---------------------------------------------------------------------------
|
|
788
|
-
function calculateScore(issues) {
|
|
789
|
-
let raw = 0;
|
|
790
|
-
for (const issue of issues) {
|
|
791
|
-
raw += RULE_WEIGHTS[issue.rule]?.weight ?? 5;
|
|
792
|
-
}
|
|
793
|
-
return Math.min(100, raw);
|
|
794
|
-
}
|
|
795
|
-
/** Normalize a function body to a canonical string (Type-2 clone detection).
|
|
796
|
-
* Variable names, parameter names, and numeric/string literals are replaced
|
|
797
|
-
* with canonical tokens so that two functions with identical logic but
|
|
798
|
-
* different identifiers produce the same fingerprint.
|
|
799
|
-
*/
|
|
800
|
-
function normalizeFunctionBody(fn) {
|
|
801
|
-
// Build a substitution map: localName → canonical token
|
|
802
|
-
const subst = new Map();
|
|
803
|
-
// Map parameters first
|
|
804
|
-
for (const [i, param] of fn.getParameters().entries()) {
|
|
805
|
-
const name = param.getName();
|
|
806
|
-
if (name && name !== '_')
|
|
807
|
-
subst.set(name, `P${i}`);
|
|
808
|
-
}
|
|
809
|
-
// Map locally declared variables (VariableDeclaration)
|
|
810
|
-
let varIdx = 0;
|
|
811
|
-
fn.forEachDescendant(node => {
|
|
812
|
-
if (node.getKind() === SyntaxKind.VariableDeclaration) {
|
|
813
|
-
const nameNode = node.getNameNode();
|
|
814
|
-
// Support destructuring — getNameNode() may be a BindingPattern
|
|
815
|
-
if (nameNode.getKind() === SyntaxKind.Identifier) {
|
|
816
|
-
const name = nameNode.getText();
|
|
817
|
-
if (!subst.has(name))
|
|
818
|
-
subst.set(name, `V${varIdx++}`);
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
});
|
|
822
|
-
function serializeNode(node) {
|
|
823
|
-
const kind = node.getKindName();
|
|
824
|
-
switch (node.getKind()) {
|
|
825
|
-
case SyntaxKind.Identifier: {
|
|
826
|
-
const text = node.getText();
|
|
827
|
-
return subst.get(text) ?? text; // external refs (Math, console) kept as-is
|
|
828
|
-
}
|
|
829
|
-
case SyntaxKind.NumericLiteral:
|
|
830
|
-
return 'NL';
|
|
831
|
-
case SyntaxKind.StringLiteral:
|
|
832
|
-
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
|
833
|
-
return 'SL';
|
|
834
|
-
case SyntaxKind.TrueKeyword:
|
|
835
|
-
return 'TRUE';
|
|
836
|
-
case SyntaxKind.FalseKeyword:
|
|
837
|
-
return 'FALSE';
|
|
838
|
-
case SyntaxKind.NullKeyword:
|
|
839
|
-
return 'NULL';
|
|
840
|
-
}
|
|
841
|
-
const children = node.getChildren();
|
|
842
|
-
if (children.length === 0)
|
|
843
|
-
return kind;
|
|
844
|
-
const childStr = children.map(serializeNode).join('|');
|
|
845
|
-
return `${kind}(${childStr})`;
|
|
846
|
-
}
|
|
847
|
-
const body = fn.getBody();
|
|
848
|
-
if (!body)
|
|
849
|
-
return '';
|
|
850
|
-
return serializeNode(body);
|
|
851
|
-
}
|
|
852
|
-
/** Return a SHA-256 fingerprint for a function body (normalized). */
|
|
853
|
-
function fingerprintFunction(fn) {
|
|
854
|
-
const normalized = normalizeFunctionBody(fn);
|
|
855
|
-
return crypto.createHash('sha256').update(normalized).digest('hex');
|
|
856
|
-
}
|
|
857
|
-
/** Return all function-like nodes from a SourceFile that are worth comparing:
|
|
858
|
-
* - At least MIN_LINES lines in their body
|
|
859
|
-
* - Not test helpers (describe/it/test/beforeEach/afterEach)
|
|
860
|
-
*/
|
|
861
|
-
const MIN_LINES = 8;
|
|
862
|
-
function collectFunctions(sf) {
|
|
863
|
-
const results = [];
|
|
864
|
-
const kinds = [
|
|
865
|
-
SyntaxKind.FunctionDeclaration,
|
|
866
|
-
SyntaxKind.FunctionExpression,
|
|
867
|
-
SyntaxKind.ArrowFunction,
|
|
868
|
-
SyntaxKind.MethodDeclaration,
|
|
869
|
-
];
|
|
870
|
-
for (const kind of kinds) {
|
|
871
|
-
for (const node of sf.getDescendantsOfKind(kind)) {
|
|
872
|
-
const body = node.getBody();
|
|
873
|
-
if (!body)
|
|
874
|
-
continue;
|
|
875
|
-
const start = body.getStartLineNumber();
|
|
876
|
-
const end = body.getEndLineNumber();
|
|
877
|
-
if (end - start + 1 < MIN_LINES)
|
|
878
|
-
continue;
|
|
879
|
-
// Skip test-framework helpers
|
|
880
|
-
const name = node.getKind() === SyntaxKind.FunctionDeclaration
|
|
881
|
-
? node.getName() ?? '<anonymous>'
|
|
882
|
-
: node.getKind() === SyntaxKind.MethodDeclaration
|
|
883
|
-
? node.getName()
|
|
884
|
-
: '<anonymous>';
|
|
885
|
-
if (['describe', 'it', 'test', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll'].includes(name))
|
|
886
|
-
continue;
|
|
887
|
-
const pos = node.getStart();
|
|
888
|
-
const lineInfo = sf.getLineAndColumnAtPos(pos);
|
|
889
|
-
results.push({ fn: node, name, line: lineInfo.line, col: lineInfo.column });
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
return results;
|
|
893
|
-
}
|
|
894
|
-
// ---------------------------------------------------------------------------
|
|
895
|
-
// Public API
|
|
54
|
+
// Per-file analysis
|
|
896
55
|
// ---------------------------------------------------------------------------
|
|
897
56
|
export function analyzeFile(file) {
|
|
898
57
|
if (isFileIgnored(file)) {
|
|
@@ -917,7 +76,6 @@ export function analyzeFile(file) {
|
|
|
917
76
|
...detectTooManyParams(file),
|
|
918
77
|
...detectHighCoupling(file),
|
|
919
78
|
...detectPromiseStyleMix(file),
|
|
920
|
-
// Stubs now implemented
|
|
921
79
|
...detectMagicNumbers(file),
|
|
922
80
|
...detectCommentContradiction(file),
|
|
923
81
|
// Phase 5: AI authorship heuristics
|
|
@@ -930,13 +88,16 @@ export function analyzeFile(file) {
|
|
|
930
88
|
return {
|
|
931
89
|
path: file.getFilePath(),
|
|
932
90
|
issues,
|
|
933
|
-
score: calculateScore(issues),
|
|
91
|
+
score: calculateScore(issues, RULE_WEIGHTS),
|
|
934
92
|
};
|
|
935
93
|
}
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// Project-level analysis (phases 2, 3, 8 require the full file set)
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
936
97
|
export function analyzeProject(targetPath, config) {
|
|
937
98
|
const project = new Project({
|
|
938
99
|
skipAddingFilesFromTsConfig: true,
|
|
939
|
-
compilerOptions: { allowJs: true },
|
|
100
|
+
compilerOptions: { allowJs: true, jsx: 1 }, // 1 = JsxEmit.Preserve
|
|
940
101
|
});
|
|
941
102
|
project.addSourceFilesAtPaths([
|
|
942
103
|
`${targetPath}/**/*.ts`,
|
|
@@ -957,26 +118,25 @@ export function analyzeProject(targetPath, config) {
|
|
|
957
118
|
const reportByPath = new Map();
|
|
958
119
|
for (const r of reports)
|
|
959
120
|
reportByPath.set(r.path, r);
|
|
960
|
-
//
|
|
961
|
-
const
|
|
962
|
-
|
|
963
|
-
const
|
|
964
|
-
const
|
|
121
|
+
// Build set of ignored paths so cross-file phases don't re-add issues
|
|
122
|
+
const ignoredPaths = new Set(sourceFiles.filter(sf => isFileIgnored(sf)).map(sf => sf.getFilePath()));
|
|
123
|
+
// ── Phase 2 setup: build import graph ──────────────────────────────────────
|
|
124
|
+
const allImportedPaths = new Set();
|
|
125
|
+
const allImportedNames = new Map();
|
|
126
|
+
const allLiteralImports = new Set();
|
|
127
|
+
const importGraph = new Map();
|
|
965
128
|
for (const sf of sourceFiles) {
|
|
966
129
|
const sfPath = sf.getFilePath();
|
|
967
130
|
for (const decl of sf.getImportDeclarations()) {
|
|
968
131
|
const moduleSpecifier = decl.getModuleSpecifierValue();
|
|
969
132
|
allLiteralImports.add(moduleSpecifier);
|
|
970
|
-
// Resolve to absolute path for dead-file / unused-export
|
|
971
133
|
const resolved = decl.getModuleSpecifierSourceFile();
|
|
972
134
|
if (resolved) {
|
|
973
135
|
const resolvedPath = resolved.getFilePath();
|
|
974
136
|
allImportedPaths.add(resolvedPath);
|
|
975
|
-
// Phase 3: populate directed import graph
|
|
976
137
|
if (!importGraph.has(sfPath))
|
|
977
138
|
importGraph.set(sfPath, new Set());
|
|
978
139
|
importGraph.get(sfPath).add(resolvedPath);
|
|
979
|
-
// Collect named imports { A, B } and default imports
|
|
980
140
|
const named = decl.getNamedImports().map(n => n.getName());
|
|
981
141
|
const def = decl.getDefaultImport()?.getText();
|
|
982
142
|
const ns = decl.getNamespaceImport()?.getText();
|
|
@@ -989,11 +149,9 @@ export function analyzeProject(targetPath, config) {
|
|
|
989
149
|
if (def)
|
|
990
150
|
nameSet.add('default');
|
|
991
151
|
if (ns)
|
|
992
|
-
nameSet.add('*');
|
|
152
|
+
nameSet.add('*');
|
|
993
153
|
}
|
|
994
154
|
}
|
|
995
|
-
// Also register re-exports: export { X, Y } from './module'
|
|
996
|
-
// These count as "using" X and Y from the source module
|
|
997
155
|
for (const exportDecl of sf.getExportDeclarations()) {
|
|
998
156
|
const reExportedModule = exportDecl.getModuleSpecifierSourceFile();
|
|
999
157
|
if (!reExportedModule)
|
|
@@ -1006,7 +164,6 @@ export function analyzeProject(targetPath, config) {
|
|
|
1006
164
|
const nameSet = allImportedNames.get(reExportedPath);
|
|
1007
165
|
const namedExports = exportDecl.getNamedExports();
|
|
1008
166
|
if (namedExports.length === 0) {
|
|
1009
|
-
// export * from './module' — namespace re-export, all names used
|
|
1010
167
|
nameSet.add('*');
|
|
1011
168
|
}
|
|
1012
169
|
else {
|
|
@@ -1015,262 +172,84 @@ export function analyzeProject(targetPath, config) {
|
|
|
1015
172
|
}
|
|
1016
173
|
}
|
|
1017
174
|
}
|
|
1018
|
-
//
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
if (!report)
|
|
175
|
+
// ── Phase 2: dead-file + unused-export + unused-dependency ─────────────────
|
|
176
|
+
const deadFiles = detectDeadFiles(sourceFiles, allImportedPaths, RULE_WEIGHTS);
|
|
177
|
+
for (const [sfPath, issue] of deadFiles) {
|
|
178
|
+
if (ignoredPaths.has(sfPath))
|
|
1023
179
|
continue;
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
const basename = path.basename(sfPath);
|
|
1027
|
-
const isBinFile = sfPath.replace(/\\/g, '/').includes('/bin/');
|
|
1028
|
-
const isEntryPoint = /^(index|main|cli|app)\.(ts|tsx|js|jsx)$/.test(basename) || isBinFile;
|
|
1029
|
-
if (!isEntryPoint && !allImportedPaths.has(sfPath)) {
|
|
1030
|
-
const issue = {
|
|
1031
|
-
rule: 'dead-file',
|
|
1032
|
-
severity: RULE_WEIGHTS['dead-file'].severity,
|
|
1033
|
-
message: 'File is never imported — may be dead code',
|
|
1034
|
-
line: 1,
|
|
1035
|
-
column: 1,
|
|
1036
|
-
snippet: basename,
|
|
1037
|
-
};
|
|
180
|
+
const report = reportByPath.get(sfPath);
|
|
181
|
+
if (report) {
|
|
1038
182
|
report.issues.push(issue);
|
|
1039
|
-
report.score = calculateScore(report.issues);
|
|
1040
|
-
}
|
|
1041
|
-
// unused-export: named exports not imported anywhere
|
|
1042
|
-
// Skip barrel files (index.ts) — their entire surface is the public API
|
|
1043
|
-
const isBarrel = /^index\.(ts|tsx|js|jsx)$/.test(basename);
|
|
1044
|
-
const importedNamesForFile = allImportedNames.get(sfPath);
|
|
1045
|
-
const hasNamespaceImport = importedNamesForFile?.has('*') ?? false;
|
|
1046
|
-
if (!isBarrel && !hasNamespaceImport) {
|
|
1047
|
-
for (const exportDecl of sf.getExportDeclarations()) {
|
|
1048
|
-
for (const namedExport of exportDecl.getNamedExports()) {
|
|
1049
|
-
const name = namedExport.getName();
|
|
1050
|
-
if (!importedNamesForFile?.has(name)) {
|
|
1051
|
-
const line = namedExport.getStartLineNumber();
|
|
1052
|
-
const issue = {
|
|
1053
|
-
rule: 'unused-export',
|
|
1054
|
-
severity: RULE_WEIGHTS['unused-export'].severity,
|
|
1055
|
-
message: `'${name}' is exported but never imported`,
|
|
1056
|
-
line,
|
|
1057
|
-
column: 1,
|
|
1058
|
-
snippet: namedExport.getText().slice(0, 80),
|
|
1059
|
-
};
|
|
1060
|
-
report.issues.push(issue);
|
|
1061
|
-
report.score = calculateScore(report.issues);
|
|
1062
|
-
}
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
// Also check inline export declarations (export function foo, export const bar)
|
|
1066
|
-
for (const exportSymbol of sf.getExportedDeclarations()) {
|
|
1067
|
-
const [exportName, declarations] = [exportSymbol[0], exportSymbol[1]];
|
|
1068
|
-
if (exportName === 'default')
|
|
1069
|
-
continue;
|
|
1070
|
-
if (importedNamesForFile?.has(exportName))
|
|
1071
|
-
continue;
|
|
1072
|
-
for (const decl of declarations) {
|
|
1073
|
-
// Skip if this is a re-export from another file
|
|
1074
|
-
if (decl.getSourceFile().getFilePath() !== sfPath)
|
|
1075
|
-
continue;
|
|
1076
|
-
const line = decl.getStartLineNumber();
|
|
1077
|
-
const issue = {
|
|
1078
|
-
rule: 'unused-export',
|
|
1079
|
-
severity: RULE_WEIGHTS['unused-export'].severity,
|
|
1080
|
-
message: `'${exportName}' is exported but never imported`,
|
|
1081
|
-
line,
|
|
1082
|
-
column: 1,
|
|
1083
|
-
snippet: decl.getText().split('\n')[0].slice(0, 80),
|
|
1084
|
-
};
|
|
1085
|
-
report.issues.push(issue);
|
|
1086
|
-
report.score = calculateScore(report.issues);
|
|
1087
|
-
break; // one issue per export name is enough
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
// Detect unused-dependency: packages in package.json never imported
|
|
1093
|
-
const pkgPath = path.join(targetPath, 'package.json');
|
|
1094
|
-
if (fs.existsSync(pkgPath)) {
|
|
1095
|
-
let pkg;
|
|
1096
|
-
try {
|
|
1097
|
-
pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
|
|
1098
|
-
}
|
|
1099
|
-
catch {
|
|
1100
|
-
pkg = {};
|
|
1101
|
-
}
|
|
1102
|
-
const deps = {
|
|
1103
|
-
...(pkg.dependencies ?? {}),
|
|
1104
|
-
};
|
|
1105
|
-
const unusedDeps = [];
|
|
1106
|
-
for (const depName of Object.keys(deps)) {
|
|
1107
|
-
// Skip type-only packages (@types/*)
|
|
1108
|
-
if (depName.startsWith('@types/'))
|
|
1109
|
-
continue;
|
|
1110
|
-
// A dependency is "used" if any import specifier starts with the package name
|
|
1111
|
-
// (handles sub-paths like 'lodash/merge', 'date-fns/format', etc.)
|
|
1112
|
-
const isUsed = [...allLiteralImports].some(imp => imp === depName || imp.startsWith(depName + '/'));
|
|
1113
|
-
if (!isUsed)
|
|
1114
|
-
unusedDeps.push(depName);
|
|
1115
|
-
}
|
|
1116
|
-
if (unusedDeps.length > 0) {
|
|
1117
|
-
const pkgIssues = unusedDeps.map(dep => ({
|
|
1118
|
-
rule: 'unused-dependency',
|
|
1119
|
-
severity: RULE_WEIGHTS['unused-dependency'].severity,
|
|
1120
|
-
message: `'${dep}' is in package.json but never imported`,
|
|
1121
|
-
line: 1,
|
|
1122
|
-
column: 1,
|
|
1123
|
-
snippet: `"${dep}"`,
|
|
1124
|
-
}));
|
|
1125
|
-
reports.push({
|
|
1126
|
-
path: pkgPath,
|
|
1127
|
-
issues: pkgIssues,
|
|
1128
|
-
score: calculateScore(pkgIssues),
|
|
1129
|
-
});
|
|
183
|
+
report.score = calculateScore(report.issues, RULE_WEIGHTS);
|
|
1130
184
|
}
|
|
1131
185
|
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
const
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
stack.push(node);
|
|
1141
|
-
for (const neighbor of graph.get(node) ?? []) {
|
|
1142
|
-
if (!visited.has(neighbor)) {
|
|
1143
|
-
dfs(neighbor, stack);
|
|
1144
|
-
}
|
|
1145
|
-
else if (inStack.has(neighbor)) {
|
|
1146
|
-
// Found a cycle — extract the cycle portion from the stack
|
|
1147
|
-
const cycleStart = stack.indexOf(neighbor);
|
|
1148
|
-
cycles.push(stack.slice(cycleStart));
|
|
1149
|
-
}
|
|
1150
|
-
}
|
|
1151
|
-
stack.pop();
|
|
1152
|
-
inStack.delete(node);
|
|
1153
|
-
}
|
|
1154
|
-
for (const node of graph.keys()) {
|
|
1155
|
-
if (!visited.has(node)) {
|
|
1156
|
-
dfs(node, []);
|
|
186
|
+
const unusedExports = detectUnusedExports(sourceFiles, allImportedNames, RULE_WEIGHTS);
|
|
187
|
+
for (const [sfPath, issues] of unusedExports) {
|
|
188
|
+
if (ignoredPaths.has(sfPath))
|
|
189
|
+
continue;
|
|
190
|
+
const report = reportByPath.get(sfPath);
|
|
191
|
+
if (report) {
|
|
192
|
+
for (const issue of issues) {
|
|
193
|
+
report.issues.push(issue);
|
|
1157
194
|
}
|
|
195
|
+
report.score = calculateScore(report.issues, RULE_WEIGHTS);
|
|
1158
196
|
}
|
|
1159
|
-
return cycles;
|
|
1160
197
|
}
|
|
1161
|
-
const
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
198
|
+
const unusedDepIssues = detectUnusedDependencies(targetPath, allLiteralImports, RULE_WEIGHTS);
|
|
199
|
+
if (unusedDepIssues.length > 0) {
|
|
200
|
+
const pkgPath = path.join(targetPath, 'package.json');
|
|
201
|
+
reports.push({
|
|
202
|
+
path: pkgPath,
|
|
203
|
+
issues: unusedDepIssues,
|
|
204
|
+
score: calculateScore(unusedDepIssues, RULE_WEIGHTS),
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
// ── Phase 3: circular-dependency ────────────────────────────────────────────
|
|
208
|
+
const circularIssues = detectCircularDependencies(importGraph, RULE_WEIGHTS);
|
|
209
|
+
for (const [filePath, issue] of circularIssues) {
|
|
210
|
+
if (ignoredPaths.has(filePath))
|
|
1173
211
|
continue;
|
|
1174
|
-
const
|
|
1175
|
-
|
|
1176
|
-
.
|
|
1177
|
-
.
|
|
1178
|
-
|
|
1179
|
-
rule: 'circular-dependency',
|
|
1180
|
-
severity: RULE_WEIGHTS['circular-dependency'].severity,
|
|
1181
|
-
message: `Circular dependency detected: ${cycleDisplay}`,
|
|
1182
|
-
line: 1,
|
|
1183
|
-
column: 1,
|
|
1184
|
-
snippet: cycleDisplay,
|
|
1185
|
-
};
|
|
1186
|
-
report.issues.push(issue);
|
|
1187
|
-
report.score = calculateScore(report.issues);
|
|
212
|
+
const report = reportByPath.get(filePath);
|
|
213
|
+
if (report) {
|
|
214
|
+
report.issues.push(issue);
|
|
215
|
+
report.score = calculateScore(report.issues, RULE_WEIGHTS);
|
|
216
|
+
}
|
|
1188
217
|
}
|
|
1189
|
-
// ── Phase 3b: layer-violation
|
|
218
|
+
// ── Phase 3b: layer-violation ────────────────────────────────────────────────
|
|
1190
219
|
if (config?.layers && config.layers.length > 0) {
|
|
1191
|
-
const
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
return layers.find(layer => layer.patterns.some(pattern => {
|
|
1195
|
-
const regexStr = pattern
|
|
1196
|
-
.replace(/\\/g, '/')
|
|
1197
|
-
.replace(/[.+^${}()|[\]]/g, '\\$&')
|
|
1198
|
-
.replace(/\*\*/g, '###DOUBLESTAR###')
|
|
1199
|
-
.replace(/\*/g, '[^/]*')
|
|
1200
|
-
.replace(/###DOUBLESTAR###/g, '.*');
|
|
1201
|
-
return new RegExp(`^${regexStr}`).test(rel);
|
|
1202
|
-
}));
|
|
1203
|
-
}
|
|
1204
|
-
for (const [filePath, imports] of importGraph.entries()) {
|
|
1205
|
-
const fileLayer = getLayer(filePath);
|
|
1206
|
-
if (!fileLayer)
|
|
220
|
+
const layerIssues = detectLayerViolations(importGraph, config.layers, targetPath, RULE_WEIGHTS);
|
|
221
|
+
for (const [filePath, issues] of layerIssues) {
|
|
222
|
+
if (ignoredPaths.has(filePath))
|
|
1207
223
|
continue;
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
continue;
|
|
1214
|
-
if (!fileLayer.canImportFrom.includes(importedLayer.name)) {
|
|
1215
|
-
const report = reportByPath.get(filePath);
|
|
1216
|
-
if (report) {
|
|
1217
|
-
const weight = RULE_WEIGHTS['layer-violation']?.weight ?? 5;
|
|
1218
|
-
report.issues.push({
|
|
1219
|
-
rule: 'layer-violation',
|
|
1220
|
-
severity: 'error',
|
|
1221
|
-
message: `Layer '${fileLayer.name}' must not import from layer '${importedLayer.name}'`,
|
|
1222
|
-
line: 1,
|
|
1223
|
-
column: 1,
|
|
1224
|
-
snippet: `import from '${path.relative(targetPath, importedPath).replace(/\\/g, '/')}'`,
|
|
1225
|
-
});
|
|
1226
|
-
report.score = Math.min(100, report.score + weight);
|
|
1227
|
-
}
|
|
224
|
+
const report = reportByPath.get(filePath);
|
|
225
|
+
if (report) {
|
|
226
|
+
for (const issue of issues) {
|
|
227
|
+
report.issues.push(issue);
|
|
228
|
+
report.score = Math.min(100, report.score + (RULE_WEIGHTS['layer-violation']?.weight ?? 5));
|
|
1228
229
|
}
|
|
1229
230
|
}
|
|
1230
231
|
}
|
|
1231
232
|
}
|
|
1232
|
-
// ── Phase 3c: cross-boundary-import
|
|
233
|
+
// ── Phase 3c: cross-boundary-import ─────────────────────────────────────────
|
|
1233
234
|
if (config?.modules && config.modules.length > 0) {
|
|
1234
|
-
const
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
return modules.find(m => rel.startsWith(m.root.replace(/\\/g, '/')));
|
|
1238
|
-
}
|
|
1239
|
-
for (const [filePath, imports] of importGraph.entries()) {
|
|
1240
|
-
const fileModule = getModule(filePath);
|
|
1241
|
-
if (!fileModule)
|
|
235
|
+
const boundaryIssues = detectCrossBoundaryImports(importGraph, config.modules, targetPath, RULE_WEIGHTS);
|
|
236
|
+
for (const [filePath, issues] of boundaryIssues) {
|
|
237
|
+
if (ignoredPaths.has(filePath))
|
|
1242
238
|
continue;
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
continue;
|
|
1249
|
-
const allowedImports = fileModule.allowedExternalImports ?? [];
|
|
1250
|
-
const relImported = importedPath.replace(/\\/g, '/');
|
|
1251
|
-
const isAllowed = allowedImports.some(allowed => relImported.startsWith(allowed.replace(/\\/g, '/')));
|
|
1252
|
-
if (!isAllowed) {
|
|
1253
|
-
const report = reportByPath.get(filePath);
|
|
1254
|
-
if (report) {
|
|
1255
|
-
const weight = RULE_WEIGHTS['cross-boundary-import']?.weight ?? 5;
|
|
1256
|
-
report.issues.push({
|
|
1257
|
-
rule: 'cross-boundary-import',
|
|
1258
|
-
severity: 'warning',
|
|
1259
|
-
message: `Module '${fileModule.name}' must not import from module '${importedModule.name}'`,
|
|
1260
|
-
line: 1,
|
|
1261
|
-
column: 1,
|
|
1262
|
-
snippet: `import from '${path.relative(targetPath, importedPath).replace(/\\/g, '/')}'`,
|
|
1263
|
-
});
|
|
1264
|
-
report.score = Math.min(100, report.score + weight);
|
|
1265
|
-
}
|
|
239
|
+
const report = reportByPath.get(filePath);
|
|
240
|
+
if (report) {
|
|
241
|
+
for (const issue of issues) {
|
|
242
|
+
report.issues.push(issue);
|
|
243
|
+
report.score = Math.min(100, report.score + (RULE_WEIGHTS['cross-boundary-import']?.weight ?? 5));
|
|
1266
244
|
}
|
|
1267
245
|
}
|
|
1268
246
|
}
|
|
1269
247
|
}
|
|
1270
|
-
// ── Phase 8: semantic-duplication
|
|
1271
|
-
// Build a fingerprint → [{filePath, fnName, line, col}] map across all files
|
|
248
|
+
// ── Phase 8: semantic-duplication ───────────────────────────────────────────
|
|
1272
249
|
const fingerprintMap = new Map();
|
|
1273
250
|
for (const sf of sourceFiles) {
|
|
251
|
+
if (isFileIgnored(sf))
|
|
252
|
+
continue;
|
|
1274
253
|
const sfPath = sf.getFilePath();
|
|
1275
254
|
for (const { fn, name, line, col } of collectFunctions(sf)) {
|
|
1276
255
|
const fp = fingerprintFunction(fn);
|
|
@@ -1279,7 +258,6 @@ export function analyzeProject(targetPath, config) {
|
|
|
1279
258
|
fingerprintMap.get(fp).push({ filePath: sfPath, name, line, col });
|
|
1280
259
|
}
|
|
1281
260
|
}
|
|
1282
|
-
// For each fingerprint with 2+ functions: report each as a duplicate of the others
|
|
1283
261
|
for (const [, entries] of fingerprintMap) {
|
|
1284
262
|
if (entries.length < 2)
|
|
1285
263
|
continue;
|
|
@@ -1287,7 +265,6 @@ export function analyzeProject(targetPath, config) {
|
|
|
1287
265
|
const report = reportByPath.get(entry.filePath);
|
|
1288
266
|
if (!report)
|
|
1289
267
|
continue;
|
|
1290
|
-
// Build the "duplicated in" list (all other locations)
|
|
1291
268
|
const others = entries
|
|
1292
269
|
.filter(e => e !== entry)
|
|
1293
270
|
.map(e => {
|
|
@@ -1309,406 +286,4 @@ export function analyzeProject(targetPath, config) {
|
|
|
1309
286
|
}
|
|
1310
287
|
return reports;
|
|
1311
288
|
}
|
|
1312
|
-
// ---------------------------------------------------------------------------
|
|
1313
|
-
// Git helpers
|
|
1314
|
-
// ---------------------------------------------------------------------------
|
|
1315
|
-
/** Analyse a file given its absolute path string (wraps analyzeFile). */
|
|
1316
|
-
function analyzeFilePath(filePath) {
|
|
1317
|
-
const proj = new Project({
|
|
1318
|
-
skipAddingFilesFromTsConfig: true,
|
|
1319
|
-
compilerOptions: { allowJs: true },
|
|
1320
|
-
});
|
|
1321
|
-
const sf = proj.addSourceFileAtPath(filePath);
|
|
1322
|
-
return analyzeFile(sf);
|
|
1323
|
-
}
|
|
1324
|
-
/**
|
|
1325
|
-
* Execute a git command synchronously and return stdout.
|
|
1326
|
-
* Throws a descriptive error if the command fails or git is not available.
|
|
1327
|
-
*/
|
|
1328
|
-
function execGit(cmd, cwd) {
|
|
1329
|
-
try {
|
|
1330
|
-
return execSync(cmd, { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
|
|
1331
|
-
}
|
|
1332
|
-
catch (err) {
|
|
1333
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
1334
|
-
throw new Error(`Git command failed: ${cmd}\n${msg}`);
|
|
1335
|
-
}
|
|
1336
|
-
}
|
|
1337
|
-
/**
|
|
1338
|
-
* Verify the given directory is a git repository.
|
|
1339
|
-
* Throws if git is not available or the directory is not a repo.
|
|
1340
|
-
*/
|
|
1341
|
-
function assertGitRepo(cwd) {
|
|
1342
|
-
try {
|
|
1343
|
-
execGit('git rev-parse --is-inside-work-tree', cwd);
|
|
1344
|
-
}
|
|
1345
|
-
catch {
|
|
1346
|
-
throw new Error(`Directory is not a git repository: ${cwd}`);
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
// ---------------------------------------------------------------------------
|
|
1350
|
-
// Historical analysis helpers
|
|
1351
|
-
// ---------------------------------------------------------------------------
|
|
1352
|
-
/**
|
|
1353
|
-
* Analyse a single file as it existed at a given commit hash.
|
|
1354
|
-
* Writes the blob to a temp file, runs analyzeFile, then cleans up.
|
|
1355
|
-
*/
|
|
1356
|
-
async function analyzeFileAtCommit(filePath, commitHash, projectRoot) {
|
|
1357
|
-
const relPath = path.relative(projectRoot, filePath).replace(/\\/g, '/');
|
|
1358
|
-
const blob = execGit(`git show ${commitHash}:${relPath}`, projectRoot);
|
|
1359
|
-
const tmpFile = path.join(os.tmpdir(), `drift-${crypto.randomBytes(8).toString('hex')}.ts`);
|
|
1360
|
-
try {
|
|
1361
|
-
fs.writeFileSync(tmpFile, blob, 'utf8');
|
|
1362
|
-
const report = analyzeFilePath(tmpFile);
|
|
1363
|
-
// Replace temp path with original for readable output
|
|
1364
|
-
return { ...report, path: filePath };
|
|
1365
|
-
}
|
|
1366
|
-
finally {
|
|
1367
|
-
try {
|
|
1368
|
-
fs.unlinkSync(tmpFile);
|
|
1369
|
-
}
|
|
1370
|
-
catch { /* ignore cleanup errors */ }
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
/**
|
|
1374
|
-
* Analyse all TypeScript files changed in a single commit.
|
|
1375
|
-
*/
|
|
1376
|
-
async function analyzeSingleCommit(commitHash, targetPath) {
|
|
1377
|
-
// --name-only lists changed files; format gives metadata
|
|
1378
|
-
const raw = execGit(`git show --name-only --format="%H|%ai|%an|%s" ${commitHash}`, targetPath);
|
|
1379
|
-
const lines = raw.split('\n');
|
|
1380
|
-
// First non-empty line is the metadata line
|
|
1381
|
-
const metaLine = lines[0] ?? '';
|
|
1382
|
-
const [hash, dateStr, author, ...msgParts] = metaLine.split('|');
|
|
1383
|
-
const message = msgParts.join('|').trim();
|
|
1384
|
-
const commitDate = new Date(dateStr ?? '');
|
|
1385
|
-
// Collect changed .ts/.tsx files (lines after the empty separator)
|
|
1386
|
-
const changedFiles = [];
|
|
1387
|
-
let pastSeparator = false;
|
|
1388
|
-
for (const line of lines.slice(1)) {
|
|
1389
|
-
if (!pastSeparator && line.trim() === '') {
|
|
1390
|
-
pastSeparator = true;
|
|
1391
|
-
continue;
|
|
1392
|
-
}
|
|
1393
|
-
if (pastSeparator && (line.endsWith('.ts') || line.endsWith('.tsx'))) {
|
|
1394
|
-
changedFiles.push(path.join(targetPath, line.trim()));
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
const fileReports = await Promise.all(changedFiles.map(f => analyzeFileAtCommit(f, hash ?? commitHash, targetPath).catch(() => null)));
|
|
1398
|
-
const validReports = fileReports.filter((r) => r !== null);
|
|
1399
|
-
const totalScore = validReports.reduce((s, r) => s + r.score, 0);
|
|
1400
|
-
const averageScore = validReports.length > 0 ? totalScore / validReports.length : 0;
|
|
1401
|
-
return {
|
|
1402
|
-
commitHash: hash ?? commitHash,
|
|
1403
|
-
commitDate,
|
|
1404
|
-
author: author ?? '',
|
|
1405
|
-
message,
|
|
1406
|
-
files: validReports,
|
|
1407
|
-
totalScore,
|
|
1408
|
-
averageScore,
|
|
1409
|
-
};
|
|
1410
|
-
}
|
|
1411
|
-
/**
|
|
1412
|
-
* Run historical analysis over all commits since a given date.
|
|
1413
|
-
* Returns results ordered chronologically (oldest first).
|
|
1414
|
-
*/
|
|
1415
|
-
async function analyzeHistoricalCommits(sinceDate, targetPath, maxCommits) {
|
|
1416
|
-
assertGitRepo(targetPath);
|
|
1417
|
-
const isoDate = sinceDate.toISOString();
|
|
1418
|
-
const raw = execGit(`git log --since="${isoDate}" --format="%H" --max-count=${maxCommits}`, targetPath);
|
|
1419
|
-
if (!raw)
|
|
1420
|
-
return [];
|
|
1421
|
-
const hashes = raw.split('\n').filter(Boolean);
|
|
1422
|
-
const analyses = await Promise.all(hashes.map(h => analyzeSingleCommit(h, targetPath).catch(() => null)));
|
|
1423
|
-
return analyses
|
|
1424
|
-
.filter((a) => a !== null)
|
|
1425
|
-
.sort((a, b) => a.commitDate.getTime() - b.commitDate.getTime());
|
|
1426
|
-
}
|
|
1427
|
-
// ---------------------------------------------------------------------------
|
|
1428
|
-
// TrendAnalyzer
|
|
1429
|
-
// ---------------------------------------------------------------------------
|
|
1430
|
-
export class TrendAnalyzer {
|
|
1431
|
-
projectPath;
|
|
1432
|
-
config;
|
|
1433
|
-
constructor(projectPath, config) {
|
|
1434
|
-
this.projectPath = projectPath;
|
|
1435
|
-
this.config = config;
|
|
1436
|
-
}
|
|
1437
|
-
// --- Static utility methods -----------------------------------------------
|
|
1438
|
-
static calculateMovingAverage(data, windowSize) {
|
|
1439
|
-
return data.map((_, i) => {
|
|
1440
|
-
const start = Math.max(0, i - windowSize + 1);
|
|
1441
|
-
const window = data.slice(start, i + 1);
|
|
1442
|
-
return window.reduce((s, p) => s + p.score, 0) / window.length;
|
|
1443
|
-
});
|
|
1444
|
-
}
|
|
1445
|
-
static linearRegression(data) {
|
|
1446
|
-
const n = data.length;
|
|
1447
|
-
if (n < 2)
|
|
1448
|
-
return { slope: 0, intercept: data[0]?.score ?? 0, r2: 0 };
|
|
1449
|
-
const xs = data.map((_, i) => i);
|
|
1450
|
-
const ys = data.map(p => p.score);
|
|
1451
|
-
const xMean = xs.reduce((s, x) => s + x, 0) / n;
|
|
1452
|
-
const yMean = ys.reduce((s, y) => s + y, 0) / n;
|
|
1453
|
-
const ssXX = xs.reduce((s, x) => s + (x - xMean) ** 2, 0);
|
|
1454
|
-
const ssXY = xs.reduce((s, x, i) => s + (x - xMean) * (ys[i] - yMean), 0);
|
|
1455
|
-
const ssYY = ys.reduce((s, y) => s + (y - yMean) ** 2, 0);
|
|
1456
|
-
const slope = ssXX === 0 ? 0 : ssXY / ssXX;
|
|
1457
|
-
const intercept = yMean - slope * xMean;
|
|
1458
|
-
const r2 = ssYY === 0 ? 1 : (ssXY ** 2) / (ssXX * ssYY);
|
|
1459
|
-
return { slope, intercept, r2 };
|
|
1460
|
-
}
|
|
1461
|
-
/** Generate a simple horizontal ASCII bar chart (one bar per data point). */
|
|
1462
|
-
static generateTrendChart(data) {
|
|
1463
|
-
if (data.length === 0)
|
|
1464
|
-
return '(no data)';
|
|
1465
|
-
const maxScore = Math.max(...data.map(p => p.score), 1);
|
|
1466
|
-
const chartWidth = 40;
|
|
1467
|
-
const lines = data.map(p => {
|
|
1468
|
-
const barLen = Math.round((p.score / maxScore) * chartWidth);
|
|
1469
|
-
const bar = '█'.repeat(barLen);
|
|
1470
|
-
const dateStr = p.date.toISOString().slice(0, 10);
|
|
1471
|
-
return `${dateStr} │${bar.padEnd(chartWidth)} ${p.score.toFixed(1)}`;
|
|
1472
|
-
});
|
|
1473
|
-
return lines.join('\n');
|
|
1474
|
-
}
|
|
1475
|
-
// --- Instance method -------------------------------------------------------
|
|
1476
|
-
async analyzeTrend(options) {
|
|
1477
|
-
assertGitRepo(this.projectPath);
|
|
1478
|
-
const periodDays = {
|
|
1479
|
-
week: 7, month: 30, quarter: 90, year: 365,
|
|
1480
|
-
};
|
|
1481
|
-
const days = periodDays[options.period ?? 'month'] ?? 30;
|
|
1482
|
-
const sinceDate = options.since
|
|
1483
|
-
? new Date(options.since)
|
|
1484
|
-
: new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
|
1485
|
-
const historicalAnalyses = await analyzeHistoricalCommits(sinceDate, this.projectPath, 100);
|
|
1486
|
-
const trendPoints = historicalAnalyses.map(h => ({
|
|
1487
|
-
date: h.commitDate,
|
|
1488
|
-
score: h.averageScore,
|
|
1489
|
-
fileCount: h.files.length,
|
|
1490
|
-
avgIssuesPerFile: h.files.length > 0
|
|
1491
|
-
? h.files.reduce((s, f) => s + f.issues.length, 0) / h.files.length
|
|
1492
|
-
: 0,
|
|
1493
|
-
}));
|
|
1494
|
-
const regression = TrendAnalyzer.linearRegression(trendPoints);
|
|
1495
|
-
// Current state report
|
|
1496
|
-
const currentFiles = analyzeProject(this.projectPath, this.config);
|
|
1497
|
-
const baseReport = buildReport(this.projectPath, currentFiles);
|
|
1498
|
-
return {
|
|
1499
|
-
...baseReport,
|
|
1500
|
-
trend: trendPoints,
|
|
1501
|
-
regression,
|
|
1502
|
-
};
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
function parseGitBlame(blameOutput) {
|
|
1506
|
-
const entries = [];
|
|
1507
|
-
const lines = blameOutput.split('\n');
|
|
1508
|
-
let i = 0;
|
|
1509
|
-
while (i < lines.length) {
|
|
1510
|
-
const headerLine = lines[i];
|
|
1511
|
-
if (!headerLine || headerLine.trim() === '') {
|
|
1512
|
-
i++;
|
|
1513
|
-
continue;
|
|
1514
|
-
}
|
|
1515
|
-
// Porcelain blame format: first line is "<hash> <orig-line> <final-line> [<num-lines>]"
|
|
1516
|
-
const headerMatch = headerLine.match(/^([0-9a-f]{40})\s/);
|
|
1517
|
-
if (!headerMatch) {
|
|
1518
|
-
i++;
|
|
1519
|
-
continue;
|
|
1520
|
-
}
|
|
1521
|
-
const hash = headerMatch[1];
|
|
1522
|
-
let author = '';
|
|
1523
|
-
let email = '';
|
|
1524
|
-
let codeLine = '';
|
|
1525
|
-
i++;
|
|
1526
|
-
while (i < lines.length && !lines[i].match(/^[0-9a-f]{40}\s/)) {
|
|
1527
|
-
const l = lines[i];
|
|
1528
|
-
if (l.startsWith('author '))
|
|
1529
|
-
author = l.slice(7).trim();
|
|
1530
|
-
else if (l.startsWith('author-mail '))
|
|
1531
|
-
email = l.slice(12).replace(/[<>]/g, '').trim();
|
|
1532
|
-
else if (l.startsWith('\t'))
|
|
1533
|
-
codeLine = l.slice(1);
|
|
1534
|
-
i++;
|
|
1535
|
-
}
|
|
1536
|
-
entries.push({ hash, author, email, line: codeLine });
|
|
1537
|
-
}
|
|
1538
|
-
return entries;
|
|
1539
|
-
}
|
|
1540
|
-
export class BlameAnalyzer {
|
|
1541
|
-
projectPath;
|
|
1542
|
-
config;
|
|
1543
|
-
constructor(projectPath, config) {
|
|
1544
|
-
this.projectPath = projectPath;
|
|
1545
|
-
this.config = config;
|
|
1546
|
-
}
|
|
1547
|
-
/** Blame a single file: returns per-author attribution. */
|
|
1548
|
-
static async analyzeFileBlame(filePath) {
|
|
1549
|
-
const dir = path.dirname(filePath);
|
|
1550
|
-
assertGitRepo(dir);
|
|
1551
|
-
const blameOutput = execGit(`git blame --porcelain "${filePath}"`, dir);
|
|
1552
|
-
const entries = parseGitBlame(blameOutput);
|
|
1553
|
-
// Analyse issues in the file
|
|
1554
|
-
const report = analyzeFilePath(filePath);
|
|
1555
|
-
// Map line numbers of issues to authors
|
|
1556
|
-
const issuesByLine = new Map();
|
|
1557
|
-
for (const issue of report.issues) {
|
|
1558
|
-
issuesByLine.set(issue.line, (issuesByLine.get(issue.line) ?? 0) + 1);
|
|
1559
|
-
}
|
|
1560
|
-
// Aggregate by author
|
|
1561
|
-
const byAuthor = new Map();
|
|
1562
|
-
entries.forEach((entry, idx) => {
|
|
1563
|
-
const key = entry.email || entry.author;
|
|
1564
|
-
if (!byAuthor.has(key)) {
|
|
1565
|
-
byAuthor.set(key, {
|
|
1566
|
-
author: entry.author,
|
|
1567
|
-
email: entry.email,
|
|
1568
|
-
commits: 0,
|
|
1569
|
-
linesChanged: 0,
|
|
1570
|
-
issuesIntroduced: 0,
|
|
1571
|
-
avgScoreImpact: 0,
|
|
1572
|
-
});
|
|
1573
|
-
}
|
|
1574
|
-
const attr = byAuthor.get(key);
|
|
1575
|
-
attr.linesChanged++;
|
|
1576
|
-
const lineNum = idx + 1;
|
|
1577
|
-
if (issuesByLine.has(lineNum)) {
|
|
1578
|
-
attr.issuesIntroduced += issuesByLine.get(lineNum);
|
|
1579
|
-
}
|
|
1580
|
-
});
|
|
1581
|
-
// Count unique commits per author
|
|
1582
|
-
const commitsByAuthor = new Map();
|
|
1583
|
-
for (const entry of entries) {
|
|
1584
|
-
const key = entry.email || entry.author;
|
|
1585
|
-
if (!commitsByAuthor.has(key))
|
|
1586
|
-
commitsByAuthor.set(key, new Set());
|
|
1587
|
-
commitsByAuthor.get(key).add(entry.hash);
|
|
1588
|
-
}
|
|
1589
|
-
const total = entries.length || 1;
|
|
1590
|
-
const results = [];
|
|
1591
|
-
for (const [key, attr] of byAuthor) {
|
|
1592
|
-
attr.commits = commitsByAuthor.get(key)?.size ?? 0;
|
|
1593
|
-
attr.avgScoreImpact = (attr.linesChanged / total) * report.score;
|
|
1594
|
-
results.push(attr);
|
|
1595
|
-
}
|
|
1596
|
-
return results.sort((a, b) => b.issuesIntroduced - a.issuesIntroduced);
|
|
1597
|
-
}
|
|
1598
|
-
/** Blame for a specific rule across all files in targetPath. */
|
|
1599
|
-
static async analyzeRuleBlame(rule, targetPath) {
|
|
1600
|
-
assertGitRepo(targetPath);
|
|
1601
|
-
const tsFiles = fs
|
|
1602
|
-
.readdirSync(targetPath, { recursive: true, encoding: 'utf8' })
|
|
1603
|
-
.filter((f) => (f.endsWith('.ts') || f.endsWith('.tsx')) && !f.includes('node_modules'))
|
|
1604
|
-
.map(f => path.join(targetPath, f));
|
|
1605
|
-
const combined = new Map();
|
|
1606
|
-
for (const file of tsFiles) {
|
|
1607
|
-
const report = analyzeFilePath(file);
|
|
1608
|
-
const ruleIssues = report.issues.filter(i => i.rule === rule);
|
|
1609
|
-
if (ruleIssues.length === 0)
|
|
1610
|
-
continue;
|
|
1611
|
-
let blameEntries = [];
|
|
1612
|
-
try {
|
|
1613
|
-
const blameOutput = execGit(`git blame --porcelain "${file}"`, targetPath);
|
|
1614
|
-
blameEntries = parseGitBlame(blameOutput);
|
|
1615
|
-
}
|
|
1616
|
-
catch {
|
|
1617
|
-
continue;
|
|
1618
|
-
}
|
|
1619
|
-
for (const issue of ruleIssues) {
|
|
1620
|
-
const entry = blameEntries[issue.line - 1];
|
|
1621
|
-
if (!entry)
|
|
1622
|
-
continue;
|
|
1623
|
-
const key = entry.email || entry.author;
|
|
1624
|
-
if (!combined.has(key)) {
|
|
1625
|
-
combined.set(key, {
|
|
1626
|
-
author: entry.author,
|
|
1627
|
-
email: entry.email,
|
|
1628
|
-
commits: 0,
|
|
1629
|
-
linesChanged: 0,
|
|
1630
|
-
issuesIntroduced: 0,
|
|
1631
|
-
avgScoreImpact: 0,
|
|
1632
|
-
});
|
|
1633
|
-
}
|
|
1634
|
-
const attr = combined.get(key);
|
|
1635
|
-
attr.issuesIntroduced++;
|
|
1636
|
-
attr.avgScoreImpact += RULE_WEIGHTS[rule]?.weight ?? 5;
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
return Array.from(combined.values()).sort((a, b) => b.issuesIntroduced - a.issuesIntroduced);
|
|
1640
|
-
}
|
|
1641
|
-
/** Overall blame across all files and rules. */
|
|
1642
|
-
static async analyzeOverallBlame(targetPath) {
|
|
1643
|
-
assertGitRepo(targetPath);
|
|
1644
|
-
const tsFiles = fs
|
|
1645
|
-
.readdirSync(targetPath, { recursive: true, encoding: 'utf8' })
|
|
1646
|
-
.filter((f) => (f.endsWith('.ts') || f.endsWith('.tsx')) && !f.includes('node_modules'))
|
|
1647
|
-
.map(f => path.join(targetPath, f));
|
|
1648
|
-
const combined = new Map();
|
|
1649
|
-
const commitsByAuthor = new Map();
|
|
1650
|
-
for (const file of tsFiles) {
|
|
1651
|
-
let blameEntries = [];
|
|
1652
|
-
try {
|
|
1653
|
-
const blameOutput = execGit(`git blame --porcelain "${file}"`, targetPath);
|
|
1654
|
-
blameEntries = parseGitBlame(blameOutput);
|
|
1655
|
-
}
|
|
1656
|
-
catch {
|
|
1657
|
-
continue;
|
|
1658
|
-
}
|
|
1659
|
-
const report = analyzeFilePath(file);
|
|
1660
|
-
const issuesByLine = new Map();
|
|
1661
|
-
for (const issue of report.issues) {
|
|
1662
|
-
issuesByLine.set(issue.line, (issuesByLine.get(issue.line) ?? 0) + 1);
|
|
1663
|
-
}
|
|
1664
|
-
blameEntries.forEach((entry, idx) => {
|
|
1665
|
-
const key = entry.email || entry.author;
|
|
1666
|
-
if (!combined.has(key)) {
|
|
1667
|
-
combined.set(key, {
|
|
1668
|
-
author: entry.author,
|
|
1669
|
-
email: entry.email,
|
|
1670
|
-
commits: 0,
|
|
1671
|
-
linesChanged: 0,
|
|
1672
|
-
issuesIntroduced: 0,
|
|
1673
|
-
avgScoreImpact: 0,
|
|
1674
|
-
});
|
|
1675
|
-
commitsByAuthor.set(key, new Set());
|
|
1676
|
-
}
|
|
1677
|
-
const attr = combined.get(key);
|
|
1678
|
-
attr.linesChanged++;
|
|
1679
|
-
commitsByAuthor.get(key).add(entry.hash);
|
|
1680
|
-
const lineNum = idx + 1;
|
|
1681
|
-
if (issuesByLine.has(lineNum)) {
|
|
1682
|
-
attr.issuesIntroduced += issuesByLine.get(lineNum);
|
|
1683
|
-
attr.avgScoreImpact += report.score * (1 / (blameEntries.length || 1));
|
|
1684
|
-
}
|
|
1685
|
-
});
|
|
1686
|
-
}
|
|
1687
|
-
for (const [key, attr] of combined) {
|
|
1688
|
-
attr.commits = commitsByAuthor.get(key)?.size ?? 0;
|
|
1689
|
-
}
|
|
1690
|
-
return Array.from(combined.values()).sort((a, b) => b.issuesIntroduced - a.issuesIntroduced);
|
|
1691
|
-
}
|
|
1692
|
-
// --- Instance method -------------------------------------------------------
|
|
1693
|
-
async analyzeBlame(options) {
|
|
1694
|
-
assertGitRepo(this.projectPath);
|
|
1695
|
-
let blame = [];
|
|
1696
|
-
const mode = options.target ?? 'overall';
|
|
1697
|
-
if (mode === 'file' && options.filePath) {
|
|
1698
|
-
blame = await BlameAnalyzer.analyzeFileBlame(options.filePath);
|
|
1699
|
-
}
|
|
1700
|
-
else if (mode === 'rule' && options.rule) {
|
|
1701
|
-
blame = await BlameAnalyzer.analyzeRuleBlame(options.rule, this.projectPath);
|
|
1702
|
-
}
|
|
1703
|
-
else {
|
|
1704
|
-
blame = await BlameAnalyzer.analyzeOverallBlame(this.projectPath);
|
|
1705
|
-
}
|
|
1706
|
-
if (options.top) {
|
|
1707
|
-
blame = blame.slice(0, options.top);
|
|
1708
|
-
}
|
|
1709
|
-
const currentFiles = analyzeProject(this.projectPath, this.config);
|
|
1710
|
-
const baseReport = buildReport(this.projectPath, currentFiles);
|
|
1711
|
-
return { ...baseReport, blame };
|
|
1712
|
-
}
|
|
1713
|
-
}
|
|
1714
289
|
//# sourceMappingURL=analyzer.js.map
|