@blundergoat/gruff-ts 0.2.0 → 0.3.1
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/CHANGELOG.md +30 -0
- package/README.md +81 -13
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +21 -5
- package/docs/output-formats.md +10 -0
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +5 -5
- package/docs/rules.md +26 -18
- package/package.json +5 -5
- package/scripts/bump-version.sh +1 -1
- package/src/analyser.ts +48 -37
- package/src/blocks.ts +23 -70
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +106 -12
- package/src/comment-rules.ts +5 -1
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +1 -1
- package/src/config.ts +215 -460
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +7 -4
- package/src/discovery.ts +88 -32
- package/src/findings-helpers.ts +41 -5
- package/src/findings.ts +10 -0
- package/src/fixture-purpose-rules.ts +7 -9
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +3 -0
- package/src/line-rules.ts +7 -5
- package/src/naming-pushers.ts +35 -6
- package/src/profiles.ts +231 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +6 -117
- package/src/report-html.ts +1 -1
- package/src/report-renderers.ts +98 -7
- package/src/rule-list.ts +23 -2
- package/src/rules.ts +11 -12
- package/src/safety-rules.ts +16 -6
- package/src/scoring.ts +43 -5
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/static-analysis-redundant-rules.ts +411 -0
- package/src/test-block-rules.ts +115 -53
- package/src/test-fixtures.ts +50 -9
- package/src/types.ts +79 -2
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
// Diff-aware changed-region filtering for analyse runs. The public JSON finding shape stays intact:
|
|
2
|
+
// this module only decides which already-produced findings are attributable to the requested change.
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { functionBlocks } from "./blocks.ts";
|
|
5
|
+
import type { SourceFile } from "./discovery.ts";
|
|
6
|
+
import { maskNonCode } from "./source-text.ts";
|
|
7
|
+
import type { AnalysisOptions, ChangedScopeMode, Finding } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
// Inclusive line range from a changed hunk or explicit `--changed-ranges` input.
|
|
10
|
+
export interface ChangedRange {
|
|
11
|
+
start: number;
|
|
12
|
+
end: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Complete changed-region filter state used after the full report is generated.
|
|
16
|
+
export interface ChangedRegionScope {
|
|
17
|
+
mode: ChangedScopeMode;
|
|
18
|
+
rangesByFile: Map<string, ChangedRange[]>;
|
|
19
|
+
wholeFiles: Set<string>;
|
|
20
|
+
explicitRanges?: ChangedRange[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Source text paired with discovery metadata so findings can be expanded to symbols.
|
|
24
|
+
interface SourceSnapshot {
|
|
25
|
+
file: SourceFile;
|
|
26
|
+
source: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Named source span used to keep symbol-scope findings when their declaration overlaps a hunk.
|
|
30
|
+
interface DeclarationRegion {
|
|
31
|
+
name: string;
|
|
32
|
+
start: number;
|
|
33
|
+
end: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Mutable state for the current file while walking a unified diff line by line.
|
|
37
|
+
interface DiffParseState {
|
|
38
|
+
currentFile: string | undefined;
|
|
39
|
+
isNewFile: boolean;
|
|
40
|
+
targetLine: number | undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
|
|
44
|
+
|
|
45
|
+
// Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
|
|
46
|
+
export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
|
|
47
|
+
if (options.changedRanges) {
|
|
48
|
+
return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
|
|
49
|
+
}
|
|
50
|
+
if (options.diffPatch !== undefined) {
|
|
51
|
+
return parseUnifiedDiff(options.diffPatch, options.changedScope);
|
|
52
|
+
}
|
|
53
|
+
if (options.since) {
|
|
54
|
+
return gitDiffScope(options.since, options.changedScope);
|
|
55
|
+
}
|
|
56
|
+
if (options.diff) {
|
|
57
|
+
if (options.diff === "-") {
|
|
58
|
+
throw new Error("--diff - requires diffPatch input; the CLI reads stdin before analysis.");
|
|
59
|
+
}
|
|
60
|
+
return gitDiffScope(options.diff, options.changedScope);
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Applies changed-region filtering to findings and reports how many pre-existing findings dropped.
|
|
66
|
+
export function filterChangedFindings(
|
|
67
|
+
findings: Finding[],
|
|
68
|
+
scope: ChangedRegionScope | undefined,
|
|
69
|
+
sources: Map<string, SourceSnapshot>,
|
|
70
|
+
): { findings: Finding[]; suppressedCount?: number } {
|
|
71
|
+
if (!scope) {
|
|
72
|
+
return { findings };
|
|
73
|
+
}
|
|
74
|
+
const declarationsByFile = new Map<string, DeclarationRegion[]>();
|
|
75
|
+
const kept: Finding[] = [];
|
|
76
|
+
let suppressedCount = 0;
|
|
77
|
+
for (const finding of findings) {
|
|
78
|
+
if (isFindingInChangedScope(finding, scope, sources, declarationsByFile)) {
|
|
79
|
+
kept.push(finding);
|
|
80
|
+
} else {
|
|
81
|
+
suppressedCount += 1;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { findings: kept, suppressedCount };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Keeps a finding when its own line or enclosing declaration intersects the changed scope.
|
|
88
|
+
function isFindingInChangedScope(
|
|
89
|
+
finding: Finding,
|
|
90
|
+
scope: ChangedRegionScope,
|
|
91
|
+
sources: Map<string, SourceSnapshot>,
|
|
92
|
+
declarationsByFile: Map<string, DeclarationRegion[]>,
|
|
93
|
+
): boolean {
|
|
94
|
+
if (scope.wholeFiles.has(finding.filePath)) {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
const changedRanges = rangesForFindingFile(scope, finding.filePath);
|
|
98
|
+
if (changedRanges.length === 0) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
if (isFileWideFinding(finding) && (scope.rangesByFile.has(finding.filePath) || scope.explicitRanges)) {
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
const findingRange = { start: finding.line ?? 1, end: finding.endLine ?? finding.line ?? 1 };
|
|
105
|
+
if (overlapsAny(findingRange, changedRanges)) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
if (scope.mode === "hunk") {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
const declaration = enclosingDeclaration(finding, sources, declarationsByFile);
|
|
112
|
+
return declaration !== undefined && overlapsAny(declaration, changedRanges);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Invariant: file-wide findings are line-1 anchors kept when any hunk changes the file.
|
|
116
|
+
function isFileWideFinding(finding: Finding): boolean {
|
|
117
|
+
return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1 && finding.symbol === undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
|
|
121
|
+
function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): ChangedRange[] {
|
|
122
|
+
return scope.explicitRanges ?? scope.rangesByFile.get(filePath) ?? [];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Resolves the narrowest declaration around a finding so symbol-scope mode can keep whole callables.
|
|
126
|
+
function enclosingDeclaration(
|
|
127
|
+
finding: Finding,
|
|
128
|
+
sources: Map<string, SourceSnapshot>,
|
|
129
|
+
declarationsByFile: Map<string, DeclarationRegion[]>,
|
|
130
|
+
): DeclarationRegion | undefined {
|
|
131
|
+
const source = sources.get(finding.filePath);
|
|
132
|
+
if (!source?.file.isScript) {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
let declarations = declarationsByFile.get(finding.filePath);
|
|
136
|
+
if (!declarations) {
|
|
137
|
+
declarations = declarationRegions(source.source);
|
|
138
|
+
declarationsByFile.set(finding.filePath, declarations);
|
|
139
|
+
}
|
|
140
|
+
const line = finding.line ?? 1;
|
|
141
|
+
const named = finding.symbol
|
|
142
|
+
? declarations.filter((region) => region.name === finding.symbol && line >= region.start && line <= region.end)
|
|
143
|
+
: [];
|
|
144
|
+
const candidates = named.length > 0 ? named : declarations.filter((region) => line >= region.start && line <= region.end);
|
|
145
|
+
return candidates.sort((left, right) => (left.end - left.start) - (right.end - right.start))[0];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Combines function and class/interface spans into one declaration inventory per source file.
|
|
149
|
+
function declarationRegions(source: string): DeclarationRegion[] {
|
|
150
|
+
const codeSource = maskNonCode(source);
|
|
151
|
+
return [
|
|
152
|
+
...functionBlocks(source, codeSource).map((block) => ({
|
|
153
|
+
name: block.name,
|
|
154
|
+
start: block.startLine,
|
|
155
|
+
end: block.startLine + block.lineCount - 1,
|
|
156
|
+
})),
|
|
157
|
+
...classLikeRegions(codeSource),
|
|
158
|
+
];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Finds class and interface spans that the function-block lexer intentionally does not emit.
|
|
162
|
+
function classLikeRegions(codeSource: string): DeclarationRegion[] {
|
|
163
|
+
const lines = codeSource.split(/\r?\n/);
|
|
164
|
+
const regions: DeclarationRegion[] = [];
|
|
165
|
+
lines.forEach((line, index) => {
|
|
166
|
+
const match = line.match(/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:class|interface)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/);
|
|
167
|
+
if (!match?.[1]) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
regions.push({ name: match[1], start: index + 1, end: bracedRegionEnd(lines, index) });
|
|
171
|
+
});
|
|
172
|
+
return regions;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Walks brace depth from a class/interface declaration to estimate its closing line.
|
|
176
|
+
function bracedRegionEnd(lines: string[], startIndex: number): number {
|
|
177
|
+
let depth = 0;
|
|
178
|
+
let hasSeenOpen = false;
|
|
179
|
+
for (let index = startIndex; index < lines.length; index += 1) {
|
|
180
|
+
for (const character of lines[index] ?? "") {
|
|
181
|
+
if (character === "{") {
|
|
182
|
+
depth += 1;
|
|
183
|
+
hasSeenOpen = true;
|
|
184
|
+
} else if (character === "}") {
|
|
185
|
+
depth -= 1;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (hasSeenOpen && depth <= 0) {
|
|
189
|
+
return index + 1;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return startIndex + 1;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Checks whether a finding or declaration span intersects any changed hunk.
|
|
196
|
+
function overlapsAny(range: ChangedRange, changedRanges: ChangedRange[]): boolean {
|
|
197
|
+
return changedRanges.some((changedRange) => rangesOverlap(range, changedRange));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Inclusive range overlap test for one-based source line numbers.
|
|
201
|
+
function rangesOverlap(left: ChangedRange, right: ChangedRange): boolean {
|
|
202
|
+
return left.start <= right.end && right.start <= left.end;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Parses the comma-separated CLI range syntax and throws validation errors for malformed ranges.
|
|
206
|
+
function parseChangedRanges(rawRanges: string): ChangedRange[] {
|
|
207
|
+
const ranges = rawRanges
|
|
208
|
+
.split(",")
|
|
209
|
+
.map((part) => part.trim())
|
|
210
|
+
.filter(Boolean)
|
|
211
|
+
.map(parseChangedRange);
|
|
212
|
+
if (ranges.length === 0) {
|
|
213
|
+
throw new Error("--changed-ranges must include at least one range such as 3-3 or 8-10");
|
|
214
|
+
}
|
|
215
|
+
return mergeRanges(ranges);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Parses one `N` or `N-M` range and throws the CLI-facing validation error for invalid input.
|
|
219
|
+
function parseChangedRange(rawRange: string): ChangedRange {
|
|
220
|
+
const match = rawRange.match(/^(\d+)(?:-(\d+))?$/);
|
|
221
|
+
if (!match?.[1]) {
|
|
222
|
+
throw new Error(`invalid --changed-ranges entry: ${rawRange}`);
|
|
223
|
+
}
|
|
224
|
+
const start = Number(match[1]);
|
|
225
|
+
const end = Number(match[2] ?? match[1]);
|
|
226
|
+
if (start < 1 || end < start) {
|
|
227
|
+
throw new Error(`invalid --changed-ranges entry: ${rawRange}`);
|
|
228
|
+
}
|
|
229
|
+
return { start, end };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Produces a changed-region scope from a named git diff mode or arbitrary git ref.
|
|
233
|
+
function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
234
|
+
if (mode === "staged") {
|
|
235
|
+
return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
|
|
236
|
+
}
|
|
237
|
+
if (mode === "unstaged") {
|
|
238
|
+
return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
|
|
239
|
+
}
|
|
240
|
+
if (mode === "working-tree") {
|
|
241
|
+
return mergeScopes(
|
|
242
|
+
[
|
|
243
|
+
parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
|
|
244
|
+
parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
|
|
245
|
+
untrackedFileScope(changedScope),
|
|
246
|
+
],
|
|
247
|
+
changedScope,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--end-of-options", mode]), changedScope);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Parses a unified diff into file-level and hunk-level scope.
|
|
254
|
+
function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
255
|
+
const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
|
|
256
|
+
const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
|
|
257
|
+
for (const line of diffText.split(/\r?\n/)) {
|
|
258
|
+
applyDiffLine(scope, state, line);
|
|
259
|
+
}
|
|
260
|
+
return scope;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Dispatches one unified-diff line to the smallest applicable state transition.
|
|
264
|
+
function applyDiffLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
|
|
265
|
+
if (line.startsWith("diff --git ")) {
|
|
266
|
+
state.currentFile = undefined;
|
|
267
|
+
state.isNewFile = false;
|
|
268
|
+
state.targetLine = undefined;
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (line.startsWith("new file mode ") || line === "--- /dev/null") {
|
|
272
|
+
state.isNewFile = true;
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (applyTargetFileLine(scope, state, line)) {
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (applyHunkHeader(scope, state, line)) {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
applyHunkBodyLine(scope, state, line);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Handles `+++` target-file headers, including new files that should keep all findings.
|
|
285
|
+
function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
|
|
286
|
+
if (line.startsWith("+++ ")) {
|
|
287
|
+
const path = diffPath(line.slice(4));
|
|
288
|
+
state.currentFile = path === "/dev/null" ? undefined : path;
|
|
289
|
+
state.targetLine = undefined;
|
|
290
|
+
if (state.currentFile && state.isNewFile) {
|
|
291
|
+
scope.wholeFiles.add(state.currentFile);
|
|
292
|
+
}
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Starts tracking target-side line numbers for the current hunk.
|
|
299
|
+
function applyHunkHeader(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
|
|
300
|
+
const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
|
|
301
|
+
if (!hunk) {
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
if (!hunk[1] || !state.currentFile || scope.wholeFiles.has(state.currentFile)) {
|
|
305
|
+
state.targetLine = undefined;
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
const start = Math.max(1, Number(hunk[1]));
|
|
309
|
+
const length = hunk[2] === undefined ? 1 : Number(hunk[2]);
|
|
310
|
+
state.targetLine = length === 0 ? undefined : start;
|
|
311
|
+
return true;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Adds only real target-side additions from the hunk body; context lines just advance the cursor.
|
|
315
|
+
function applyHunkBodyLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
|
|
316
|
+
if (!state.currentFile || state.targetLine === undefined || scope.wholeFiles.has(state.currentFile)) {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (line.startsWith("+")) {
|
|
320
|
+
addRange(scope.rangesByFile, state.currentFile, { start: state.targetLine, end: state.targetLine });
|
|
321
|
+
state.targetLine += 1;
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (line.startsWith(" ")) {
|
|
325
|
+
state.targetLine += 1;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Normalizes the `+++ b/path` header path into the same display path discovery uses.
|
|
330
|
+
function diffPath(rawPath: string): string {
|
|
331
|
+
const trimmed = rawPath.trim();
|
|
332
|
+
if (trimmed === "/dev/null") {
|
|
333
|
+
return trimmed;
|
|
334
|
+
}
|
|
335
|
+
return trimmed.replace(/^"?(?:a|b)\//, "").replace(/"$/, "").replaceAll("\\", "/");
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Treats untracked files as whole-file changed because git has no hunks for them yet.
|
|
339
|
+
function untrackedFileScope(changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
340
|
+
return {
|
|
341
|
+
mode: changedScope,
|
|
342
|
+
rangesByFile: new Map(),
|
|
343
|
+
wholeFiles: new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/"))),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Unions staged, unstaged, and untracked scopes while whole-file changes dominate hunk ranges.
|
|
348
|
+
function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
349
|
+
const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
|
|
350
|
+
for (const scope of scopes) {
|
|
351
|
+
for (const file of scope.wholeFiles) {
|
|
352
|
+
merged.wholeFiles.add(file);
|
|
353
|
+
merged.rangesByFile.delete(file);
|
|
354
|
+
}
|
|
355
|
+
for (const [file, ranges] of scope.rangesByFile) {
|
|
356
|
+
if (merged.wholeFiles.has(file)) {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
for (const range of ranges) {
|
|
360
|
+
addRange(merged.rangesByFile, file, range);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return merged;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Inserts a range for one file and immediately coalesces adjacent hunks.
|
|
368
|
+
function addRange(rangesByFile: Map<string, ChangedRange[]>, filePath: string, range: ChangedRange): void {
|
|
369
|
+
rangesByFile.set(filePath, mergeRanges([...(rangesByFile.get(filePath) ?? []), range]));
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Sorts and merges overlapping or adjacent line ranges so downstream checks stay deterministic.
|
|
373
|
+
function mergeRanges(ranges: ChangedRange[]): ChangedRange[] {
|
|
374
|
+
const sorted = [...ranges].sort((left, right) => left.start - right.start || left.end - right.end);
|
|
375
|
+
const merged: ChangedRange[] = [];
|
|
376
|
+
for (const range of sorted) {
|
|
377
|
+
const previous = merged[merged.length - 1];
|
|
378
|
+
if (!previous || range.start > previous.end + 1) {
|
|
379
|
+
merged.push({ ...range });
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
previous.end = Math.max(previous.end, range.end);
|
|
383
|
+
}
|
|
384
|
+
return merged;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Spawns `git` through a fixed argv vector; callers construct argv arrays without interpolation.
|
|
388
|
+
function gitOutput(args: string[]): string {
|
|
389
|
+
return execFileSync("git", args, { encoding: "utf8" });
|
|
390
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// `check-ignore` command core: classify each path through the shared discovery ignore engine and
|
|
2
|
+
// render the verdict. No analysis is performed - this is an O(1)-per-path config/gitignore/default
|
|
3
|
+
// lookup that mirrors `git check-ignore` exit semantics, so a coding-agent hook can ask "will gruff
|
|
4
|
+
// skip this changed file?" before running a scan. Single source of truth: `classifyPathIgnore` is the
|
|
5
|
+
// exact engine `analyse` discovery uses; this module only loads config and formats the output.
|
|
6
|
+
import { cwd } from "node:process";
|
|
7
|
+
import { loadConfig } from "./config.ts";
|
|
8
|
+
import { classifyPathIgnore, type PathIgnoreClassification } from "./discovery.ts";
|
|
9
|
+
import type { AnalysisOptions } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
/** Output encodings supported by the `check-ignore` command. */
|
|
12
|
+
export type CheckIgnoreFormat = "text" | "json";
|
|
13
|
+
|
|
14
|
+
// Resolves config exactly as `analyse` does (`--config` / `--no-config`), then classifies each input
|
|
15
|
+
// path. Config `paths.ignore` is authoritative; default and gitignore matches are reported with their
|
|
16
|
+
// source too so the caller sees why a path would be skipped.
|
|
17
|
+
export function checkIgnore(inputs: string[], options: AnalysisOptions): PathIgnoreClassification[] {
|
|
18
|
+
const projectRoot = cwd();
|
|
19
|
+
const config = loadConfig(projectRoot, options);
|
|
20
|
+
return inputs.map((input) => classifyPathIgnore(projectRoot, input, options, config));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Mirrors `git check-ignore`: exit 0 when at least one path is ignored, 1 when none are. Exit 2 is
|
|
24
|
+
// reserved for config/usage errors and is set by the CLI layer via `runWithConfigErrorHandling`.
|
|
25
|
+
export function checkIgnoreExitCode(results: PathIgnoreClassification[]): number {
|
|
26
|
+
return results.some((result) => result.isIgnored) ? 0 : 1;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// JSON is the agent-facing contract: every input path as `{ path, ignored, source, pattern }`, with
|
|
30
|
+
// `source`/`pattern` null when the path is not ignored. Text lists only the ignored paths as
|
|
31
|
+
// `<path>\t<source>:<pattern>`, matching `git check-ignore`'s "print the matches" behaviour.
|
|
32
|
+
export function renderCheckIgnore(results: PathIgnoreClassification[], format: CheckIgnoreFormat): string {
|
|
33
|
+
if (format === "json") {
|
|
34
|
+
return JSON.stringify(
|
|
35
|
+
results.map((result) => ({
|
|
36
|
+
path: result.path,
|
|
37
|
+
ignored: result.isIgnored,
|
|
38
|
+
source: result.source ?? null,
|
|
39
|
+
pattern: result.pattern ?? null,
|
|
40
|
+
})),
|
|
41
|
+
null,
|
|
42
|
+
2,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return results
|
|
46
|
+
.filter((result) => result.isIgnored)
|
|
47
|
+
.map((result) => `${result.path}\t${result.source}:${result.pattern}`)
|
|
48
|
+
.join("\n");
|
|
49
|
+
}
|
package/src/class-rules.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { type ExportedDeclaration, exportedDeclarations, pushMissingPublicDocFin
|
|
|
7
7
|
import { type SourceFile } from "./discovery.ts";
|
|
8
8
|
import { makeFinding } from "./findings.ts";
|
|
9
9
|
import { fileBaseName, finding, normalizedIdentifier } from "./findings-helpers.ts";
|
|
10
|
-
import { pushBooleanPrefixAt, pushNegativeBooleanAt } from "./naming-pushers.ts";
|
|
10
|
+
import { pushBooleanPrefixAt, pushNegativeBooleanAt, type NamingSurface } from "./naming-pushers.ts";
|
|
11
11
|
import { byteLine } from "./text-scans.ts";
|
|
12
12
|
import type { Config, Finding } from "./types.ts";
|
|
13
13
|
|
|
@@ -16,6 +16,7 @@ import type { Config, Finding } from "./types.ts";
|
|
|
16
16
|
interface DeclaredIdentifier {
|
|
17
17
|
name: string;
|
|
18
18
|
line: number;
|
|
19
|
+
surface: NamingSurface;
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
// Aggregates `const`/`let`/`var` declarations, callable parameters, and interface fields into a
|
|
@@ -23,24 +24,24 @@ interface DeclaredIdentifier {
|
|
|
23
24
|
export function collectDeclaredIdentifiers(source: string, codeSource: string, blocks: FunctionBlock[]): DeclaredIdentifier[] {
|
|
24
25
|
const inventory: DeclaredIdentifier[] = [];
|
|
25
26
|
const seen = new Set<string>();
|
|
26
|
-
const push = (name: string, line: number): void => {
|
|
27
|
+
const push = (name: string, line: number, surface: NamingSurface): void => {
|
|
27
28
|
if (!name) return;
|
|
28
|
-
const key = `${name}@${line}`;
|
|
29
|
+
const key = `${name}@${line}@${surface}`;
|
|
29
30
|
if (seen.has(key)) return;
|
|
30
31
|
seen.add(key);
|
|
31
|
-
inventory.push({ name, line });
|
|
32
|
+
inventory.push({ name, line, surface });
|
|
32
33
|
};
|
|
33
34
|
|
|
34
35
|
for (const match of codeSource.matchAll(/\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) {
|
|
35
|
-
push(match[1] ?? "", byteLine(source, match.index ?? 0));
|
|
36
|
+
push(match[1] ?? "", byteLine(source, match.index ?? 0), "declaration");
|
|
36
37
|
}
|
|
37
38
|
for (const block of blocks) {
|
|
38
39
|
for (const parameter of parameterNames(block.params)) {
|
|
39
|
-
push(parameter.name, block.declarationLine);
|
|
40
|
+
push(parameter.name, block.declarationLine, "parameter");
|
|
40
41
|
}
|
|
41
42
|
}
|
|
42
43
|
for (const fieldMatch of collectInterfaceFieldDeclarations(source, codeSource)) {
|
|
43
|
-
push(fieldMatch.name, fieldMatch.line);
|
|
44
|
+
push(fieldMatch.name, fieldMatch.line, "interface-field");
|
|
44
45
|
}
|
|
45
46
|
return inventory;
|
|
46
47
|
}
|
|
@@ -52,23 +53,36 @@ function collectInterfaceFieldDeclarations(source: string, codeSource: string):
|
|
|
52
53
|
const out: DeclaredIdentifier[] = [];
|
|
53
54
|
for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
|
|
54
55
|
const name = sourceLine.match(fieldRegex)?.[1] ?? "";
|
|
55
|
-
if (name) out.push({ name, line: lineIndex + 1 });
|
|
56
|
+
if (name) out.push({ name, line: lineIndex + 1, surface: "interface-field" });
|
|
56
57
|
}
|
|
57
58
|
return out;
|
|
58
59
|
}
|
|
59
60
|
|
|
60
|
-
// Strips separators
|
|
61
|
+
// Strips separators only so `userId`, `user_id`, and `userID` collapse, while `adr013` and
|
|
62
|
+
// `adr020` remain distinct domain tokens instead of fake casing variants.
|
|
61
63
|
// Two names sharing this key but differing in original form are the casing-drift signal.
|
|
62
64
|
function casingCanonicalKey(name: string): string {
|
|
63
|
-
return name.toLowerCase().replace(/[_\-
|
|
65
|
+
return name.toLowerCase().replace(/[_\-]/g, "");
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
/*
|
|
67
|
-
* Groups identifiers by
|
|
68
|
-
*
|
|
69
|
-
*
|
|
69
|
+
* Groups identifiers by canonical key, then filters out boundary surfaces before reporting. The
|
|
70
|
+
* split helper flow is intentional: the rule must preserve same-scope drift signal while refusing
|
|
71
|
+
* to command rewrites of constants, DTO fields, or intentionally-unused `_` names. Error behavior:
|
|
72
|
+
* never throws; it reports drift by appending findings only.
|
|
70
73
|
*/
|
|
71
74
|
export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], findings: Finding[]): void {
|
|
75
|
+
for (const entries of declaredIdentifierGroups(inventory).values()) {
|
|
76
|
+
const candidate = inconsistentCasingCandidate(entries);
|
|
77
|
+
if (!candidate) {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
findings.push(inconsistentCasingFinding(file, candidate));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Builds canonical-key groups once so the reporting pass can stay focused on rule semantics.
|
|
85
|
+
function declaredIdentifierGroups(inventory: DeclaredIdentifier[]): Map<string, DeclaredIdentifier[]> {
|
|
72
86
|
const groups = new Map<string, DeclaredIdentifier[]>();
|
|
73
87
|
for (const entry of inventory) {
|
|
74
88
|
const key = casingCanonicalKey(entry.name);
|
|
@@ -77,27 +91,60 @@ export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredI
|
|
|
77
91
|
list.push(entry);
|
|
78
92
|
groups.set(key, list);
|
|
79
93
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
filePath: file.displayPath,
|
|
91
|
-
line: second.line,
|
|
92
|
-
severity: "advisory",
|
|
93
|
-
pillar: "naming",
|
|
94
|
-
confidence: "medium",
|
|
95
|
-
symbol: second.name,
|
|
96
|
-
remediation: "Choose one form and use it consistently within the file.",
|
|
97
|
-
metadata: { variants: [...surfaces].sort() },
|
|
98
|
-
}),
|
|
99
|
-
);
|
|
94
|
+
return groups;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Invariant: returns the exact variant pair to report after boundary-aware suppression has run.
|
|
98
|
+
function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
|
|
99
|
+
const reportableEntries = casingReportableEntries(entries);
|
|
100
|
+
const sameSurfaceEntries = sameCasingSurfaceEntries(reportableEntries);
|
|
101
|
+
const surfaces = [...new Set(sameSurfaceEntries.map((entry) => entry.name))].sort();
|
|
102
|
+
if (surfaces.length < 2) {
|
|
103
|
+
return undefined;
|
|
100
104
|
}
|
|
105
|
+
const sorted = [...sameSurfaceEntries].sort((a, b) => a.line - b.line);
|
|
106
|
+
const first = sorted[0];
|
|
107
|
+
const second = sorted.find((entry, index) => index > 0 && entry.name !== first?.name);
|
|
108
|
+
return first && second ? { first, second, surfaces } : undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Builds the stable finding after candidate selection so fingerprint shape stays in one place.
|
|
112
|
+
function inconsistentCasingFinding(file: SourceFile, candidate: { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] }): Finding {
|
|
113
|
+
return makeFinding({
|
|
114
|
+
ruleId: "naming.inconsistent-casing",
|
|
115
|
+
message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` in the same file.`,
|
|
116
|
+
filePath: file.displayPath,
|
|
117
|
+
line: candidate.second.line,
|
|
118
|
+
severity: "advisory",
|
|
119
|
+
pillar: "naming",
|
|
120
|
+
confidence: "medium",
|
|
121
|
+
symbol: candidate.second.name,
|
|
122
|
+
remediation: "Choose one form and use it consistently within the file.",
|
|
123
|
+
metadata: { variants: candidate.surfaces },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// `_event` is the standard intentionally-unused spelling; comparing it with `event` would tell an
|
|
128
|
+
// agent to remove useful boundary information rather than fix casing drift.
|
|
129
|
+
function casingReportableEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
|
|
130
|
+
return entries.filter((entry) => !entry.name.startsWith("_"));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Contract fields and SCREAMING_SNAKE constants are boundary surfaces; remove only those entries so
|
|
134
|
+
// they do not mask real local drift elsewhere in the same canonical group.
|
|
135
|
+
function sameCasingSurfaceEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
|
|
136
|
+
const hasLocalSurface = entries.some((entry) => entry.surface !== "interface-field" && !isScreamingConstant(entry.name));
|
|
137
|
+
return entries.filter((entry) => {
|
|
138
|
+
if (hasLocalSurface && entry.surface === "interface-field") {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
return !(hasLocalSurface && isScreamingConstant(entry.name));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Recognises constant-style identifiers without stripping digits, so `V110` remains one token.
|
|
146
|
+
function isScreamingConstant(name: string): boolean {
|
|
147
|
+
return /^[A-Z][A-Z0-9_]*$/.test(name) && /[A-Z]/.test(name);
|
|
101
148
|
}
|
|
102
149
|
|
|
103
150
|
// Splits camelCase, PascalCase, snake_case, and kebab-case into tokens. The regex preserves
|