@eduardbar/drift 0.9.1 → 1.1.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/actions/drift-scan/README.md +61 -0
- package/.github/actions/drift-scan/action.yml +65 -0
- package/.github/workflows/publish-vscode.yml +78 -0
- package/AGENTS.md +83 -23
- package/README.md +69 -2
- package/ROADMAP.md +130 -98
- package/dist/analyzer.d.ts +8 -38
- package/dist/analyzer.js +181 -1526
- package/dist/badge.js +40 -22
- package/dist/ci.js +32 -18
- package/dist/cli.js +125 -4
- package/dist/config.js +1 -1
- package/dist/diff.d.ts +0 -7
- package/dist/diff.js +26 -25
- package/dist/fix.d.ts +17 -0
- package/dist/fix.js +132 -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 +81 -0
- package/dist/git.d.ts +0 -13
- package/dist/git.js +27 -21
- package/dist/index.d.ts +5 -1
- package/dist/index.js +3 -0
- package/dist/map.d.ts +3 -0
- package/dist/map.js +103 -0
- package/dist/metrics.d.ts +4 -0
- package/dist/metrics.js +176 -0
- package/dist/plugins.d.ts +6 -0
- package/dist/plugins.js +74 -0
- package/dist/printer.js +20 -0
- package/dist/report.js +654 -293
- package/dist/reporter.js +85 -2
- package/dist/review.d.ts +15 -0
- package/dist/review.js +80 -0
- package/dist/rules/comments.d.ts +4 -0
- package/dist/rules/comments.js +45 -0
- package/dist/rules/complexity.d.ts +4 -0
- package/dist/rules/complexity.js +51 -0
- package/dist/rules/coupling.d.ts +4 -0
- package/dist/rules/coupling.js +19 -0
- package/dist/rules/magic.d.ts +4 -0
- package/dist/rules/magic.js +33 -0
- package/dist/rules/nesting.d.ts +5 -0
- package/dist/rules/nesting.js +82 -0
- package/dist/rules/phase0-basic.d.ts +11 -0
- package/dist/rules/phase0-basic.js +183 -0
- package/dist/rules/phase1-complexity.d.ts +7 -0
- package/dist/rules/phase1-complexity.js +8 -0
- package/dist/rules/phase2-crossfile.d.ts +23 -0
- package/dist/rules/phase2-crossfile.js +135 -0
- package/dist/rules/phase3-arch.d.ts +23 -0
- package/dist/rules/phase3-arch.js +151 -0
- package/dist/rules/phase3-configurable.d.ts +6 -0
- package/dist/rules/phase3-configurable.js +97 -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 +17 -0
- package/dist/rules/phase8-semantic.js +110 -0
- package/dist/rules/promise.d.ts +4 -0
- package/dist/rules/promise.js +24 -0
- package/dist/rules/shared.d.ts +7 -0
- package/dist/rules/shared.js +27 -0
- package/dist/snapshot.d.ts +19 -0
- package/dist/snapshot.js +119 -0
- package/dist/types.d.ts +69 -0
- package/dist/utils.d.ts +2 -1
- package/dist/utils.js +1 -0
- package/docs/AGENTS.md +146 -0
- package/docs/PRD.md +208 -0
- package/package.json +8 -3
- package/packages/eslint-plugin-drift/src/index.ts +1 -1
- 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 +40 -0
- package/packages/vscode-drift/src/diagnostics.ts +55 -0
- package/packages/vscode-drift/src/extension.ts +135 -0
- package/packages/vscode-drift/src/statusbar.ts +55 -0
- package/packages/vscode-drift/src/treeview.ts +110 -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 +248 -1765
- package/src/badge.ts +38 -16
- package/src/ci.ts +38 -17
- package/src/cli.ts +143 -4
- package/src/config.ts +1 -1
- package/src/diff.ts +36 -30
- package/src/fix.ts +178 -0
- package/src/git/blame.ts +279 -0
- package/src/git/helpers.ts +198 -0
- package/src/git/trend.ts +117 -0
- package/src/git.ts +33 -24
- package/src/index.ts +16 -1
- package/src/map.ts +117 -0
- package/src/metrics.ts +200 -0
- package/src/plugins.ts +76 -0
- package/src/printer.ts +20 -0
- package/src/report.ts +666 -296
- package/src/reporter.ts +95 -2
- package/src/review.ts +98 -0
- package/src/rules/comments.ts +56 -0
- package/src/rules/complexity.ts +57 -0
- package/src/rules/coupling.ts +23 -0
- package/src/rules/magic.ts +38 -0
- package/src/rules/nesting.ts +88 -0
- package/src/rules/phase0-basic.ts +194 -0
- package/src/rules/phase1-complexity.ts +8 -0
- package/src/rules/phase2-crossfile.ts +177 -0
- package/src/rules/phase3-arch.ts +183 -0
- package/src/rules/phase3-configurable.ts +132 -0
- package/src/rules/phase5-ai.ts +292 -0
- package/src/rules/phase8-semantic.ts +136 -0
- package/src/rules/promise.ts +29 -0
- package/src/rules/shared.ts +39 -0
- package/src/snapshot.ts +175 -0
- package/src/types.ts +75 -1
- package/src/utils.ts +3 -1
- package/tests/helpers.ts +45 -0
- package/tests/new-features.test.ts +153 -0
- package/tests/rules.test.ts +1269 -0
- package/vitest.config.ts +15 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// drift-ignore-file
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { assertGitRepo, execGit, analyzeFilePath } from './helpers.js';
|
|
5
|
+
import { buildReport } from '../reporter.js';
|
|
6
|
+
function parseGitBlame(blameOutput) {
|
|
7
|
+
const entries = [];
|
|
8
|
+
const lines = blameOutput.split('\n');
|
|
9
|
+
let i = 0;
|
|
10
|
+
while (i < lines.length) {
|
|
11
|
+
const headerLine = lines[i];
|
|
12
|
+
if (!headerLine || headerLine.trim() === '') {
|
|
13
|
+
i++;
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
// Porcelain blame format: first line is "<hash> <orig-line> <final-line> [<num-lines>]"
|
|
17
|
+
const headerMatch = headerLine.match(/^([0-9a-f]{40})\s/);
|
|
18
|
+
if (!headerMatch) {
|
|
19
|
+
i++;
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const hash = headerMatch[1];
|
|
23
|
+
let author = '';
|
|
24
|
+
let email = '';
|
|
25
|
+
let codeLine = '';
|
|
26
|
+
i++;
|
|
27
|
+
while (i < lines.length && !lines[i].match(/^[0-9a-f]{40}\s/)) {
|
|
28
|
+
const l = lines[i];
|
|
29
|
+
if (l.startsWith('author '))
|
|
30
|
+
author = l.slice(7).trim();
|
|
31
|
+
else if (l.startsWith('author-mail '))
|
|
32
|
+
email = l.slice(12).replace(/[<>]/g, '').trim();
|
|
33
|
+
else if (l.startsWith('\t'))
|
|
34
|
+
codeLine = l.slice(1);
|
|
35
|
+
i++;
|
|
36
|
+
}
|
|
37
|
+
entries.push({ hash, author, email, line: codeLine });
|
|
38
|
+
}
|
|
39
|
+
return entries;
|
|
40
|
+
}
|
|
41
|
+
export class BlameAnalyzer {
|
|
42
|
+
projectPath;
|
|
43
|
+
config;
|
|
44
|
+
analyzeProjectFn;
|
|
45
|
+
analyzeFileFn;
|
|
46
|
+
constructor(projectPath, analyzeProjectFn, analyzeFileFn, config) {
|
|
47
|
+
this.projectPath = projectPath;
|
|
48
|
+
this.analyzeProjectFn = analyzeProjectFn;
|
|
49
|
+
this.analyzeFileFn = analyzeFileFn;
|
|
50
|
+
this.config = config;
|
|
51
|
+
}
|
|
52
|
+
/** Blame a single file: returns per-author attribution. */
|
|
53
|
+
static async analyzeFileBlame(filePath, analyzeFileFn) {
|
|
54
|
+
const dir = path.dirname(filePath);
|
|
55
|
+
assertGitRepo(dir);
|
|
56
|
+
const blameOutput = execGit(`git blame --porcelain "${filePath}"`, dir);
|
|
57
|
+
const entries = parseGitBlame(blameOutput);
|
|
58
|
+
// Analyse issues in the file
|
|
59
|
+
const report = analyzeFilePath(filePath, analyzeFileFn);
|
|
60
|
+
// Map line numbers of issues to authors
|
|
61
|
+
const issuesByLine = new Map();
|
|
62
|
+
for (const issue of report.issues) {
|
|
63
|
+
issuesByLine.set(issue.line, (issuesByLine.get(issue.line) ?? 0) + 1);
|
|
64
|
+
}
|
|
65
|
+
// Aggregate by author
|
|
66
|
+
const byAuthor = new Map();
|
|
67
|
+
entries.forEach((entry, idx) => {
|
|
68
|
+
const key = entry.email || entry.author;
|
|
69
|
+
if (!byAuthor.has(key)) {
|
|
70
|
+
byAuthor.set(key, {
|
|
71
|
+
author: entry.author,
|
|
72
|
+
email: entry.email,
|
|
73
|
+
commits: 0,
|
|
74
|
+
linesChanged: 0,
|
|
75
|
+
issuesIntroduced: 0,
|
|
76
|
+
avgScoreImpact: 0,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const attr = byAuthor.get(key);
|
|
80
|
+
attr.linesChanged++;
|
|
81
|
+
const lineNum = idx + 1;
|
|
82
|
+
if (issuesByLine.has(lineNum)) {
|
|
83
|
+
attr.issuesIntroduced += issuesByLine.get(lineNum);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
// Count unique commits per author
|
|
87
|
+
const commitsByAuthor = new Map();
|
|
88
|
+
for (const entry of entries) {
|
|
89
|
+
const key = entry.email || entry.author;
|
|
90
|
+
if (!commitsByAuthor.has(key))
|
|
91
|
+
commitsByAuthor.set(key, new Set());
|
|
92
|
+
commitsByAuthor.get(key).add(entry.hash);
|
|
93
|
+
}
|
|
94
|
+
const total = entries.length || 1;
|
|
95
|
+
const results = [];
|
|
96
|
+
for (const [key, attr] of byAuthor) {
|
|
97
|
+
attr.commits = commitsByAuthor.get(key)?.size ?? 0;
|
|
98
|
+
attr.avgScoreImpact = (attr.linesChanged / total) * report.score;
|
|
99
|
+
results.push(attr);
|
|
100
|
+
}
|
|
101
|
+
return results.sort((a, b) => b.issuesIntroduced - a.issuesIntroduced);
|
|
102
|
+
}
|
|
103
|
+
/** Blame for a specific rule across all files in targetPath. */
|
|
104
|
+
static async analyzeRuleBlame(rule, targetPath, analyzeFileFn) {
|
|
105
|
+
assertGitRepo(targetPath);
|
|
106
|
+
const tsFiles = fs
|
|
107
|
+
.readdirSync(targetPath, { recursive: true, encoding: 'utf8' })
|
|
108
|
+
.filter((f) => (f.endsWith('.ts') || f.endsWith('.tsx') || f.endsWith('.js') || f.endsWith('.jsx')) && !f.includes('node_modules') && !f.endsWith('.d.ts'))
|
|
109
|
+
.map(f => path.join(targetPath, f));
|
|
110
|
+
const combined = new Map();
|
|
111
|
+
const commitsByAuthor = new Map();
|
|
112
|
+
for (const file of tsFiles) {
|
|
113
|
+
let blameEntries = [];
|
|
114
|
+
try {
|
|
115
|
+
const blameOutput = execGit(`git blame --porcelain "${file}"`, targetPath);
|
|
116
|
+
blameEntries = parseGitBlame(blameOutput);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const report = analyzeFilePath(file, analyzeFileFn);
|
|
122
|
+
const issuesByLine = new Map();
|
|
123
|
+
for (const issue of report.issues) {
|
|
124
|
+
issuesByLine.set(issue.line, (issuesByLine.get(issue.line) ?? 0) + 1);
|
|
125
|
+
}
|
|
126
|
+
blameEntries.forEach((entry, idx) => {
|
|
127
|
+
const key = entry.email || entry.author;
|
|
128
|
+
if (!combined.has(key)) {
|
|
129
|
+
combined.set(key, {
|
|
130
|
+
author: entry.author,
|
|
131
|
+
email: entry.email,
|
|
132
|
+
commits: 0,
|
|
133
|
+
linesChanged: 0,
|
|
134
|
+
issuesIntroduced: 0,
|
|
135
|
+
avgScoreImpact: 0,
|
|
136
|
+
});
|
|
137
|
+
commitsByAuthor.set(key, new Set());
|
|
138
|
+
}
|
|
139
|
+
const attr = combined.get(key);
|
|
140
|
+
attr.linesChanged++;
|
|
141
|
+
commitsByAuthor.get(key).add(entry.hash);
|
|
142
|
+
const lineNum = idx + 1;
|
|
143
|
+
if (issuesByLine.has(lineNum)) {
|
|
144
|
+
attr.issuesIntroduced += issuesByLine.get(lineNum);
|
|
145
|
+
attr.avgScoreImpact += report.score * (1 / (blameEntries.length || 1));
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
for (const [key, attr] of combined) {
|
|
150
|
+
attr.commits = commitsByAuthor.get(key)?.size ?? 0;
|
|
151
|
+
}
|
|
152
|
+
return Array.from(combined.values()).sort((a, b) => b.issuesIntroduced - a.issuesIntroduced);
|
|
153
|
+
}
|
|
154
|
+
/** Overall blame across all files and rules. */
|
|
155
|
+
static async analyzeOverallBlame(targetPath, analyzeFileFn) {
|
|
156
|
+
assertGitRepo(targetPath);
|
|
157
|
+
const tsFiles = fs
|
|
158
|
+
.readdirSync(targetPath, { recursive: true, encoding: 'utf8' })
|
|
159
|
+
.filter((f) => (f.endsWith('.ts') || f.endsWith('.tsx') || f.endsWith('.js') || f.endsWith('.jsx')) && !f.includes('node_modules') && !f.endsWith('.d.ts'))
|
|
160
|
+
.map(f => path.join(targetPath, f));
|
|
161
|
+
const combined = new Map();
|
|
162
|
+
const commitsByAuthor = new Map();
|
|
163
|
+
for (const file of tsFiles) {
|
|
164
|
+
let blameEntries = [];
|
|
165
|
+
try {
|
|
166
|
+
const blameOutput = execGit(`git blame --porcelain "${file}"`, targetPath);
|
|
167
|
+
blameEntries = parseGitBlame(blameOutput);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const report = analyzeFilePath(file, analyzeFileFn);
|
|
173
|
+
const issuesByLine = new Map();
|
|
174
|
+
for (const issue of report.issues) {
|
|
175
|
+
issuesByLine.set(issue.line, (issuesByLine.get(issue.line) ?? 0) + 1);
|
|
176
|
+
}
|
|
177
|
+
blameEntries.forEach((entry, idx) => {
|
|
178
|
+
const key = entry.email || entry.author;
|
|
179
|
+
if (!combined.has(key)) {
|
|
180
|
+
combined.set(key, {
|
|
181
|
+
author: entry.author,
|
|
182
|
+
email: entry.email,
|
|
183
|
+
commits: 0,
|
|
184
|
+
linesChanged: 0,
|
|
185
|
+
issuesIntroduced: 0,
|
|
186
|
+
avgScoreImpact: 0,
|
|
187
|
+
});
|
|
188
|
+
commitsByAuthor.set(key, new Set());
|
|
189
|
+
}
|
|
190
|
+
const attr = combined.get(key);
|
|
191
|
+
attr.linesChanged++;
|
|
192
|
+
commitsByAuthor.get(key).add(entry.hash);
|
|
193
|
+
const lineNum = idx + 1;
|
|
194
|
+
if (issuesByLine.has(lineNum)) {
|
|
195
|
+
attr.issuesIntroduced += issuesByLine.get(lineNum);
|
|
196
|
+
attr.avgScoreImpact += report.score * (1 / (blameEntries.length || 1));
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
for (const [key, attr] of combined) {
|
|
201
|
+
attr.commits = commitsByAuthor.get(key)?.size ?? 0;
|
|
202
|
+
}
|
|
203
|
+
return Array.from(combined.values()).sort((a, b) => b.issuesIntroduced - a.issuesIntroduced);
|
|
204
|
+
}
|
|
205
|
+
// --- Instance method -------------------------------------------------------
|
|
206
|
+
async analyzeBlame(options) {
|
|
207
|
+
assertGitRepo(this.projectPath);
|
|
208
|
+
let blame = [];
|
|
209
|
+
const mode = options.target ?? 'overall';
|
|
210
|
+
if (mode === 'file' && options.filePath) {
|
|
211
|
+
blame = await BlameAnalyzer.analyzeFileBlame(options.filePath, this.analyzeFileFn);
|
|
212
|
+
}
|
|
213
|
+
else if (mode === 'rule' && options.rule) {
|
|
214
|
+
blame = await BlameAnalyzer.analyzeRuleBlame(options.rule, this.projectPath, this.analyzeFileFn);
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
blame = await BlameAnalyzer.analyzeOverallBlame(this.projectPath, this.analyzeFileFn);
|
|
218
|
+
}
|
|
219
|
+
if (options.top) {
|
|
220
|
+
blame = blame.slice(0, options.top);
|
|
221
|
+
}
|
|
222
|
+
const currentFiles = this.analyzeProjectFn(this.projectPath, this.config);
|
|
223
|
+
const baseReport = buildReport(this.projectPath, currentFiles);
|
|
224
|
+
return { ...baseReport, blame };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
//# sourceMappingURL=blame.js.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { SourceFile } from 'ts-morph';
|
|
2
|
+
import type { FileReport, DriftConfig, HistoricalAnalysis } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Analyse a file given its absolute path string.
|
|
5
|
+
* Accepts analyzeFile as a parameter to avoid circular dependency.
|
|
6
|
+
*/
|
|
7
|
+
export declare function analyzeFilePath(filePath: string, analyzeFile: (sf: SourceFile) => FileReport): FileReport;
|
|
8
|
+
/**
|
|
9
|
+
* Execute a git command synchronously and return stdout.
|
|
10
|
+
* Throws a descriptive error if the command fails or git is not available.
|
|
11
|
+
*/
|
|
12
|
+
export declare function execGit(cmd: string, cwd: string): string;
|
|
13
|
+
/**
|
|
14
|
+
* Verify the given directory is a git repository.
|
|
15
|
+
* Throws if git is not available or the directory is not a repo.
|
|
16
|
+
*/
|
|
17
|
+
export declare function assertGitRepo(cwd: string): void;
|
|
18
|
+
/**
|
|
19
|
+
* Analyse a single file as it existed at a given commit hash.
|
|
20
|
+
* Writes the blob to a temp file, runs analyzeFile, then cleans up.
|
|
21
|
+
*/
|
|
22
|
+
export declare function analyzeFileAtCommit(// drift-ignore
|
|
23
|
+
filePath: string, commitHash: string, projectRoot: string, analyzeFile: (sf: SourceFile) => FileReport): Promise<FileReport>;
|
|
24
|
+
/**
|
|
25
|
+
* Analyse ALL TypeScript files in the project snapshot at a given commit.
|
|
26
|
+
* Uses `git ls-tree` to enumerate every file in the tree, writes them to a
|
|
27
|
+
* temp directory, then runs `analyzeProject` on that full snapshot.
|
|
28
|
+
*/
|
|
29
|
+
export declare function analyzeSingleCommit(// drift-ignore
|
|
30
|
+
commitHash: string, targetPath: string, analyzeProject: (targetPath: string, config?: DriftConfig) => FileReport[], config?: DriftConfig): Promise<HistoricalAnalysis>;
|
|
31
|
+
/**
|
|
32
|
+
* Run historical analysis over all commits since a given date.
|
|
33
|
+
* Returns results ordered chronologically (oldest first).
|
|
34
|
+
*/
|
|
35
|
+
export declare function analyzeHistoricalCommits(sinceDate: Date, targetPath: string, maxCommits: number, analyzeProject: (targetPath: string, config?: DriftConfig) => FileReport[], config?: DriftConfig, maxSamples?: number): Promise<HistoricalAnalysis[]>;
|
|
36
|
+
//# sourceMappingURL=helpers.d.ts.map
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// drift-ignore-file
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import * as os from 'node:os';
|
|
5
|
+
import * as crypto from 'node:crypto';
|
|
6
|
+
import { execSync } from 'node:child_process';
|
|
7
|
+
import { Project } from 'ts-morph';
|
|
8
|
+
/**
|
|
9
|
+
* Analyse a file given its absolute path string.
|
|
10
|
+
* Accepts analyzeFile as a parameter to avoid circular dependency.
|
|
11
|
+
*/
|
|
12
|
+
export function analyzeFilePath(filePath, analyzeFile) {
|
|
13
|
+
const proj = new Project({
|
|
14
|
+
skipAddingFilesFromTsConfig: true,
|
|
15
|
+
compilerOptions: { allowJs: true },
|
|
16
|
+
});
|
|
17
|
+
const sf = proj.addSourceFileAtPath(filePath);
|
|
18
|
+
return analyzeFile(sf);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Execute a git command synchronously and return stdout.
|
|
22
|
+
* Throws a descriptive error if the command fails or git is not available.
|
|
23
|
+
*/
|
|
24
|
+
export function execGit(cmd, cwd) {
|
|
25
|
+
try {
|
|
26
|
+
return execSync(cmd, { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
30
|
+
throw new Error(`Git command failed: ${cmd}\n${msg}`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Verify the given directory is a git repository.
|
|
35
|
+
* Throws if git is not available or the directory is not a repo.
|
|
36
|
+
*/
|
|
37
|
+
export function assertGitRepo(cwd) {
|
|
38
|
+
try {
|
|
39
|
+
execGit('git rev-parse --is-inside-work-tree', cwd);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new Error(`Directory is not a git repository: ${cwd}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Analyse a single file as it existed at a given commit hash.
|
|
47
|
+
* Writes the blob to a temp file, runs analyzeFile, then cleans up.
|
|
48
|
+
*/
|
|
49
|
+
export async function analyzeFileAtCommit(// drift-ignore
|
|
50
|
+
filePath, commitHash, projectRoot, analyzeFile) {
|
|
51
|
+
const relPath = path.relative(projectRoot, filePath).replace(/\\/g, '/');
|
|
52
|
+
const blob = execGit(`git show ${commitHash}:${relPath}`, projectRoot);
|
|
53
|
+
const tmpFile = path.join(os.tmpdir(), `drift-${crypto.randomBytes(8).toString('hex')}.ts`);
|
|
54
|
+
try {
|
|
55
|
+
fs.writeFileSync(tmpFile, blob, 'utf8');
|
|
56
|
+
const report = analyzeFilePath(tmpFile, analyzeFile);
|
|
57
|
+
// Replace temp path with original for readable output
|
|
58
|
+
return { ...report, path: filePath };
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
try {
|
|
62
|
+
fs.unlinkSync(tmpFile);
|
|
63
|
+
}
|
|
64
|
+
catch { /* ignore cleanup errors */ } // drift-ignore
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Analyse ALL TypeScript files in the project snapshot at a given commit.
|
|
69
|
+
* Uses `git ls-tree` to enumerate every file in the tree, writes them to a
|
|
70
|
+
* temp directory, then runs `analyzeProject` on that full snapshot.
|
|
71
|
+
*/
|
|
72
|
+
export async function analyzeSingleCommit(// drift-ignore
|
|
73
|
+
commitHash, targetPath, analyzeProject, config) {
|
|
74
|
+
// 1. Commit metadata
|
|
75
|
+
const meta = execGit(`git show --no-patch --format="%H|%aI|%an|%s" ${commitHash}`, targetPath);
|
|
76
|
+
const [hash, dateStr, author, ...msgParts] = meta.split('|');
|
|
77
|
+
const message = msgParts.join('|').trim();
|
|
78
|
+
const commitDate = new Date(dateStr ?? '');
|
|
79
|
+
// 2. All .ts/.tsx files tracked at this commit (no diffs, full tree)
|
|
80
|
+
const allFiles = execGit(`git ls-tree -r ${commitHash} --name-only`, targetPath)
|
|
81
|
+
.split('\n')
|
|
82
|
+
.filter(f => (f.endsWith('.ts') || f.endsWith('.tsx') || f.endsWith('.js') || f.endsWith('.jsx')) &&
|
|
83
|
+
!f.endsWith('.d.ts') &&
|
|
84
|
+
!f.includes('node_modules') &&
|
|
85
|
+
!f.startsWith('dist/'));
|
|
86
|
+
if (allFiles.length === 0) {
|
|
87
|
+
return {
|
|
88
|
+
commitHash: hash ?? commitHash,
|
|
89
|
+
commitDate,
|
|
90
|
+
author: author ?? '',
|
|
91
|
+
message,
|
|
92
|
+
files: [],
|
|
93
|
+
totalScore: 0,
|
|
94
|
+
averageScore: 0,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
// 3. Write snapshot to temp directory
|
|
98
|
+
const tmpDir = path.join(os.tmpdir(), `drift-${(hash ?? commitHash).slice(0, 8)}`);
|
|
99
|
+
fs.mkdirSync(tmpDir, { recursive: true });
|
|
100
|
+
for (const relPath of allFiles) {
|
|
101
|
+
try {
|
|
102
|
+
const content = execGit(`git show ${commitHash}:${relPath}`, targetPath);
|
|
103
|
+
const destPath = path.join(tmpDir, relPath);
|
|
104
|
+
fs.mkdirSync(path.dirname(destPath), { recursive: true });
|
|
105
|
+
fs.writeFileSync(destPath, content, 'utf-8');
|
|
106
|
+
}
|
|
107
|
+
catch { // drift-ignore
|
|
108
|
+
// skip files that can't be read (binary, deleted in partial clone, etc.)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// 4. Analyse the full project snapshot
|
|
112
|
+
const fileReports = analyzeProject(tmpDir, config);
|
|
113
|
+
const totalScore = fileReports.reduce((sum, r) => sum + r.score, 0);
|
|
114
|
+
const averageScore = fileReports.length > 0 ? totalScore / fileReports.length : 0;
|
|
115
|
+
// 5. Cleanup
|
|
116
|
+
try {
|
|
117
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
catch { // drift-ignore
|
|
120
|
+
// non-fatal — temp dirs are cleaned by the OS eventually
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
commitHash: hash ?? commitHash,
|
|
124
|
+
commitDate,
|
|
125
|
+
author: author ?? '',
|
|
126
|
+
message,
|
|
127
|
+
files: fileReports,
|
|
128
|
+
totalScore,
|
|
129
|
+
averageScore,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Run historical analysis over all commits since a given date.
|
|
134
|
+
* Returns results ordered chronologically (oldest first).
|
|
135
|
+
*/
|
|
136
|
+
export async function analyzeHistoricalCommits(sinceDate, targetPath, maxCommits, analyzeProject, config, maxSamples = 10) {
|
|
137
|
+
assertGitRepo(targetPath);
|
|
138
|
+
const isoDate = sinceDate.toISOString();
|
|
139
|
+
const raw = execGit(`git log --since="${isoDate}" --format="%H" --max-count=${maxCommits}`, targetPath);
|
|
140
|
+
if (!raw)
|
|
141
|
+
return [];
|
|
142
|
+
const hashes = raw.split('\n').filter(Boolean);
|
|
143
|
+
// Sample: distribute evenly across the range
|
|
144
|
+
const sampled = hashes.length <= maxSamples
|
|
145
|
+
? hashes
|
|
146
|
+
: Array.from({ length: maxSamples }, (_, i) => hashes[Math.floor(i * (hashes.length - 1) / (maxSamples - 1))]);
|
|
147
|
+
const analyses = await Promise.all(sampled.map(h => analyzeSingleCommit(h, targetPath, analyzeProject, config).catch(() => null)));
|
|
148
|
+
return analyses
|
|
149
|
+
.filter((a) => a !== null)
|
|
150
|
+
.sort((a, b) => a.commitDate.getTime() - b.commitDate.getTime());
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=helpers.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FileReport, DriftConfig, TrendDataPoint, DriftTrendReport } from '../types.js';
|
|
2
|
+
export declare class TrendAnalyzer {
|
|
3
|
+
private readonly projectPath;
|
|
4
|
+
private readonly config;
|
|
5
|
+
private readonly analyzeProjectFn;
|
|
6
|
+
constructor(projectPath: string, analyzeProjectFn: (targetPath: string, config?: DriftConfig) => FileReport[], config?: DriftConfig);
|
|
7
|
+
static calculateMovingAverage(data: TrendDataPoint[], windowSize: number): number[];
|
|
8
|
+
static linearRegression(data: TrendDataPoint[]): {
|
|
9
|
+
slope: number;
|
|
10
|
+
intercept: number;
|
|
11
|
+
r2: number;
|
|
12
|
+
};
|
|
13
|
+
/** Generate a simple horizontal ASCII bar chart (one bar per data point). */
|
|
14
|
+
static generateTrendChart(data: TrendDataPoint[]): string;
|
|
15
|
+
analyzeTrend(options: {
|
|
16
|
+
period?: 'week' | 'month' | 'quarter' | 'year';
|
|
17
|
+
since?: string;
|
|
18
|
+
until?: string;
|
|
19
|
+
}): Promise<DriftTrendReport>;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=trend.d.ts.map
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// drift-ignore-file
|
|
2
|
+
import { assertGitRepo, analyzeHistoricalCommits } from './helpers.js';
|
|
3
|
+
import { buildReport } from '../reporter.js';
|
|
4
|
+
export class TrendAnalyzer {
|
|
5
|
+
projectPath;
|
|
6
|
+
config;
|
|
7
|
+
analyzeProjectFn;
|
|
8
|
+
constructor(projectPath, analyzeProjectFn, config) {
|
|
9
|
+
this.projectPath = projectPath;
|
|
10
|
+
this.analyzeProjectFn = analyzeProjectFn;
|
|
11
|
+
this.config = config;
|
|
12
|
+
}
|
|
13
|
+
// --- Static utility methods -----------------------------------------------
|
|
14
|
+
static calculateMovingAverage(data, windowSize) {
|
|
15
|
+
return data.map((_, i) => {
|
|
16
|
+
const start = Math.max(0, i - windowSize + 1);
|
|
17
|
+
const window = data.slice(start, i + 1);
|
|
18
|
+
return window.reduce((s, p) => s + p.score, 0) / window.length;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
static linearRegression(data) {
|
|
22
|
+
const n = data.length;
|
|
23
|
+
if (n < 2)
|
|
24
|
+
return { slope: 0, intercept: data[0]?.score ?? 0, r2: 0 };
|
|
25
|
+
const xs = data.map((_, i) => i);
|
|
26
|
+
const ys = data.map(p => p.score);
|
|
27
|
+
const xMean = xs.reduce((s, x) => s + x, 0) / n;
|
|
28
|
+
const yMean = ys.reduce((s, y) => s + y, 0) / n;
|
|
29
|
+
const ssXX = xs.reduce((s, x) => s + (x - xMean) ** 2, 0);
|
|
30
|
+
const ssXY = xs.reduce((s, x, i) => s + (x - xMean) * (ys[i] - yMean), 0);
|
|
31
|
+
const ssYY = ys.reduce((s, y) => s + (y - yMean) ** 2, 0);
|
|
32
|
+
const slope = ssXX === 0 ? 0 : ssXY / ssXX;
|
|
33
|
+
const intercept = yMean - slope * xMean;
|
|
34
|
+
const r2 = ssYY === 0 ? 1 : (ssXY ** 2) / (ssXX * ssYY);
|
|
35
|
+
return { slope, intercept, r2 };
|
|
36
|
+
}
|
|
37
|
+
/** Generate a simple horizontal ASCII bar chart (one bar per data point). */
|
|
38
|
+
static generateTrendChart(data) {
|
|
39
|
+
if (data.length === 0)
|
|
40
|
+
return '(no data)';
|
|
41
|
+
const maxScore = Math.max(...data.map(p => p.score), 1);
|
|
42
|
+
const chartWidth = 40;
|
|
43
|
+
const lines = data.map(p => {
|
|
44
|
+
const barLen = Math.round((p.score / maxScore) * chartWidth);
|
|
45
|
+
const bar = '█'.repeat(barLen);
|
|
46
|
+
const dateStr = p.date.toISOString().slice(0, 10);
|
|
47
|
+
return `${dateStr} │${bar.padEnd(chartWidth)} ${p.score.toFixed(1)}`;
|
|
48
|
+
});
|
|
49
|
+
return lines.join('\n');
|
|
50
|
+
}
|
|
51
|
+
// --- Instance method -------------------------------------------------------
|
|
52
|
+
async analyzeTrend(options) {
|
|
53
|
+
assertGitRepo(this.projectPath);
|
|
54
|
+
const periodDays = {
|
|
55
|
+
week: 7, month: 30, quarter: 90, year: 365,
|
|
56
|
+
};
|
|
57
|
+
const days = periodDays[options.period ?? 'month'] ?? 30;
|
|
58
|
+
const sinceDate = options.since
|
|
59
|
+
? new Date(options.since)
|
|
60
|
+
: new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
|
61
|
+
const historicalAnalyses = await analyzeHistoricalCommits(sinceDate, this.projectPath, 100, this.analyzeProjectFn, this.config, 10);
|
|
62
|
+
const trendPoints = historicalAnalyses.map(h => ({
|
|
63
|
+
date: h.commitDate,
|
|
64
|
+
score: h.averageScore,
|
|
65
|
+
fileCount: h.files.length,
|
|
66
|
+
avgIssuesPerFile: h.files.length > 0
|
|
67
|
+
? h.files.reduce((s, f) => s + f.issues.length, 0) / h.files.length
|
|
68
|
+
: 0,
|
|
69
|
+
}));
|
|
70
|
+
const regression = TrendAnalyzer.linearRegression(trendPoints);
|
|
71
|
+
// Current state report
|
|
72
|
+
const currentFiles = this.analyzeProjectFn(this.projectPath, this.config);
|
|
73
|
+
const baseReport = buildReport(this.projectPath, currentFiles);
|
|
74
|
+
return {
|
|
75
|
+
...baseReport,
|
|
76
|
+
trend: trendPoints,
|
|
77
|
+
regression,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=trend.js.map
|
package/dist/git.d.ts
CHANGED
|
@@ -1,19 +1,6 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Extract all TypeScript files from the project at a given git ref into a
|
|
3
|
-
* temporary directory. Returns the temp directory path.
|
|
4
|
-
*
|
|
5
|
-
* Uses `git ls-tree` to list files and `git show <ref>:<path>` to read each
|
|
6
|
-
* file — no checkout, no stash, no repo state mutation.
|
|
7
|
-
*
|
|
8
|
-
* Throws if the directory is not a git repo or the ref is invalid.
|
|
9
|
-
*/
|
|
10
1
|
export declare function extractFilesAtRef(projectPath: string, ref: string): string;
|
|
11
2
|
/**
|
|
12
3
|
* Clean up a temporary directory created by extractFilesAtRef.
|
|
13
4
|
*/
|
|
14
5
|
export declare function cleanupTempDir(tempDir: string): void;
|
|
15
|
-
/**
|
|
16
|
-
* Get the short hash of a git ref for display purposes.
|
|
17
|
-
*/
|
|
18
|
-
export declare function resolveRefHash(projectPath: string, ref: string): string;
|
|
19
6
|
//# sourceMappingURL=git.d.ts.map
|
package/dist/git.js
CHANGED
|
@@ -12,22 +12,23 @@ import { randomUUID } from 'node:crypto';
|
|
|
12
12
|
*
|
|
13
13
|
* Throws if the directory is not a git repo or the ref is invalid.
|
|
14
14
|
*/
|
|
15
|
-
|
|
16
|
-
// Verify git repo
|
|
15
|
+
function verifyGitRepo(projectPath) {
|
|
17
16
|
try {
|
|
18
17
|
execSync('git rev-parse --git-dir', { cwd: projectPath, stdio: 'pipe' });
|
|
19
18
|
}
|
|
20
19
|
catch {
|
|
21
20
|
throw new Error(`Not a git repository: ${projectPath}`);
|
|
22
21
|
}
|
|
23
|
-
|
|
22
|
+
}
|
|
23
|
+
function verifyRefExists(projectPath, ref) {
|
|
24
24
|
try {
|
|
25
25
|
execSync(`git rev-parse --verify ${ref}`, { cwd: projectPath, stdio: 'pipe' });
|
|
26
26
|
}
|
|
27
27
|
catch {
|
|
28
28
|
throw new Error(`Invalid git ref: '${ref}'. Run 'git log --oneline' to see available commits.`);
|
|
29
29
|
}
|
|
30
|
-
|
|
30
|
+
}
|
|
31
|
+
function listTsFilesAtRef(projectPath, ref) {
|
|
31
32
|
let fileList;
|
|
32
33
|
try {
|
|
33
34
|
fileList = execSync(`git ls-tree -r --name-only ${ref}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });
|
|
@@ -35,30 +36,35 @@ export function extractFilesAtRef(projectPath, ref) {
|
|
|
35
36
|
catch {
|
|
36
37
|
throw new Error(`Failed to list files at ref '${ref}'`);
|
|
37
38
|
}
|
|
38
|
-
|
|
39
|
+
return fileList
|
|
39
40
|
.split('\n')
|
|
40
41
|
.map(f => f.trim())
|
|
41
|
-
.filter(f => f.endsWith('.ts') && !f.endsWith('.d.ts'));
|
|
42
|
+
.filter(f => (f.endsWith('.ts') || f.endsWith('.tsx') || f.endsWith('.js') || f.endsWith('.jsx')) && !f.endsWith('.d.ts'));
|
|
43
|
+
}
|
|
44
|
+
function extractFile(projectPath, ref, filePath, tempDir) {
|
|
45
|
+
let content;
|
|
46
|
+
try {
|
|
47
|
+
content = execSync(`git show ${ref}:${filePath}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const destPath = join(tempDir, filePath.split('/').join(sep));
|
|
53
|
+
const destDir = destPath.substring(0, destPath.lastIndexOf(sep));
|
|
54
|
+
mkdirSync(destDir, { recursive: true });
|
|
55
|
+
writeFileSync(destPath, content, 'utf-8');
|
|
56
|
+
}
|
|
57
|
+
export function extractFilesAtRef(projectPath, ref) {
|
|
58
|
+
verifyGitRepo(projectPath);
|
|
59
|
+
verifyRefExists(projectPath, ref);
|
|
60
|
+
const tsFiles = listTsFilesAtRef(projectPath, ref);
|
|
42
61
|
if (tsFiles.length === 0) {
|
|
43
62
|
throw new Error(`No TypeScript files found at ref '${ref}'`);
|
|
44
63
|
}
|
|
45
|
-
// Create temp directory
|
|
46
64
|
const tempDir = join(tmpdir(), `drift-diff-${randomUUID()}`);
|
|
47
65
|
mkdirSync(tempDir, { recursive: true });
|
|
48
|
-
// Extract each file
|
|
49
66
|
for (const filePath of tsFiles) {
|
|
50
|
-
|
|
51
|
-
try {
|
|
52
|
-
content = execSync(`git show ${ref}:${filePath}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });
|
|
53
|
-
}
|
|
54
|
-
catch {
|
|
55
|
-
// File may not exist at this ref — skip
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
const destPath = join(tempDir, filePath.split('/').join(sep));
|
|
59
|
-
const destDir = destPath.substring(0, destPath.lastIndexOf(sep));
|
|
60
|
-
mkdirSync(destDir, { recursive: true });
|
|
61
|
-
writeFileSync(destPath, content, 'utf-8');
|
|
67
|
+
extractFile(projectPath, ref, filePath, tempDir);
|
|
62
68
|
}
|
|
63
69
|
return tempDir;
|
|
64
70
|
}
|
|
@@ -73,7 +79,7 @@ export function cleanupTempDir(tempDir) {
|
|
|
73
79
|
/**
|
|
74
80
|
* Get the short hash of a git ref for display purposes.
|
|
75
81
|
*/
|
|
76
|
-
|
|
82
|
+
function resolveRefHash(projectPath, ref) {
|
|
77
83
|
try {
|
|
78
84
|
return execSync(`git rev-parse --short ${ref}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' }).trim();
|
|
79
85
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
export { analyzeProject, analyzeFile, RULE_WEIGHTS } from './analyzer.js';
|
|
2
2
|
export { buildReport, formatMarkdown } from './reporter.js';
|
|
3
3
|
export { computeDiff } from './diff.js';
|
|
4
|
-
export
|
|
4
|
+
export { generateReview, formatReviewMarkdown } from './review.js';
|
|
5
|
+
export { generateArchitectureMap, generateArchitectureSvg } from './map.js';
|
|
6
|
+
export type { DriftReport, FileReport, DriftIssue, DriftDiff, FileDiff, DriftConfig, RepoQualityScore, MaintenanceRiskMetrics, DriftPlugin, DriftPluginRule, } from './types.js';
|
|
7
|
+
export { loadHistory, saveSnapshot } from './snapshot.js';
|
|
8
|
+
export type { SnapshotEntry, SnapshotHistory } from './snapshot.js';
|
|
5
9
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
export { analyzeProject, analyzeFile, RULE_WEIGHTS } from './analyzer.js';
|
|
2
2
|
export { buildReport, formatMarkdown } from './reporter.js';
|
|
3
3
|
export { computeDiff } from './diff.js';
|
|
4
|
+
export { generateReview, formatReviewMarkdown } from './review.js';
|
|
5
|
+
export { generateArchitectureMap, generateArchitectureSvg } from './map.js';
|
|
6
|
+
export { loadHistory, saveSnapshot } from './snapshot.js';
|
|
4
7
|
//# sourceMappingURL=index.js.map
|
package/dist/map.d.ts
ADDED