@blundergoat/gruff-ts 0.5.0 → 0.6.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/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
package/src/changed-regions.ts
CHANGED
|
@@ -1,12 +1,26 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Selects the findings that belong to a user's Git changes, patch, or explicit line ranges.
|
|
2
|
+
//
|
|
3
|
+
// Use `analyse --diff staged` to review the next commit, or `--changed-ranges` for specific lines.
|
|
4
|
+
// A full scan supplies context for findings that span functions, files, or imports.
|
|
3
5
|
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { cwd } from "node:process";
|
|
4
7
|
import { functionBlocks } from "./blocks.ts";
|
|
5
8
|
import type { SourceFile } from "./discovery.ts";
|
|
6
9
|
import type { ParsedScript } from "./parsed-script.ts";
|
|
7
10
|
import { maskNonCode } from "./source-text.ts";
|
|
8
11
|
import type { AnalysisOptions, ChangedScopeMode, Finding, RunDiagnostic } from "./types.ts";
|
|
9
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Signals that Gruff could not read the lines the user asked to review.
|
|
15
|
+
*
|
|
16
|
+
* For example, a mistyped revision makes `analyse --since` fail with a `changed-region` diagnostic.
|
|
17
|
+
* Hooks can show the same diagnostic when an edit could not be reviewed.
|
|
18
|
+
*/
|
|
19
|
+
export class ChangedRegionError extends Error {}
|
|
20
|
+
|
|
21
|
+
// The diagnostic type both the hook and `analyse` give a ChangedRegionError.
|
|
22
|
+
export const CHANGED_REGION_DIAGNOSTIC_TYPE = "changed-region";
|
|
23
|
+
|
|
10
24
|
// Inclusive line range from a changed hunk or explicit `--changed-ranges` input.
|
|
11
25
|
export interface ChangedRange {
|
|
12
26
|
start: number;
|
|
@@ -51,22 +65,35 @@ const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.m
|
|
|
51
65
|
// so changed-region attribution must consult the member list, not only the anchor `filePath`.
|
|
52
66
|
const PROJECT_RELATIONSHIP_RULE_IDS = new Set(["design.circular-import"]);
|
|
53
67
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Resolves the changed lines requested for `analyse` or a hook.
|
|
70
|
+
* Explicit ranges take priority, then supplied patch text, then `--since` or `--diff`.
|
|
71
|
+
*
|
|
72
|
+
* @param options - Analysis options carrying changed-range, patch, `--since`, `--diff`, and scope selectors.
|
|
73
|
+
* @param projectRoot - Working directory used when running Git comparisons; defaults to the current working directory.
|
|
74
|
+
* @returns Scope describing the requested changes, or undefined when the user asks for a full scan.
|
|
75
|
+
* @throws {ChangedRegionError} When a range, patch input, or Git comparison cannot be read.
|
|
76
|
+
*/
|
|
77
|
+
export function changedRegionScope(options: AnalysisOptions, projectRoot = cwd()): ChangedRegionScope | undefined {
|
|
78
|
+
// Editor integrations can specify the exact line ranges the user edited.
|
|
79
|
+
if (options.changedRanges !== undefined) {
|
|
57
80
|
return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
|
|
58
81
|
}
|
|
82
|
+
// An empty supplied patch means nothing changed and still takes priority over Git selectors.
|
|
59
83
|
if (options.diffPatch !== undefined) {
|
|
60
84
|
return parseUnifiedDiff(options.diffPatch, options.changedScope);
|
|
61
85
|
}
|
|
86
|
+
// A commit range lets a user see findings introduced since a known revision; `--since` always names a Git ref, never a diff mode keyword.
|
|
62
87
|
if (options.since) {
|
|
63
|
-
return gitDiffScope(options.since, options.changedScope);
|
|
88
|
+
return gitDiffScope(options.since, options.changedScope, projectRoot, false);
|
|
64
89
|
}
|
|
90
|
+
// A named diff compares the requested part of the checkout, unless `--diff-base` explicitly named a Git ref.
|
|
65
91
|
if (options.diff) {
|
|
92
|
+
// A lone dash expects patch text from stdin, supplied by the CLI before the scan.
|
|
66
93
|
if (options.diff === "-") {
|
|
67
|
-
throw new
|
|
94
|
+
throw new ChangedRegionError("--diff - requires diffPatch input; the CLI reads stdin before analysis.");
|
|
68
95
|
}
|
|
69
|
-
return gitDiffScope(options.diff, options.changedScope);
|
|
96
|
+
return gitDiffScope(options.diff, options.changedScope, projectRoot, options.isDiffExplicitRef !== true);
|
|
70
97
|
}
|
|
71
98
|
return undefined;
|
|
72
99
|
}
|
|
@@ -74,14 +101,15 @@ export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope
|
|
|
74
101
|
// Diagnostic types that describe one analysed file's content or readability. Only these are
|
|
75
102
|
// file-scoped under diff filtering; operational diagnostics (missing paths, history errors) always
|
|
76
103
|
// stay, because they describe the request rather than an unchanged context file.
|
|
77
|
-
const FILE_CONTENT_DIAGNOSTIC_TYPES = new Set(["parse-error", "read-error"]);
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
104
|
+
const FILE_CONTENT_DIAGNOSTIC_TYPES = new Set(["bounded-deep-scan", "parse-error", "read-error"]);
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Filters run diagnostics to changed target files when a diff scope is active.
|
|
108
|
+
* Operational diagnostics and diagnostics without a file path always remain.
|
|
109
|
+
*
|
|
110
|
+
* @param diagnostics - Run diagnostics emitted during analysis.
|
|
111
|
+
* @param scope - Active changed-region scope, or undefined for an unscoped run.
|
|
112
|
+
* @returns Input diagnostics unchanged for unscoped or explicit-range runs, or diff-filtered diagnostics keeping changed-file content errors.
|
|
85
113
|
*/
|
|
86
114
|
export function filterScopedDiagnostics(diagnostics: RunDiagnostic[], scope: ChangedRegionScope | undefined): RunDiagnostic[] {
|
|
87
115
|
if (!scope || scope.explicitRanges !== undefined) {
|
|
@@ -96,8 +124,15 @@ export function filterScopedDiagnostics(diagnostics: RunDiagnostic[], scope: Cha
|
|
|
96
124
|
});
|
|
97
125
|
}
|
|
98
126
|
|
|
99
|
-
|
|
100
|
-
|
|
127
|
+
/**
|
|
128
|
+
* Filters findings against the active changed-region scope, using sources to resolve declarations for symbol scope.
|
|
129
|
+
* The invariant is that kept plus suppressed equals the input total when a scope is provided.
|
|
130
|
+
*
|
|
131
|
+
* @param findings - Candidate findings from the full analysis pass.
|
|
132
|
+
* @param scope - Active changed-region scope, or undefined when no filtering is requested.
|
|
133
|
+
* @param sources - Snapshot lookup by file path used to resolve enclosing declarations in symbol scope.
|
|
134
|
+
* @returns Kept findings with suppressedCount when scoped, or the original findings with suppressedCount absent when unscoped.
|
|
135
|
+
*/
|
|
101
136
|
export function filterChangedFindings(
|
|
102
137
|
findings: Finding[],
|
|
103
138
|
scope: ChangedRegionScope | undefined,
|
|
@@ -119,8 +154,16 @@ export function filterChangedFindings(
|
|
|
119
154
|
return { findings: kept, suppressedCount };
|
|
120
155
|
}
|
|
121
156
|
|
|
122
|
-
|
|
123
|
-
|
|
157
|
+
/**
|
|
158
|
+
* Determines whether scope keeps a finding by relationship member, whole file, hunk overlap, or enclosing declaration under the gate contract.
|
|
159
|
+
* Hunk checks use line 1 for an absent start and the start for an absent end; empty ranges disable hunk and symbol matches.
|
|
160
|
+
*
|
|
161
|
+
* @param finding - Finding to evaluate against the active scope.
|
|
162
|
+
* @param scope - Active changed-region selection rules and file ranges.
|
|
163
|
+
* @param sources - Snapshot lookup used to read script sources on declaration cache misses.
|
|
164
|
+
* @param declarationsByFile - Mutates this per-file declaration cache on misses to avoid rebuilding spans during symbol widening.
|
|
165
|
+
* @returns True when the finding belongs in the changed scope under the gate contract; otherwise false.
|
|
166
|
+
*/
|
|
124
167
|
function isFindingInChangedScope(
|
|
125
168
|
finding: Finding,
|
|
126
169
|
scope: ChangedRegionScope,
|
|
@@ -133,8 +176,7 @@ function isFindingInChangedScope(
|
|
|
133
176
|
if (scope.wholeFiles.has(finding.filePath)) {
|
|
134
177
|
return true;
|
|
135
178
|
}
|
|
136
|
-
//
|
|
137
|
-
// a deletion-only edit produces no target-side ranges but still counts as touching the file.
|
|
179
|
+
// File scope runs before line checks so deletion-only edits still count. Explicit ranges make every selected file eligible.
|
|
138
180
|
if (scope.mode === "file") {
|
|
139
181
|
return scope.explicitRanges !== undefined || scope.changedFiles.has(finding.filePath);
|
|
140
182
|
}
|
|
@@ -149,8 +191,17 @@ function isFindingInChangedScope(
|
|
|
149
191
|
return symbolScopeWidensFinding(finding, scope, sources, declarationsByFile, changedRanges);
|
|
150
192
|
}
|
|
151
193
|
|
|
152
|
-
|
|
153
|
-
|
|
194
|
+
/**
|
|
195
|
+
* Checks whether symbol scope widens to keep a finding because its enclosing declaration overlaps changedRanges.
|
|
196
|
+
* The invariant is that file-wide findings and findings without a resolvable declaration never widen.
|
|
197
|
+
*
|
|
198
|
+
* @param finding - Finding outside direct hunk ranges to test for declaration-level widening.
|
|
199
|
+
* @param scope - Active changed-region scope whose mode must be `symbol` for widening to apply.
|
|
200
|
+
* @param sources - Snapshot lookup used to load scripts when resolving declarations.
|
|
201
|
+
* @param declarationsByFile - Mutates this per-file declaration cache on misses while resolving the enclosing declaration.
|
|
202
|
+
* @param changedRanges - Changed line ranges for the finding's file.
|
|
203
|
+
* @returns True when symbol scope keeps the finding because its enclosing declaration overlaps changedRanges; otherwise false.
|
|
204
|
+
*/
|
|
154
205
|
function symbolScopeWidensFinding(
|
|
155
206
|
finding: Finding,
|
|
156
207
|
scope: ChangedRegionScope,
|
|
@@ -165,16 +216,23 @@ function symbolScopeWidensFinding(
|
|
|
165
216
|
return declaration !== undefined && overlapsAny(declaration, changedRanges);
|
|
166
217
|
}
|
|
167
218
|
|
|
168
|
-
|
|
219
|
+
/**
|
|
220
|
+
* Checks whether a finding is a file-wide rule anchored at explicit line 1 so the symbol-scope invariant prevents widening.
|
|
221
|
+
* An absent line leaves the finding eligible for ordinary symbol-scope checks.
|
|
222
|
+
*
|
|
223
|
+
* @param finding - Finding whose rule ID and line anchor are checked.
|
|
224
|
+
* @returns True when a `FILE_WIDE_RULE_IDS` finding has an explicit line 1 anchor; otherwise false.
|
|
225
|
+
*/
|
|
169
226
|
function isFileWideFinding(finding: Finding): boolean {
|
|
170
227
|
return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
|
|
171
228
|
}
|
|
172
229
|
|
|
173
|
-
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
230
|
+
/**
|
|
231
|
+
* Applies the project-relationship scope contract using the files that participate in the change.
|
|
232
|
+
*
|
|
233
|
+
* @param finding - relationship to check. Uses its path if no member array exists. An empty member array matches neither file set.
|
|
234
|
+
* @param scope - selection whose whole-file and changed-file sets identify participating members
|
|
235
|
+
* @returns True for explicit ranges because they apply to every selected file, or if a member is in either file set. Otherwise false.
|
|
178
236
|
*/
|
|
179
237
|
function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegionScope): boolean {
|
|
180
238
|
if (scope.explicitRanges !== undefined) {
|
|
@@ -184,13 +242,27 @@ function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegion
|
|
|
184
242
|
return files.some((file) => typeof file === "string" && (scope.wholeFiles.has(file) || scope.changedFiles.has(file)));
|
|
185
243
|
}
|
|
186
244
|
|
|
187
|
-
|
|
245
|
+
/**
|
|
246
|
+
* Resolves the changed line ranges applicable to a finding's file under the scope contract.
|
|
247
|
+
* Explicit ranges take precedence because they apply to every selected file; an empty list leaves range checks with no target span.
|
|
248
|
+
*
|
|
249
|
+
* @param scope - Active changed-region scope holding explicit ranges and per-file hunk ranges.
|
|
250
|
+
* @param filePath - Path of the finding's file to look up when explicit ranges are absent.
|
|
251
|
+
* @returns Explicit ranges if configured, otherwise the hunk ranges for filePath or an empty list.
|
|
252
|
+
*/
|
|
188
253
|
function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): ChangedRange[] {
|
|
189
254
|
return scope.explicitRanges ?? scope.rangesByFile.get(filePath) ?? [];
|
|
190
255
|
}
|
|
191
256
|
|
|
192
|
-
|
|
193
|
-
|
|
257
|
+
/**
|
|
258
|
+
* Finds the narrowest declaration around the finding's line, preferring matching symbols for a stable choice.
|
|
259
|
+
* An absent line means line 1; fills declarationsByFile on a cache miss to avoid rebuilding declaration spans.
|
|
260
|
+
*
|
|
261
|
+
* @param finding - Finding whose file, symbol name, and line anchor locate the enclosing declaration.
|
|
262
|
+
* @param sources - Snapshot lookup used to verify script status and retrieve source text on cache misses.
|
|
263
|
+
* @param declarationsByFile - Mutates this per-file declaration cache on misses.
|
|
264
|
+
* @returns Narrowest enclosing declaration region, or undefined when no script or enclosing declaration is available.
|
|
265
|
+
*/
|
|
194
266
|
function enclosingDeclaration(
|
|
195
267
|
finding: Finding,
|
|
196
268
|
sources: Map<string, SourceSnapshot>,
|
|
@@ -213,7 +285,14 @@ function enclosingDeclaration(
|
|
|
213
285
|
return candidates.sort((left, right) => (left.end - left.start) - (right.end - right.start))[0];
|
|
214
286
|
}
|
|
215
287
|
|
|
216
|
-
|
|
288
|
+
/**
|
|
289
|
+
* Collects function, class, and interface spans in source for symbol scoping.
|
|
290
|
+
* Without the optional shared parse, function spans come from the text-based block scan instead of syntax nodes.
|
|
291
|
+
*
|
|
292
|
+
* @param source - Full file text to scan for function, class, and interface declarations.
|
|
293
|
+
* @param parsed - Optional shared parse supplying syntax for function spans when available.
|
|
294
|
+
* @returns Combined declaration regions across functions, classes, and interfaces.
|
|
295
|
+
*/
|
|
217
296
|
function declarationRegions(source: string, parsed?: ParsedScript): DeclarationRegion[] {
|
|
218
297
|
const codeSource = maskNonCode(source);
|
|
219
298
|
return [
|
|
@@ -226,7 +305,12 @@ function declarationRegions(source: string, parsed?: ParsedScript): DeclarationR
|
|
|
226
305
|
];
|
|
227
306
|
}
|
|
228
307
|
|
|
229
|
-
|
|
308
|
+
/**
|
|
309
|
+
* Extracts named class and interface line spans from masked source text, covering declarations outside the function-block scan.
|
|
310
|
+
*
|
|
311
|
+
* @param codeSource - Source text with comments and non-code literals masked out.
|
|
312
|
+
* @returns Named declaration regions for matched class and interface declarations.
|
|
313
|
+
*/
|
|
230
314
|
function classLikeRegions(codeSource: string): DeclarationRegion[] {
|
|
231
315
|
const lines = codeSource.split(/\r?\n/);
|
|
232
316
|
const regions: DeclarationRegion[] = [];
|
|
@@ -240,7 +324,14 @@ function classLikeRegions(codeSource: string): DeclarationRegion[] {
|
|
|
240
324
|
return regions;
|
|
241
325
|
}
|
|
242
326
|
|
|
243
|
-
|
|
327
|
+
/**
|
|
328
|
+
* Estimates a class or interface's one-based closing line by counting braces from the zero-based declaration startIndex.
|
|
329
|
+
* If no closing brace balances the declaration, returns its one-based starting line.
|
|
330
|
+
*
|
|
331
|
+
* @param lines - Masked source lines split at line breaks.
|
|
332
|
+
* @param startIndex - Zero-based line index where the class or interface declaration starts.
|
|
333
|
+
* @returns One-based closing line number, or the starting line when braces never balance.
|
|
334
|
+
*/
|
|
244
335
|
function bracedRegionEnd(lines: string[], startIndex: number): number {
|
|
245
336
|
let depth = 0;
|
|
246
337
|
let hasSeenOpen = false;
|
|
@@ -260,17 +351,35 @@ function bracedRegionEnd(lines: string[], startIndex: number): number {
|
|
|
260
351
|
return startIndex + 1;
|
|
261
352
|
}
|
|
262
353
|
|
|
263
|
-
|
|
354
|
+
/**
|
|
355
|
+
* Checks whether a finding or declaration span intersects any changed hunk.
|
|
356
|
+
*
|
|
357
|
+
* @param range - Inclusive one-based line span to test.
|
|
358
|
+
* @param changedRanges - Changed line ranges for the target file.
|
|
359
|
+
* @returns True when range overlaps at least one entry in changedRanges; otherwise false.
|
|
360
|
+
*/
|
|
264
361
|
function overlapsAny(range: ChangedRange, changedRanges: ChangedRange[]): boolean {
|
|
265
362
|
return changedRanges.some((changedRange) => rangesOverlap(range, changedRange));
|
|
266
363
|
}
|
|
267
364
|
|
|
268
|
-
|
|
365
|
+
/**
|
|
366
|
+
* Performs an inclusive range overlap test for one-based source line numbers.
|
|
367
|
+
*
|
|
368
|
+
* @param left - First inclusive line range.
|
|
369
|
+
* @param right - Second inclusive line range.
|
|
370
|
+
* @returns True when left and right share at least one line; otherwise false.
|
|
371
|
+
*/
|
|
269
372
|
function rangesOverlap(left: ChangedRange, right: ChangedRange): boolean {
|
|
270
373
|
return left.start <= right.end && right.start <= left.end;
|
|
271
374
|
}
|
|
272
375
|
|
|
273
|
-
|
|
376
|
+
/**
|
|
377
|
+
* Parses sorted, merged line ranges from comma-separated CLI text, skipping blank entries.
|
|
378
|
+
*
|
|
379
|
+
* @param rawRanges - Comma-separated `--changed-ranges` input text.
|
|
380
|
+
* @returns Sorted, merged inclusive line ranges.
|
|
381
|
+
* @throws {ChangedRegionError} When no ranges remain or a nonblank entry is outside the valid N or N-M syntax or bounds.
|
|
382
|
+
*/
|
|
274
383
|
function parseChangedRanges(rawRanges: string): ChangedRange[] {
|
|
275
384
|
const ranges = rawRanges
|
|
276
385
|
.split(",")
|
|
@@ -278,53 +387,166 @@ function parseChangedRanges(rawRanges: string): ChangedRange[] {
|
|
|
278
387
|
.filter(Boolean)
|
|
279
388
|
.map(parseChangedRange);
|
|
280
389
|
if (ranges.length === 0) {
|
|
281
|
-
throw new
|
|
390
|
+
throw new ChangedRegionError("--changed-ranges must include at least one range such as 3-3 or 8-10");
|
|
282
391
|
}
|
|
283
392
|
return mergeRanges(ranges);
|
|
284
393
|
}
|
|
285
394
|
|
|
286
|
-
|
|
395
|
+
/**
|
|
396
|
+
* Parses inclusive line bounds for one `--changed-ranges` entry, using a single number for both bounds.
|
|
397
|
+
*
|
|
398
|
+
* @param rawRange - Trimmed single range token in N or N-M form.
|
|
399
|
+
* @returns Inclusive start and end line numbers for the entry.
|
|
400
|
+
* @throws {ChangedRegionError} When the entry is not N or N-M digits, starts below 1, or ends before it starts.
|
|
401
|
+
*/
|
|
287
402
|
function parseChangedRange(rawRange: string): ChangedRange {
|
|
288
403
|
const match = rawRange.match(/^(\d+)(?:-(\d+))?$/);
|
|
289
404
|
if (!match?.[1]) {
|
|
290
|
-
throw new
|
|
405
|
+
throw new ChangedRegionError(`invalid --changed-ranges entry: ${rawRange}`);
|
|
291
406
|
}
|
|
292
407
|
const start = Number(match[1]);
|
|
293
408
|
const end = Number(match[2] ?? match[1]);
|
|
294
409
|
if (start < 1 || end < start) {
|
|
295
|
-
throw new
|
|
410
|
+
throw new ChangedRegionError(`invalid --changed-ranges entry: ${rawRange}`);
|
|
296
411
|
}
|
|
297
412
|
return { start, end };
|
|
298
413
|
}
|
|
299
414
|
|
|
300
|
-
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
415
|
+
/**
|
|
416
|
+
* Builds a changed-region scope from Git diff output, reading paths relative to the scan directory so nested scans match findings.
|
|
417
|
+
* Working-tree mode combines staged, unstaged, and non-ignored untracked changes for a review of all local edits.
|
|
418
|
+
*
|
|
419
|
+
* @param mode - Diff selector: `staged`, `unstaged`, `working-tree` (when `allowDiffModes` is true), or a Git revision expression.
|
|
420
|
+
* @param changedScope - Attribution mode carried onto the resulting scope for downstream filtering.
|
|
421
|
+
* @param projectRoot - Directory passed to Git so reported paths remain relative to the scan root.
|
|
422
|
+
* @param allowDiffModes - true lets `staged`, `unstaged` and `working-tree` pick a mode; false (`--since`, `--diff-base`) reads them as Git refs
|
|
423
|
+
* @returns Scope populated with changed files, whole files, and per-file hunk ranges.
|
|
306
424
|
*/
|
|
307
|
-
function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
308
|
-
|
|
309
|
-
|
|
425
|
+
function gitDiffScope(mode: string, changedScope: ChangedScopeMode, projectRoot: string, allowDiffModes = true): ChangedRegionScope {
|
|
426
|
+
/**
|
|
427
|
+
* Runs `git diff` with paths relative to the selected project so a scan launched from a parent directory sees the right edits.
|
|
428
|
+
*
|
|
429
|
+
* @param extra - Additional Git diff flags or revision arguments appended to the base command.
|
|
430
|
+
* @returns Parsed changed-region scope from the resulting unified diff output.
|
|
431
|
+
*/
|
|
432
|
+
const readDiff = (extra: string[]) => parseUnifiedDiff(
|
|
433
|
+
gitOutput(["-c", "core.quotepath=false", "diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative", ...extra], projectRoot),
|
|
434
|
+
changedScope,
|
|
435
|
+
);
|
|
436
|
+
// Mode keywords apply only to --diff; --since and --diff-base treat the value as a Git ref, even a branch named staged.
|
|
437
|
+
if (allowDiffModes) {
|
|
438
|
+
// Staged mode reviews the contents selected for the next commit. Without HEAD every staged file is new, so whole-file coverage needs no renumbering.
|
|
439
|
+
if (mode === "staged") {
|
|
440
|
+
const staged = readDiff(["--cached"]);
|
|
441
|
+
return hasGitHead(projectRoot) ? stagedInWorkingTreeLines(staged, readDiff(["HEAD", "--"]), readDiff([])) : staged;
|
|
442
|
+
}
|
|
443
|
+
// Unstaged mode reviews changes made since the last staging operation.
|
|
444
|
+
if (mode === "unstaged") {
|
|
445
|
+
return readDiff([]);
|
|
446
|
+
}
|
|
447
|
+
// A working-tree review uses `git diff HEAD` when HEAD exists so staged and unstaged edits share exact working-tree line numbers.
|
|
448
|
+
if (mode === "working-tree") {
|
|
449
|
+
const trackedScopes = hasGitHead(projectRoot)
|
|
450
|
+
? [readDiff(["HEAD", "--"])]
|
|
451
|
+
: [readDiff(["--cached"]), readDiff([])];
|
|
452
|
+
return mergeScopes(
|
|
453
|
+
[...trackedScopes, untrackedFileScope(changedScope, projectRoot)],
|
|
454
|
+
changedScope,
|
|
455
|
+
);
|
|
456
|
+
}
|
|
310
457
|
}
|
|
311
|
-
|
|
312
|
-
|
|
458
|
+
// Trailing `--` forces Git to interpret `mode` strictly as a revision expression rather than a path when the ref is missing.
|
|
459
|
+
return readDiff(["--end-of-options", mode, "--"]);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Renumbers staged ranges in working-tree lines, because the scan reads the working tree while `git diff --cached` numbers the index.
|
|
464
|
+
* For example, two unstaged lines inserted above a staged line 20 move it to line 22, which an index range would miss.
|
|
465
|
+
* A staged line counts when it is new since HEAD and the unstaged edit did not add it; one an unstaged edit rewrote drops out.
|
|
466
|
+
*
|
|
467
|
+
* @param staged - `git diff --cached` scope, which decides the changed files and whole files a staged review covers
|
|
468
|
+
* @param sinceHead - `git diff HEAD` scope: lines new since HEAD, numbered in the working tree
|
|
469
|
+
* @param unstaged - `git diff` scope: lines the unstaged edit added, numbered in the working tree
|
|
470
|
+
* @returns The staged scope with each file's hunk ranges (and newly staged files that also carry unstaged edits) expressed in working-tree lines; files without surviving lines get no ranges.
|
|
471
|
+
*/
|
|
472
|
+
function stagedInWorkingTreeLines(staged: ChangedRegionScope, sinceHead: ChangedRegionScope, unstaged: ChangedRegionScope): ChangedRegionScope {
|
|
473
|
+
const rangesByFile = new Map<string, ChangedRange[]>();
|
|
474
|
+
const wholeFiles = new Set<string>();
|
|
475
|
+
for (const file of staged.wholeFiles) {
|
|
476
|
+
const unstagedRanges = unstaged.rangesByFile.get(file);
|
|
477
|
+
if (!unstagedRanges || unstagedRanges.length === 0) {
|
|
478
|
+
wholeFiles.add(file);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const ranges = subtractRanges([{ start: 1, end: Number.MAX_SAFE_INTEGER }], unstagedRanges);
|
|
482
|
+
if (ranges.length > 0) {
|
|
483
|
+
rangesByFile.set(file, ranges);
|
|
484
|
+
}
|
|
313
485
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
);
|
|
486
|
+
for (const file of staged.rangesByFile.keys()) {
|
|
487
|
+
// A staged rename that unstaged edits pushed past Git's rename threshold reads as a new file since HEAD, so every line is new.
|
|
488
|
+
const newSinceHead = sinceHead.wholeFiles.has(file) ? [{ start: 1, end: Number.MAX_SAFE_INTEGER }] : sinceHead.rangesByFile.get(file) ?? [];
|
|
489
|
+
const ranges = subtractRanges(newSinceHead, unstaged.rangesByFile.get(file) ?? []);
|
|
490
|
+
// A staged hunk whose lines an unstaged edit replaced leaves nothing staged in the working tree to review.
|
|
491
|
+
if (ranges.length > 0) {
|
|
492
|
+
rangesByFile.set(file, ranges);
|
|
493
|
+
}
|
|
323
494
|
}
|
|
324
|
-
return
|
|
495
|
+
return { ...staged, wholeFiles, rangesByFile };
|
|
325
496
|
}
|
|
326
497
|
|
|
327
|
-
|
|
498
|
+
/**
|
|
499
|
+
* Removes every line covered by `removed` from `ranges`, splitting a range when a removed block falls inside it.
|
|
500
|
+
*
|
|
501
|
+
* @param ranges - sorted, merged inclusive ranges to keep lines from
|
|
502
|
+
* @param removed - sorted, merged inclusive ranges whose lines are taken out
|
|
503
|
+
* @returns Sorted inclusive ranges holding the lines of `ranges` outside `removed`; empty when every line is removed.
|
|
504
|
+
*/
|
|
505
|
+
function subtractRanges(ranges: ChangedRange[], removed: ChangedRange[]): ChangedRange[] {
|
|
506
|
+
const kept: ChangedRange[] = [];
|
|
507
|
+
for (const range of ranges) {
|
|
508
|
+
let start = range.start;
|
|
509
|
+
for (const cut of removed) {
|
|
510
|
+
// A removed block entirely before the remaining span, or after the range, leaves it whole.
|
|
511
|
+
if (cut.end < start || cut.start > range.end) {
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (cut.start > start) {
|
|
515
|
+
kept.push({ start, end: cut.start - 1 });
|
|
516
|
+
}
|
|
517
|
+
start = cut.end + 1;
|
|
518
|
+
}
|
|
519
|
+
if (start <= range.end) {
|
|
520
|
+
kept.push({ start, end: range.end });
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return kept;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Spawns `git rev-parse` to check whether `HEAD` exists so `working-tree` can diff against `HEAD` instead of merging index coordinates.
|
|
528
|
+
*
|
|
529
|
+
* @param projectRoot - Directory passed to Git when verifying `HEAD`.
|
|
530
|
+
* @returns True when `HEAD` resolves to a commit; false in a freshly initialized repository with an unborn `HEAD` or outside a repo.
|
|
531
|
+
*/
|
|
532
|
+
function hasGitHead(projectRoot: string): boolean {
|
|
533
|
+
try {
|
|
534
|
+
execFileSync("git", ["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: projectRoot, stdio: ["ignore", "ignore", "ignore"] });
|
|
535
|
+
return true;
|
|
536
|
+
} catch {
|
|
537
|
+
// For example, a brand-new repository after `git init` has staged files but no initial commit yet, so `HEAD` does not exist.
|
|
538
|
+
return false;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Parses changed target files and addition ranges from unified diff text, carrying changedScope forward for later filtering.
|
|
544
|
+
* A new file with a target header gets whole-file coverage; a surviving file with only deletions can be changed without target ranges.
|
|
545
|
+
*
|
|
546
|
+
* @param diffText - Unified diff text to walk line by line; an empty patch yields a scope with no changed files.
|
|
547
|
+
* @param changedScope - Scope attribution mode assigned to the returned scope.
|
|
548
|
+
* @returns Scope containing changed files, whole-file additions, and per-file target addition ranges.
|
|
549
|
+
*/
|
|
328
550
|
function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
329
551
|
const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
|
|
330
552
|
const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
|
|
@@ -334,7 +556,15 @@ function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): Cha
|
|
|
334
556
|
return scope;
|
|
335
557
|
}
|
|
336
558
|
|
|
337
|
-
|
|
559
|
+
/**
|
|
560
|
+
* Reads one unified-diff line and updates state for the current target file and hunk.
|
|
561
|
+
* Mutates scope and state, clearing state at each file header to avoid carrying over the previous file.
|
|
562
|
+
*
|
|
563
|
+
* @param scope - Mutates changedFiles, wholeFiles, and rangesByFile as target headers and additions are encountered.
|
|
564
|
+
* @param state - Mutates per-file parser state across headers and hunk lines.
|
|
565
|
+
* @param line - Single line from the unified diff stream.
|
|
566
|
+
* @returns Nothing. Records changed files and additions in scope and updates state in place.
|
|
567
|
+
*/
|
|
338
568
|
function applyDiffLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
|
|
339
569
|
if (line.startsWith("diff --git ")) {
|
|
340
570
|
state.currentFile = undefined;
|
|
@@ -355,7 +585,15 @@ function applyDiffLine(scope: ChangedRegionScope, state: DiffParseState, line: s
|
|
|
355
585
|
applyHunkBodyLine(scope, state, line);
|
|
356
586
|
}
|
|
357
587
|
|
|
358
|
-
|
|
588
|
+
/**
|
|
589
|
+
* Applies a unified-diff target-file header (`+++ `) by updating state's current file and clearing its hunk cursor.
|
|
590
|
+
* A deleted target leaves no current file; surviving targets enter changedFiles, with whole-file coverage for new files.
|
|
591
|
+
*
|
|
592
|
+
* @param scope - Mutates changedFiles and wholeFiles when a surviving or new target file header is matched.
|
|
593
|
+
* @param state - Mutates currentFile and resets targetLine when the line is a target-file header.
|
|
594
|
+
* @param line - Candidate unified-diff line to inspect.
|
|
595
|
+
* @returns True if line is a target-file header; otherwise false.
|
|
596
|
+
*/
|
|
359
597
|
function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
|
|
360
598
|
if (line.startsWith("+++ ")) {
|
|
361
599
|
const path = diffPath(line.slice(4));
|
|
@@ -372,7 +610,15 @@ function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, l
|
|
|
372
610
|
return false;
|
|
373
611
|
}
|
|
374
612
|
|
|
375
|
-
|
|
613
|
+
/**
|
|
614
|
+
* Applies a unified-diff hunk header (`@@ ... @@`) and updates state's target line cursor for the hunk.
|
|
615
|
+
* A missing target file, whole-file coverage in scope, or a zero-length target hunk clears the cursor and skips line tracking.
|
|
616
|
+
*
|
|
617
|
+
* @param scope - Active diff scope checked for whole-file coverage on the current file.
|
|
618
|
+
* @param state - Mutates targetLine to the hunk's starting line or clears it when tracking should be skipped.
|
|
619
|
+
* @param line - Candidate unified-diff line to inspect.
|
|
620
|
+
* @returns True if line is a hunk header; otherwise false.
|
|
621
|
+
*/
|
|
376
622
|
function applyHunkHeader(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
|
|
377
623
|
const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
|
|
378
624
|
if (!hunk) {
|
|
@@ -388,7 +634,15 @@ function applyHunkHeader(scope: ChangedRegionScope, state: DiffParseState, line:
|
|
|
388
634
|
return true;
|
|
389
635
|
}
|
|
390
636
|
|
|
391
|
-
|
|
637
|
+
/**
|
|
638
|
+
* Reads one hunk body line using state's current file and target cursor, recording additions and advancing the cursor on context lines.
|
|
639
|
+
* Line tracking is skipped when no target file or cursor is active, or for whole-file coverage because the scope already includes every line.
|
|
640
|
+
*
|
|
641
|
+
* @param scope - Mutates rangesByFile on added lines unless whole-file coverage already applies.
|
|
642
|
+
* @param state - Mutates targetLine as added or context lines advance through the hunk.
|
|
643
|
+
* @param line - Hunk body line prefixed with `+`, space, or `-`.
|
|
644
|
+
* @returns Nothing. Updates scope ranges and state's targetLine cursor in place.
|
|
645
|
+
*/
|
|
392
646
|
function applyHunkBodyLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
|
|
393
647
|
if (!state.currentFile || state.targetLine === undefined || scope.wholeFiles.has(state.currentFile)) {
|
|
394
648
|
return;
|
|
@@ -403,7 +657,12 @@ function applyHunkBodyLine(scope: ChangedRegionScope, state: DiffParseState, lin
|
|
|
403
657
|
}
|
|
404
658
|
}
|
|
405
659
|
|
|
406
|
-
|
|
660
|
+
/**
|
|
661
|
+
* Normalizes a unified-diff target-header path for finding lookup while preserving `/dev/null` as the deleted-target marker.
|
|
662
|
+
*
|
|
663
|
+
* @param rawPath - Raw path suffix extracted after the `+++ ` header prefix.
|
|
664
|
+
* @returns Normalized forward-slash path relative to the diff root, or `/dev/null` for deleted targets.
|
|
665
|
+
*/
|
|
407
666
|
function diffPath(rawPath: string): string {
|
|
408
667
|
const trimmed = rawPath.trim();
|
|
409
668
|
if (trimmed === "/dev/null") {
|
|
@@ -412,13 +671,27 @@ function diffPath(rawPath: string): string {
|
|
|
412
671
|
return trimmed.replace(/^"?(?:a|b)\//, "").replace(/"$/, "").replaceAll("\\", "/");
|
|
413
672
|
}
|
|
414
673
|
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
674
|
+
/**
|
|
675
|
+
* Collects new, non-ignored files for a working-tree review because Git has no hunks yet for these files.
|
|
676
|
+
* Reads NUL-separated paths from `git ls-files` to keep filenames with spaces or newlines intact.
|
|
677
|
+
*
|
|
678
|
+
* @param changedScope - Attribution mode assigned to the resulting scope.
|
|
679
|
+
* @param projectRoot - Directory passed to Git when listing untracked files.
|
|
680
|
+
* @returns Scope marking all untracked non-ignored files as whole-file changes, or empty sets if none exist.
|
|
681
|
+
*/
|
|
682
|
+
function untrackedFileScope(changedScope: ChangedScopeMode, projectRoot: string): ChangedRegionScope {
|
|
683
|
+
const untracked = new Set(gitOutput(["ls-files", "-z", "--others", "--exclude-standard"], projectRoot).split("\0").filter(Boolean));
|
|
418
684
|
return { mode: changedScope, rangesByFile: new Map(), wholeFiles: untracked, changedFiles: new Set(untracked) };
|
|
419
685
|
}
|
|
420
686
|
|
|
421
|
-
|
|
687
|
+
/**
|
|
688
|
+
* Combines staged, unstaged, and untracked input scopes into a single scope under changedScope mode.
|
|
689
|
+
* Whole-file coverage takes precedence over hunk ranges for the same file.
|
|
690
|
+
*
|
|
691
|
+
* @param scopes - Input scopes whose changed files, whole files, and hunk ranges are merged.
|
|
692
|
+
* @param changedScope - Attribution mode assigned to the combined scope.
|
|
693
|
+
* @returns New merged scope combining all input changes.
|
|
694
|
+
*/
|
|
422
695
|
function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
423
696
|
const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
|
|
424
697
|
for (const scope of scopes) {
|
|
@@ -441,12 +714,24 @@ function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMod
|
|
|
441
714
|
return merged;
|
|
442
715
|
}
|
|
443
716
|
|
|
444
|
-
|
|
717
|
+
/**
|
|
718
|
+
* Adds a changed line range to the entry for filePath, creating it if absent and merging overlaps or adjacent ranges.
|
|
719
|
+
*
|
|
720
|
+
* @param rangesByFile - Mutates the per-file range list for filePath in place.
|
|
721
|
+
* @param filePath - Target file path whose changed ranges are being updated.
|
|
722
|
+
* @param range - Inclusive line range to insert and merge.
|
|
723
|
+
* @returns Nothing. Mutates rangesByFile in place with the sorted, merged ranges for filePath.
|
|
724
|
+
*/
|
|
445
725
|
function addRange(rangesByFile: Map<string, ChangedRange[]>, filePath: string, range: ChangedRange): void {
|
|
446
726
|
rangesByFile.set(filePath, mergeRanges([...(rangesByFile.get(filePath) ?? []), range]));
|
|
447
727
|
}
|
|
448
728
|
|
|
449
|
-
|
|
729
|
+
/**
|
|
730
|
+
* Builds a sorted list of line ranges, merging overlaps and adjacency so downstream checks stay deterministic.
|
|
731
|
+
*
|
|
732
|
+
* @param ranges - Unsorted or potentially overlapping inclusive line ranges.
|
|
733
|
+
* @returns New sorted, non-overlapping, non-adjacent inclusive line ranges.
|
|
734
|
+
*/
|
|
450
735
|
function mergeRanges(ranges: ChangedRange[]): ChangedRange[] {
|
|
451
736
|
const sorted = [...ranges].sort((left, right) => left.start - right.start || left.end - right.end);
|
|
452
737
|
const merged: ChangedRange[] = [];
|
|
@@ -461,7 +746,23 @@ function mergeRanges(ranges: ChangedRange[]): ChangedRange[] {
|
|
|
461
746
|
return merged;
|
|
462
747
|
}
|
|
463
748
|
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
749
|
+
/**
|
|
750
|
+
* Spawns git with the caller's argument array and returns UTF-8 stdout, which can be empty when git has no changes to report.
|
|
751
|
+
*
|
|
752
|
+
* @param args - Git CLI flags and arguments passed directly to the executable.
|
|
753
|
+
* @param projectRoot - Working directory used for the Git subprocess.
|
|
754
|
+
* @returns UTF-8 standard output produced by Git.
|
|
755
|
+
* @throws {ChangedRegionError} If Git cannot read the changes from projectRoot.
|
|
756
|
+
*/
|
|
757
|
+
function gitOutput(args: string[], projectRoot: string): string {
|
|
758
|
+
try {
|
|
759
|
+
return execFileSync("git", args, { cwd: projectRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
760
|
+
} catch (error) {
|
|
761
|
+
// For example, `--since main` can fail in a shallow checkout where that branch is missing.
|
|
762
|
+
// When Git supplies no detail, the user still sees that the change selection failed.
|
|
763
|
+
const detail = error instanceof Error && "stderr" in error && typeof error.stderr === "string"
|
|
764
|
+
? error.stderr.split(/\r?\n/u)[0]
|
|
765
|
+
: undefined;
|
|
766
|
+
throw new ChangedRegionError(`Unable to read the requested Git changes${detail ? `: ${detail}` : "."}`);
|
|
767
|
+
}
|
|
467
768
|
}
|