@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.
Files changed (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
package/src/discovery.ts CHANGED
@@ -1,30 +1,31 @@
1
- // Filesystem discovery, ignore-policy matching, and display-path normalization for deterministic scans.
1
+ // Discovers scannable TypeScript, JavaScript, and config files under a project root for every CLI command.
2
+ //
3
+ // Owns the single allowlist of scannable extensions (`pushSourceFile`), applies ignore rules in precedence order
4
+ // (`paths.ignore`, VCS directories, `.gitignore`, third-party/minified defaults, and fallback directories), and normalizes display paths.
2
5
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
6
  import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
4
7
  import type { AnalysisOptions, Config, IgnoreSource, ScanSurfaceNote, SkippedPath } from "./types.ts";
5
8
 
6
- // `absolutePath` is what `node:fs` operates on; `displayPath` is project-relative inside the run
7
- // root and absolute outside it. They must stay aligned - diverging them breaks fingerprint stability.
9
+ // `absolutePath` is what `node:fs` operates on; `displayPath` is project-relative inside the run root and absolute outside it.
10
+ // Both paths must stay aligned because finding fingerprints hash `displayPath`.
8
11
  export interface SourceFile {
9
12
  absolutePath: string;
10
13
  displayPath: string;
11
14
  isScript: boolean;
12
15
  }
13
16
 
14
- // Mutable accumulator used during the walk. `ignoredPaths` is a Set because the walker may visit
15
- // the same parent path through multiple roots; finalised into a sorted array on return.
17
+ // Mutable accumulator used during the directory walk; `skipped` is keyed by display path so repeated roots deduplicate before sorting.
16
18
  interface SourceDiscovery {
17
19
  files: SourceFile[];
18
20
  missingPaths: string[];
19
21
  skipped: Map<string, SkippedPath>;
20
22
  }
21
23
 
22
- // Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths` (the
23
- // back-compatible string[] of excluded paths) and `skipped` (the same paths enriched with ignore
24
- // source + matched pattern) are sorted so reports stay deterministic even when the underlying
25
- // filesystem returns directory entries in arbitrary order. `notes` carries one entry per requested
26
- // input that exists but contributed zero analysable files, so an all-skipped scan is never a
27
- // silent zero-finding success.
24
+ // Deterministic discovery output returned to the analyser and `check-ignore`:
25
+ //
26
+ // - `files` are sorted and deduplicated by `displayPath` so reports never depend on filesystem readdir order;
27
+ // - `ignoredPaths` and `skipped` record excluded paths with their ignore source and matched pattern;
28
+ // - `notes` lists existing targets that produced zero analysable files so an all-skipped run never looks silently clean.
28
29
  export interface SourceDiscoveryResult {
29
30
  files: SourceFile[];
30
31
  missingPaths: string[];
@@ -33,8 +34,7 @@ export interface SourceDiscoveryResult {
33
34
  notes: ScanSurfaceNote[];
34
35
  }
35
36
 
36
- // A single line from a `.gitignore`. The combination of `isAnchored`, `isDirectoryOnly`, and `hasSlash`
37
- // reproduces git's documented matching semantics; missing any one of them yields wrong matches.
37
+ // One parsed `.gitignore` line whose flags (`isAnchored`, `isDirectoryOnly`, `hasSlash`, `isNegated`) preserve git's matching semantics.
38
38
  interface GitIgnoreRule {
39
39
  basePath: string;
40
40
  pattern: string;
@@ -44,9 +44,15 @@ interface GitIgnoreRule {
44
44
  hasSlash: boolean;
45
45
  }
46
46
 
47
- // Public entry point. Reads from the filesystem and returns a sorted, deduped, deterministic
48
- // result so finding ordering and report-path metadata remain stable across runs - this is part of
49
- // the schema invariant that makes baseline matching reproducible.
47
+ /**
48
+ * Reads the filesystem, resolving options' paths against projectRoot and using config and options to decide what to skip.
49
+ * With no paths, scans projectRoot. Deduplicates files by absolute path and sorts files and skips to preserve stable report order.
50
+ *
51
+ * @param projectRoot - base directory used to resolve requested paths and format report paths
52
+ * @param options - scan options supplying target paths and ignore bypass settings
53
+ * @param config - user configuration supplying explicit ignore patterns
54
+ * @returns discovered files, missing paths, skipped paths and reasons, and notes for inputs that add no files or missing paths
55
+ */
50
56
  export function discoverSources(projectRoot: string, options: AnalysisOptions, config: Config): SourceDiscoveryResult {
51
57
  const discovery: SourceDiscovery = { files: [], missingPaths: [], skipped: new Map<string, SkippedPath>() };
52
58
  const inputs = options.paths.length > 0 ? options.paths : ["."];
@@ -67,9 +73,14 @@ export function discoverSources(projectRoot: string, options: AnalysisOptions, c
67
73
  return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped, notes };
68
74
  }
69
75
 
70
- // A requested input that exists but contributed no analysable files is a per-input note, never a
71
- // diagnostic - exit codes stay unchanged. The skip count names the likely cause (parent gitignore
72
- // or config ignore rules hiding the whole subtree) so the caller does not read 0 findings as clean.
76
+ /**
77
+ * Builds an informational note for an existing input that contributed no analysable files, so zero findings cannot be mistaken for a clean scan.
78
+ * A positive count reports newly recorded skips, while a zero count reports no analysable source files.
79
+ *
80
+ * @param input - requested file or directory path that produced no analysable files
81
+ * @param skippedCount - number of newly recorded skipped paths under the input
82
+ * @returns scan surface note describing why the input contributed no analysable files
83
+ */
73
84
  function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote {
74
85
  const cause = skippedCount > 0
75
86
  ? `${skippedCount} path(s) under it were excluded by ignore rules`
@@ -81,11 +92,18 @@ function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote
81
92
  };
82
93
  }
83
94
 
84
- // Resolves the input against `node:fs`. Missing inputs go into `missingPaths` so the CLI can
85
- // report them as diagnostics rather than silently producing no findings. CI output depends on that
86
- // distinction. An explicitly supplied file still honours config `paths.ignore` (authoritative in
87
- // every invocation, per ADR-007); default/gitignore stay directory-walk-only (ADR-003), so passing
88
- // empty gitignore rules here keeps an explicit file scannable unless config excludes it.
95
+ /**
96
+ * Collects files, missing inputs, and exclusion reasons for one requested path.
97
+ * Explicit files honour config and VCS exclusions and bypass Git ignore rules and all other default exclusions.
98
+ * If no exclusion matches, an explicit file outside the scan allowlist adds no entry.
99
+ *
100
+ * @param projectRoot - base directory for resolving input and formatting report paths
101
+ * @param input - requested file or directory path
102
+ * @param options - scan options controlling inclusion of ignored paths
103
+ * @param config - user configuration supplying explicit ignore patterns
104
+ * @param discovery - accumulator mutated with files, missingPaths, and skipped entries
105
+ * @returns Nothing. Records discovered files, missing paths, or exclusions in discovery.
106
+ */
89
107
  function discoverSourceInput(projectRoot: string, input: string, options: AnalysisOptions, config: Config, discovery: SourceDiscovery): void {
90
108
  const absolute = absolutize(projectRoot, input);
91
109
  if (!existsSync(absolute)) {
@@ -95,7 +113,16 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
95
113
  const stats = statSync(absolute);
96
114
  if (stats.isFile()) {
97
115
  const display = displayPath(projectRoot, absolute);
98
- const match = classifyIgnore(display, false, options, config, []);
116
+ const match = classifyIgnore({
117
+ projectRoot,
118
+ absolute,
119
+ display,
120
+ isDirectory: false,
121
+ options,
122
+ config,
123
+ gitIgnoreRules: [],
124
+ isExplicitFile: true,
125
+ });
99
126
  if (match) {
100
127
  discovery.skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
101
128
  return;
@@ -107,8 +134,18 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
107
134
  walk(projectRoot, absolute, options, config, discovery.skipped, discovery.files, gitIgnoreRules);
108
135
  }
109
136
 
110
- // Depth-first directory walk that applies ignore rules before recursing, because descending into
111
- // an excluded subtree would waste reads; skips record source and pattern to avoid silent exclusions.
137
+ /**
138
+ * Reads directory entries depth first to collect supported files and prunes ignored subtrees to avoid reading their contents.
139
+ *
140
+ * @param projectRoot - base directory for report paths and ignore-rule ownership
141
+ * @param directory - directory whose entries are scanned
142
+ * @param options - controls whether to bypass Git rules and non-VCS defaults
143
+ * @param config - user configuration supplying explicit ignore patterns
144
+ * @param skipped - map mutated with excluded paths and their reasons
145
+ * @param files - array mutated with admitted source records
146
+ * @param gitIgnoreRules - inherited rules extended for each child directory unless ignored paths are included
147
+ * @returns Nothing. Adds eligible source records to files and records exclusions in skipped.
148
+ */
112
149
  function walk(
113
150
  projectRoot: string,
114
151
  directory: string,
@@ -122,9 +159,21 @@ function walk(
122
159
  const absolute = join(directory, entry.name);
123
160
  const display = displayPath(projectRoot, absolute);
124
161
  if (entry.isDirectory() || entry.isFile()) {
125
- const match = classifyIgnore(display, entry.isDirectory(), options, config, gitIgnoreRules);
162
+ const match = classifyIgnore({
163
+ projectRoot,
164
+ absolute,
165
+ display,
166
+ isDirectory: entry.isDirectory(),
167
+ options,
168
+ config,
169
+ gitIgnoreRules,
170
+ isExplicitFile: false,
171
+ });
126
172
  if (match) {
127
- skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
173
+ // Default minified-file exclusions record skips only for scannable file types; explicit config or .gitignore rules always record skips.
174
+ if (match.source !== "default" || match.pattern !== MINIFIED_FILE_PATTERN || isScannableSourceFile(absolute)) {
175
+ skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
176
+ }
128
177
  continue;
129
178
  }
130
179
  }
@@ -145,24 +194,84 @@ export const TEXT_FILE_EXTENSIONS: readonly string[] = ["conf", "config", "env",
145
194
  /** Extensionless credential files that stay scannable without admitting every dotfile. */
146
195
  export const EXACT_SECRET_TEXT_FILES: readonly string[] = [".npmrc", ".pypirc", ".envrc", ".netrc"];
147
196
 
148
- // Single source of truth for which extensions count as scannable. Adding a new file kind to the
149
- // lists above will expand the rule set's reach across an entire project - the scan surface is also
150
- // stated in prose across seven documents, so `release-truth.test.ts` pins these lists literally.
197
+ /**
198
+ * Adds a supported path to the scan list; release-truth.test.ts pins the allowlists defining the documented scan surface.
199
+ *
200
+ * @param projectRoot - base directory for formatting the file's report path
201
+ * @param absolutePath - candidate file path checked against the script and text allowlists
202
+ * @param files - accumulator receiving a source record for supported files; unsupported paths leave it unchanged
203
+ * @returns Nothing. Adds the source record for a supported path to files.
204
+ */
151
205
  function pushSourceFile(projectRoot: string, absolutePath: string, files: SourceFile[]): void {
152
- const extension = extname(absolutePath).slice(1).toLowerCase();
153
- const name = basename(absolutePath);
154
- const isScript = SCRIPT_FILE_EXTENSIONS.includes(extension);
155
- const isText = TEXT_FILE_EXTENSIONS.includes(extension) || name.startsWith(".env") || EXACT_SECRET_TEXT_FILES.includes(name);
156
- if (isScript || isText) {
157
- files.push({ absolutePath, displayPath: displayPath(projectRoot, absolutePath), isScript });
206
+ if (isScannableSourceFile(absolutePath)) {
207
+ files.push({ absolutePath, displayPath: displayPath(projectRoot, absolutePath), isScript: isScriptFile(absolutePath) });
158
208
  }
159
209
  }
160
210
 
161
- // The default-ignore list is part of the documented schema contract: callers can override with
162
- // `--include-ignored`, but the list itself must not silently change between releases without notice.
163
- function isDefaultIgnoredDir(path: string): boolean {
164
- const first = path.split("/")[0] ?? path;
165
- return [".git", ".hg", ".svn", ".idea", ".vscode", "build", "cache", "coverage", "dist", "generated", "node_modules", "target", "tmp", "vendor"].includes(first);
211
+ /**
212
+ * Reports whether pushSourceFile would admit a path, so the walk lists a skipped minified file only when it is scannable.
213
+ *
214
+ * @param absolutePath - candidate file path whose extension and basename are checked against script and text allowlists
215
+ * @returns true when the file matches a supported script, text, or secret-file allowlist entry
216
+ */
217
+ function isScannableSourceFile(absolutePath: string): boolean {
218
+ const name = basename(absolutePath);
219
+ const isText = TEXT_FILE_EXTENSIONS.includes(extname(absolutePath).slice(1).toLowerCase()) || name.startsWith(".env") || EXACT_SECRET_TEXT_FILES.includes(name);
220
+ return isScriptFile(absolutePath) || isText;
221
+ }
222
+
223
+ /**
224
+ * Reports whether a path's extension is parsed as code.
225
+ *
226
+ * @param absolutePath - candidate file path whose lowercase extension is checked
227
+ * @returns true when the extension belongs to the script file allowlist
228
+ */
229
+ function isScriptFile(absolutePath: string): boolean {
230
+ return SCRIPT_FILE_EXTENSIONS.includes(extname(absolutePath).slice(1).toLowerCase());
231
+ }
232
+
233
+ const VCS_DIRECTORIES = [".git", ".hg", ".svn"] as const;
234
+ const FALLBACK_DIRECTORIES = [".fleet", ".idea", ".vscode", "build", "coverage", "node_modules"] as const;
235
+
236
+ // Third-party copy directories plus `dist`, skipped at any depth under ASCII case folding even when a `.gitignore` governs the directory.
237
+ // `build` and `coverage` stay fallback-only (FAMILY-CONTRACT.md section 7, amended by precision-floor M04).
238
+ const THIRD_PARTY_DIRECTORIES: readonly string[] = ["bower_components", "dist", "third-party", "third_party", "vendor", "vendors"];
239
+
240
+ /** Pattern recorded for a minified file such as `jquery.min.js`, which section 7 skips as generated. */
241
+ export const MINIFIED_FILE_PATTERN = "*.min.*";
242
+
243
+ /**
244
+ * Folds only ASCII capital letters to lowercase so directory and filename checks use consistent case folding.
245
+ *
246
+ * @param pathComponent - single path segment or filename to normalize
247
+ * @returns the path component with ASCII uppercase letters converted to lowercase
248
+ */
249
+ function asciiLower(pathComponent: string): string {
250
+ return pathComponent.replace(/[A-Z]/gu, (character) => character.toLowerCase());
251
+ }
252
+
253
+ /**
254
+ * Finds the outermost third-party or build-output directory on display using ASCII-lowercased components.
255
+ *
256
+ * @param display - slash-separated display path to inspect
257
+ * @param isDirectory - controls whether to check the final component, so a/Vendor/x.ts gives vendor and a file named dist gives no match
258
+ * @returns lowercase matched directory name, or undefined when this policy supplies no exclusion
259
+ */
260
+ function matchedThirdPartyDirectory(display: string, isDirectory: boolean): string | undefined {
261
+ const components = display.split("/");
262
+ const directories = isDirectory ? components : components.slice(0, -1);
263
+ return directories.map(asciiLower).find((component) => THIRD_PARTY_DIRECTORIES.includes(component));
264
+ }
265
+
266
+ /**
267
+ * Reports whether the base name has an ASCII case-insensitive .min. marker directly before its final extension.
268
+ * For example, jquery.MIN.js matches, while app.min.js.map and admin.mini.js do not.
269
+ *
270
+ * @param name - file basename to check for a minified marker
271
+ * @returns true when the name ends with a .min. marker followed by a single final extension
272
+ */
273
+ function isMinifiedName(name: string): boolean {
274
+ return /\.min\.[^.]+$/u.test(asciiLower(name));
166
275
  }
167
276
 
168
277
  // The matched ignore source and the exact pattern that excluded a path. Returned by `classifyIgnore`.
@@ -171,26 +280,55 @@ interface IgnoreMatch {
171
280
  pattern: string;
172
281
  }
173
282
 
174
- // Single ignore decision shared by the directory walk, explicit-file handling, and `check-ignore`,
175
- // so there is exactly one glob/ignore implementation. Returns the first matching source with its
176
- // pattern, or undefined. Evaluation order is default -> gitignore -> config, but config is the
177
- // authoritative source: it is checked regardless of `--include-ignored` and applies to explicit file
178
- // operands (which pass empty gitignore rules so default/gitignore cannot match them, per ADR-003).
179
- function classifyIgnore(display: string, isDirectory: boolean, options: AnalysisOptions, config: Config, gitIgnoreRules: GitIgnoreRule[]): IgnoreMatch | undefined {
180
- const defaultMatch = defaultIgnoreMatch(display, isDirectory, options, false);
181
- if (defaultMatch) {
182
- return defaultMatch;
183
- }
184
- if (!options.shouldIncludeIgnored) {
185
- const rule = matchedGitIgnoreRule(gitIgnoreRules, display, isDirectory);
186
- if (rule) {
187
- return { source: "gitignore", pattern: rule.pattern };
188
- }
189
- }
283
+ // Bundles one ignore decision so adding policy context does not expand the helper's parameter list.
284
+ interface IgnoreClassificationInput {
285
+ projectRoot: string;
286
+ absolute: string;
287
+ display: string;
288
+ isDirectory: boolean;
289
+ options: AnalysisOptions;
290
+ config: Config;
291
+ gitIgnoreRules: GitIgnoreRule[];
292
+ isExplicitFile: boolean;
293
+ }
294
+
295
+ /**
296
+ * Classifies the path in input using its location, kind, scan options, config, and Git ignore rules.
297
+ * Config and VCS exclusions always apply; explicit files and --include-ignored bypass Git and remaining default exclusions.
298
+ *
299
+ * @param input - bundled path coordinates, kind, options, config, and inherited Git ignore rules
300
+ * @returns the first matching ignore source and pattern, or undefined to keep the path eligible
301
+ */
302
+ function classifyIgnore(input: IgnoreClassificationInput): IgnoreMatch | undefined {
303
+ const { projectRoot, absolute, display, isDirectory, options, config, gitIgnoreRules, isExplicitFile } = input;
190
304
  const configPattern = config.ignoredPaths.find((pattern) => pathMatches(pattern, display));
191
305
  if (configPattern !== undefined) {
192
306
  return { source: "config", pattern: configPattern };
193
307
  }
308
+ // Match the absolute path, not the report path: `analyse ../repo/.git/config.ts` roots the run inside `.git`, which drops the component from `display`.
309
+ const vcsComponent = matchedDirectoryComponent(absolute.replaceAll("\\", "/"), VCS_DIRECTORIES);
310
+ if (vcsComponent !== undefined) {
311
+ return { source: "default", pattern: `${vcsComponent}/` };
312
+ }
313
+ if (options.shouldIncludeIgnored || isExplicitFile) {
314
+ return undefined;
315
+ }
316
+ const rule = matchedGitIgnoreRule(gitIgnoreRules, display, isDirectory);
317
+ if (rule) {
318
+ return { source: "gitignore", pattern: rule.pattern };
319
+ }
320
+ // When Git has no match, a third-party directory takes priority over a minified file name in the reported reason.
321
+ const thirdPartyDirectory = matchedThirdPartyDirectory(display, isDirectory);
322
+ if (thirdPartyDirectory !== undefined) {
323
+ return { source: "default", pattern: `${thirdPartyDirectory}/` };
324
+ }
325
+ if (!isDirectory && isMinifiedName(basename(display))) {
326
+ return { source: "default", pattern: MINIFIED_FILE_PATTERN };
327
+ }
328
+ const fallbackComponent = matchedDirectoryComponent(display, FALLBACK_DIRECTORIES);
329
+ if (fallbackComponent !== undefined && fallbackAppliesAt(projectRoot, absolute)) {
330
+ return { source: "default", pattern: `${fallbackComponent}/` };
331
+ }
194
332
  return undefined;
195
333
  }
196
334
 
@@ -204,34 +342,98 @@ export interface PathIgnoreClassification {
204
342
  pattern?: string;
205
343
  }
206
344
 
207
- // Classifies one caller-supplied path without analysing it, preserving the shared ignore contract.
345
+ /**
346
+ * Reports the shared ignore decision for one path without scanning its contents.
347
+ * Existing regular files bypass Git and default exclusions, while config and VCS exclusions still apply.
348
+ *
349
+ * @param projectRoot - base directory for resolving input and formatting the reported path
350
+ * @param input - path to classify. Missing paths are treated as non-directories and receive no explicit-file bypass
351
+ * @param options - controls whether ignored paths are included
352
+ * @param config - user configuration supplying explicit ignore patterns
353
+ * @returns display path and isIgnored; ignored paths also include the exclusion source and pattern
354
+ */
208
355
  export function classifyPathIgnore(projectRoot: string, input: string, options: AnalysisOptions, config: Config): PathIgnoreClassification {
209
356
  const absolute = absolutize(projectRoot, input);
210
357
  const display = displayPath(projectRoot, absolute);
211
- const isDirectory = existsSync(absolute) && statSync(absolute).isDirectory();
212
- const defaultMatch = defaultIgnoreMatch(display, isDirectory, options, true);
213
- if (defaultMatch) {
214
- return { path: display, isIgnored: true, source: defaultMatch.source, pattern: defaultMatch.pattern };
215
- }
216
- const ruleDirectory = isDirectory ? absolute : dirname(absolute);
217
- const gitIgnoreRules = options.shouldIncludeIgnored || !isDirectory ? [] : gitIgnoreRulesForDirectory(projectRoot, ruleDirectory);
218
- const match = classifyIgnore(display, isDirectory, options, config, gitIgnoreRules);
358
+ const exists = existsSync(absolute);
359
+ const isDirectory = exists && statSync(absolute).isDirectory();
360
+ const isExplicitFile = exists && statSync(absolute).isFile();
361
+ const gitIgnoreLookupDirectory = isInsideProject(projectRoot, dirname(absolute)) ? dirname(absolute) : projectRoot;
362
+ const gitIgnoreRules = options.shouldIncludeIgnored || isExplicitFile
363
+ ? []
364
+ : gitIgnoreRulesForDirectory(projectRoot, gitIgnoreLookupDirectory);
365
+ const match = classifyIgnore({
366
+ projectRoot,
367
+ absolute,
368
+ display,
369
+ isDirectory,
370
+ options,
371
+ config,
372
+ gitIgnoreRules,
373
+ isExplicitFile,
374
+ });
219
375
  return match ? { path: display, isIgnored: true, source: match.source, pattern: match.pattern } : { path: display, isIgnored: false };
220
376
  }
221
377
 
222
- // Default ignores are directory-walk policy; `check-ignore` also needs parent-dir answers for
223
- // changed-file prefilters so generated paths under `dist/` agree with what `analyse .` would scan.
224
- function defaultIgnoreMatch(display: string, isDirectory: boolean, options: AnalysisOptions, includeParentDir: boolean): IgnoreMatch | undefined {
225
- if (options.shouldIncludeIgnored) {
226
- return undefined;
378
+ /**
379
+ * Finds the first path component owned by one directory-policy set.
380
+ *
381
+ * @param path - slash-separated path whose components are inspected
382
+ * @param candidates - directory names belonging to a specific exclusion policy
383
+ * @returns the first matching component, or undefined when no component belongs to candidates
384
+ */
385
+ function matchedDirectoryComponent(path: string, candidates: readonly string[]): string | undefined {
386
+ return path.split("/").find((component) => candidates.includes(component));
387
+ }
388
+
389
+ /**
390
+ * Reports whether fallback exclusions apply to absolute: outside projectRoot they always apply.
391
+ * Inside projectRoot they apply only if no regular .gitignore exists from the root through the candidate's parent.
392
+ *
393
+ * @param projectRoot - run root directory that bounds .gitignore lookup
394
+ * @param absolute - resolved candidate path being evaluated
395
+ * @returns true when fallback directory exclusions govern the candidate path
396
+ */
397
+ function fallbackAppliesAt(projectRoot: string, absolute: string): boolean {
398
+ if (!isInsideProject(projectRoot, absolute)) {
399
+ return true;
227
400
  }
228
- const defaultIgnored = includeParentDir ? isDefaultIgnoredDir(display) : isDirectory && isDefaultIgnoredDir(display);
229
- return defaultIgnored ? { source: "default", pattern: `${display.split("/")[0] ?? display}/` } : undefined;
401
+ const parentDirectory = dirname(absolute);
402
+ const relativeParent = isInsideProject(projectRoot, parentDirectory)
403
+ ? relative(projectRoot, parentDirectory).replaceAll("\\", "/")
404
+ : "";
405
+ const segments = relativeParent === "" ? [] : relativeParent.split("/");
406
+ let current = projectRoot;
407
+ if (isGitIgnoreFile(join(current, ".gitignore"))) {
408
+ return false;
409
+ }
410
+ for (const segment of segments) {
411
+ current = join(current, segment);
412
+ if (isGitIgnoreFile(join(current, ".gitignore"))) {
413
+ return false;
414
+ }
415
+ }
416
+ return true;
417
+ }
418
+
419
+ /**
420
+ * Distinguishes a regular .gitignore file from a missing path or directory.
421
+ *
422
+ * @param path - filesystem path to check for a regular file
423
+ * @returns true when the path exists on the filesystem and is a regular file
424
+ */
425
+ function isGitIgnoreFile(path: string): boolean {
426
+ return existsSync(path) && statSync(path).isFile();
230
427
  }
231
428
 
232
- // Walks .gitignore files top-down from project root to the target directory so child rules can
233
- // override parents - this must match git's documented inheritance order or the scan will diverge
234
- // from `git status` on the same tree, and reads each `.gitignore` it encounters along the way.
429
+ /**
430
+ * Collects .gitignore rules from projectRoot through directory in parent-before-child order, so later child rules can override parents.
431
+ * Reads every regular .gitignore along the chain.
432
+ *
433
+ * @param projectRoot - root directory beyond which .gitignore files are not read
434
+ * @param directory - target directory whose ancestor .gitignore chain is loaded
435
+ * @returns ordered ignore rules, or an empty list outside projectRoot or when no file contributes usable rules
436
+ */
235
437
  function gitIgnoreRulesForDirectory(projectRoot: string, directory: string): GitIgnoreRule[] {
236
438
  if (!isInsideProject(projectRoot, directory)) {
237
439
  return [];
@@ -248,8 +450,15 @@ function gitIgnoreRulesForDirectory(projectRoot: string, directory: string): Git
248
450
  return rules;
249
451
  }
250
452
 
251
- // Reads one `.gitignore` and appends its rules to the inherited stack. Returns the original array
252
- // untouched when no file exists so the walker can pass results around without spurious allocations.
453
+ /**
454
+ * Reads directory's .gitignore with rule paths based at projectRoot and appends its rules after inheritedRules.
455
+ * Preserves the caller's inherited stack by returning a new array when rules are added.
456
+ *
457
+ * @param projectRoot - root directory used to compute the .gitignore basePath
458
+ * @param directory - directory inspected for a regular .gitignore file
459
+ * @param inheritedRules - parent ignore rules that stay unchanged when no usable rules are found
460
+ * @returns inheritedRules unchanged if no usable rules apply, otherwise a new combined array
461
+ */
253
462
  function appendGitIgnoreRules(projectRoot: string, directory: string, inheritedRules: GitIgnoreRule[]): GitIgnoreRule[] {
254
463
  const ignoreFile = join(directory, ".gitignore");
255
464
  if (!existsSync(ignoreFile) || !statSync(ignoreFile).isFile()) {
@@ -261,8 +470,13 @@ function appendGitIgnoreRules(projectRoot: string, directory: string, inheritedR
261
470
  return parsedRules.length > 0 ? [...inheritedRules, ...parsedRules] : inheritedRules;
262
471
  }
263
472
 
264
- // One rule per non-empty, non-comment line. Empty results are dropped here so downstream matchers
265
- // never need to guard against undefined patterns.
473
+ /**
474
+ * Parses .gitignore source into ordered rules owned by basePath, dropping comments, blanks, and marker-only lines.
475
+ *
476
+ * @param source - raw .gitignore file text with LF or CRLF line endings
477
+ * @param basePath - directory path owning these rules relative to the project root, or empty string for the root
478
+ * @returns ordered parsed rules, or an empty array when no usable rules remain
479
+ */
266
480
  function parseGitIgnoreRules(source: string, basePath: string): GitIgnoreRule[] {
267
481
  const rules: GitIgnoreRule[] = [];
268
482
  for (const rawLine of source.replace(/\r\n/g, "\n").split("\n")) {
@@ -274,9 +488,13 @@ function parseGitIgnoreRules(source: string, basePath: string): GitIgnoreRule[]
274
488
  return rules;
275
489
  }
276
490
 
277
- // Extracts the four flags git applies per pattern: negation (`!`), directory-only (trailing `/`),
278
- // path-scoped (leading `/` or contains `/`), and the cleaned pattern itself. Undefined return means
279
- // the line was blank or a comment - callers must not treat it as a "match nothing" rule.
491
+ /**
492
+ * Parses rawLine from the .gitignore owned by basePath into its normalized pattern and matching flags.
493
+ *
494
+ * @param rawLine - single line from a .gitignore file
495
+ * @param basePath - owning directory path relative to the project root; an empty string attaches the rule to the root
496
+ * @returns parsed rule, or undefined for comments, blank lines, or lines whose negation or slash markers leave no pattern
497
+ */
280
498
  function parseGitIgnoreRule(rawLine: string, basePath: string): GitIgnoreRule | undefined {
281
499
  const initial = unescapedGitIgnoreLine(rawLine);
282
500
  if (!initial) {
@@ -296,8 +514,12 @@ function parseGitIgnoreRule(rawLine: string, basePath: string): GitIgnoreRule |
296
514
  return { basePath, pattern, isNegated, isDirectoryOnly, isAnchored, hasSlash: pattern.includes("/") };
297
515
  }
298
516
 
299
- // Blank and comment lines return undefined so the caller can skip them cleanly. Trailing spaces are
300
- // ignored only when they are not escaped, matching gitignore's literal-space escape.
517
+ /**
518
+ * Normalizes a raw .gitignore line, ignoring trailing spaces only when they are not escaped to match gitignore's literal-space escape.
519
+ *
520
+ * @param rawLine - single line read from a .gitignore file
521
+ * @returns trimmed pattern text, or undefined for blank or comment lines so the caller can skip them cleanly
522
+ */
301
523
  function unescapedGitIgnoreLine(rawLine: string): string | undefined {
302
524
  const line = trimUnescapedTrailingSpaces(rawLine);
303
525
  if (line.length === 0 || line.startsWith("#")) {
@@ -306,8 +528,13 @@ function unescapedGitIgnoreLine(rawLine: string): string | undefined {
306
528
  return line;
307
529
  }
308
530
 
309
- // Gitignore treats trailing spaces as insignificant unless escaped. Walk back from the end so a
310
- // literal `\ ` stays part of the pattern while editor-added padding disappears.
531
+ /**
532
+ * Strips unescaped trailing spaces from a .gitignore line because Git treats them as padding.
533
+ * A backslash-escaped trailing space stays part of the pattern.
534
+ *
535
+ * @param rawLine - raw line from a .gitignore file
536
+ * @returns line text without unescaped trailing spaces
537
+ */
311
538
  function trimUnescapedTrailingSpaces(rawLine: string): string {
312
539
  let end = rawLine.length;
313
540
  while (end > 0 && rawLine[end - 1] === " " && !isEscapedAt(rawLine, end - 1)) {
@@ -316,8 +543,14 @@ function trimUnescapedTrailingSpaces(rawLine: string): string {
316
543
  return rawLine.slice(0, end);
317
544
  }
318
545
 
319
- // True when the character at `index` has an odd number of backslashes immediately before it.
320
- // Even runs cancel out because `\\ ` means a literal slash followed by an unescaped space.
546
+ /**
547
+ * Checks whether the character at index in source has an odd number of backslashes immediately before it.
548
+ * Even runs cancel out because a pair represents a literal backslash and leaves the next character unescaped.
549
+ *
550
+ * @param source - string containing the character to test
551
+ * @param index - zero-based position of the character in source
552
+ * @returns true when an odd run of backslashes precedes index
553
+ */
321
554
  function isEscapedAt(source: string, index: number): boolean {
322
555
  let slashCount = 0;
323
556
  for (let cursor = index - 1; cursor >= 0 && source[cursor] === "\\"; cursor -= 1) {
@@ -326,8 +559,13 @@ function isEscapedAt(source: string, index: number): boolean {
326
559
  return slashCount % 2 === 1;
327
560
  }
328
561
 
329
- // Strips leading and trailing slashes (those flags are already captured in `isAnchored` /
330
- // `isDirectoryOnly`) and collapses any internal `//` runs so the glob matcher sees canonical segments.
562
+ /**
563
+ * Builds the canonical matcher pattern for a gitignore line after its anchor and directory-only flags have been captured.
564
+ * Removes edge slashes and empty internal segments.
565
+ *
566
+ * @param line - unescaped gitignore line without negation prefix
567
+ * @returns normalized pattern, or an empty string for an all-slash line so the caller drops the rule
568
+ */
331
569
  function normalizedGitIgnorePattern(line: string): string {
332
570
  return line
333
571
  .replace(/^\/+/, "")
@@ -337,9 +575,15 @@ function normalizedGitIgnorePattern(line: string): string {
337
575
  .join("/");
338
576
  }
339
577
 
340
- // Sequential evaluation, last match wins. This is the same algorithm git uses and is the reason
341
- // negations later in a file (or in a child `.gitignore`) can reinstate previously ignored paths.
342
- // Returns the deciding rule (for source + pattern reporting) when the path ends up ignored.
578
+ /**
579
+ * Evaluates rules in inherited file order against display so later negations can clear an earlier exclusion.
580
+ * The last matching rule decides whether the path is ignored.
581
+ *
582
+ * @param rules - ordered .gitignore rules from root through parent directories
583
+ * @param display - candidate path formatted relative to the project root
584
+ * @param isDirectory - identifies whether the candidate path is a directory
585
+ * @returns the deciding rule for an ignored path, or undefined when no rule matches or the last match is a negation
586
+ */
343
587
  function matchedGitIgnoreRule(rules: GitIgnoreRule[], display: string, isDirectory: boolean): GitIgnoreRule | undefined {
344
588
  let matched: GitIgnoreRule | undefined;
345
589
  let isIgnored = false;
@@ -352,8 +596,15 @@ function matchedGitIgnoreRule(rules: GitIgnoreRule[], display: string, isDirecto
352
596
  return isIgnored ? matched : undefined;
353
597
  }
354
598
 
355
- // First rebases the display path against the rule's basePath (rules don't reach outside their
356
- // owning directory), then dispatches to the directory-only or file matcher.
599
+ /**
600
+ * Reports whether rule matches the candidate display path after rebasing it against the rule's owning directory.
601
+ * The owner never matches, and nested rules reject paths outside their base; files can still match through an ancestor directory.
602
+ *
603
+ * @param rule - parsed .gitignore rule to evaluate
604
+ * @param display - candidate project-relative display path supplied by discovery
605
+ * @param isDirectory - tells directory-only rules whether they can test the leaf itself
606
+ * @returns true when the rule matches the rebased path
607
+ */
357
608
  function gitIgnoreRuleMatches(rule: GitIgnoreRule, display: string, isDirectory: boolean): boolean {
358
609
  const relativePath = pathRelativeToBase(rule.basePath, display);
359
610
  if (relativePath === undefined || relativePath.length === 0) {
@@ -366,8 +617,14 @@ function gitIgnoreRuleMatches(rule: GitIgnoreRule, display: string, isDirectory:
366
617
  return gitIgnoreFileRuleMatches(rule, relativePath, isDirectory);
367
618
  }
368
619
 
369
- // Path-scoped patterns (with `/` or anchored) match against progressive sub-paths; bare patterns
370
- // match any path segment. Mirrors git's distinction between `foo` (any segment) and `dir/foo`.
620
+ /**
621
+ * Reports whether a non-directory-only rule matches relativePath, testing successive prefixes for path-scoped patterns and segments for bare ones.
622
+ *
623
+ * @param rule - parsed .gitignore rule without a trailing slash restriction
624
+ * @param relativePath - candidate path relative to the rule's owning directory
625
+ * @param isDirectory - candidate kind passed to the prefix helper while both files and directories include the leaf
626
+ * @returns true when the rule pattern matches any candidate prefix or segment
627
+ */
371
628
  function gitIgnoreFileRuleMatches(rule: GitIgnoreRule, relativePath: string, isDirectory: boolean): boolean {
372
629
  if (isPathScopedGitIgnoreRule(rule)) {
373
630
  return gitIgnorePathCandidates(relativePath, isDirectory, true).some((candidate) => gitIgnoreGlobMatches(rule.pattern, candidate));
@@ -375,8 +632,15 @@ function gitIgnoreFileRuleMatches(rule: GitIgnoreRule, relativePath: string, isD
375
632
  return relativePath.split("/").some((segment) => gitIgnoreGlobMatches(rule.pattern, segment));
376
633
  }
377
634
 
378
- // Like the file matcher but only considers directory segments - `node_modules/` must not match the
379
- // leaf file name even if a file happened to be called `node_modules`.
635
+ /**
636
+ * Reports whether a directory-only rule matches a directory in relativePath.
637
+ * A rule such as node_modules/ must skip a same-named file leaf while still matching ancestor directories.
638
+ *
639
+ * @param rule - parsed directory-only .gitignore rule
640
+ * @param relativePath - candidate path relative to the rule's owning directory
641
+ * @param isDirectory - includes the final segment as a candidate only when true
642
+ * @returns true when the rule pattern matches a directory prefix or directory segment
643
+ */
380
644
  function gitIgnoreDirectoryRuleMatches(rule: GitIgnoreRule, relativePath: string, isDirectory: boolean): boolean {
381
645
  if (isPathScopedGitIgnoreRule(rule)) {
382
646
  return gitIgnorePathCandidates(relativePath, isDirectory, false).some((candidate) => gitIgnoreGlobMatches(rule.pattern, candidate));
@@ -386,15 +650,26 @@ function gitIgnoreDirectoryRuleMatches(rule: GitIgnoreRule, relativePath: string
386
650
  return directorySegments.some((segment) => gitIgnoreGlobMatches(rule.pattern, segment));
387
651
  }
388
652
 
389
- // A rule is "path scoped" when it was anchored (leading `/`) or contained a `/` - both signal that
390
- // the pattern should be matched against multi-segment sub-paths rather than individual names.
653
+ /**
654
+ * Reports whether rule has a leading slash or an internal slash, so its pattern is tested against prefixes from its owning directory.
655
+ * A prefix can be a single component, such as the candidate for an anchored pattern with one name.
656
+ *
657
+ * @param rule - parsed .gitignore rule to inspect
658
+ * @returns true when the rule is anchored or contains an internal slash
659
+ */
391
660
  function isPathScopedGitIgnoreRule(rule: GitIgnoreRule): boolean {
392
661
  return rule.isAnchored || rule.hasSlash;
393
662
  }
394
663
 
395
- // Enumerates progressively longer prefixes of `relativePath` so a single-segment pattern can match
396
- // at any nesting depth. `shouldIncludeFilePath` controls whether the leaf segment is part of the prefix set
397
- // - directory-only rules omit it because `dir/` must not match a file called `dir`.
664
+ /**
665
+ * Builds successive prefixes of relativePath so a matching ancestor can exclude descendants.
666
+ * Excluding the leaf of a single-component file path yields an empty list because there is no ancestor prefix to test.
667
+ *
668
+ * @param relativePath - slash-separated path relative to the rule's owning directory
669
+ * @param isDirectory - includes the leaf prefix when true
670
+ * @param shouldIncludeFilePath - decides whether to include the leaf when isDirectory is false
671
+ * @returns ordered path prefixes from shallowest ancestor to the permitted leaf
672
+ */
398
673
  function gitIgnorePathCandidates(relativePath: string, isDirectory: boolean, shouldIncludeFilePath: boolean): string[] {
399
674
  const segments = relativePath.split("/");
400
675
  const limit = isDirectory || shouldIncludeFilePath ? segments.length : segments.length - 1;
@@ -405,15 +680,24 @@ function gitIgnorePathCandidates(relativePath: string, isDirectory: boolean, sho
405
680
  return candidates;
406
681
  }
407
682
 
408
- // Compiles the pattern on demand. Compilation is cheap relative to the surrounding walk so caching
409
- // across calls is not worth the cache-invalidation footgun.
683
+ /**
684
+ * Reports whether candidatePath matches the complete gitignore pattern.
685
+ *
686
+ * @param pattern - normalized gitignore glob pattern
687
+ * @param candidatePath - path prefix or segment tested against the compiled pattern
688
+ * @returns true when the entire candidatePath matches the pattern
689
+ */
410
690
  function gitIgnoreGlobMatches(pattern: string, candidatePath: string): boolean {
411
691
  return gitIgnoreGlobRegex(pattern).test(candidatePath);
412
692
  }
413
693
 
414
- // Translates a git glob into a JS RegExp. `**`, `*`, and `?` get their git-flavoured semantics:
415
- // `*` matches a single segment (`[^/]*`), `**` can cross segment boundaries, and `?` matches one
416
- // non-slash character.
694
+ /**
695
+ * Translates a git glob pattern into a JS RegExp with Git wildcard semantics.
696
+ * Single stars stay within a segment, supported double-star forms cross segments, and question marks match one non-slash character.
697
+ *
698
+ * @param pattern - normalized gitignore glob pattern
699
+ * @returns anchored regular expression matching complete candidate strings
700
+ */
417
701
  function gitIgnoreGlobRegex(pattern: string): RegExp {
418
702
  let source = "^";
419
703
  for (let index = 0; index < pattern.length; index += 1) {
@@ -424,8 +708,14 @@ function gitIgnoreGlobRegex(pattern: string): RegExp {
424
708
  return new RegExp(`${source}$`);
425
709
  }
426
710
 
427
- // One pattern character → one regex fragment. `*` dispatches to the star helper because `**` and
428
- // `**/ ` need special handling; everything else falls through to literal escape via `escapeRegex`.
711
+ /**
712
+ * Converts the token at index in pattern into a regex fragment, handling stars, wildcards, classes, and escapes.
713
+ * An unparsed class opener or trailing backslash is kept as a literal.
714
+ *
715
+ * @param pattern - normalized gitignore glob pattern
716
+ * @param index - zero-based cursor position in pattern
717
+ * @returns regex source fragment and the number of extra characters consumed past index
718
+ */
429
719
  function gitIgnoreGlobFragment(pattern: string, index: number): { source: string; skip: number } {
430
720
  const character = pattern[index] ?? "";
431
721
  if (character === "*") {
@@ -443,9 +733,14 @@ function gitIgnoreGlobFragment(pattern: string, index: number): { source: string
443
733
  return { source: escapeRegex(character), skip: 0 };
444
734
  }
445
735
 
446
- // Three star modes from the git spec: single `*` is segment-local, `**/` matches zero or more
447
- // segments, and trailing `**` matches anything. The `skip` return lets the caller advance past the
448
- // extra characters consumed.
736
+ /**
737
+ * Converts the star at index in pattern to regex source according to Git single-star and double-star rules.
738
+ * Leading or slash-delimited star pairs followed by a slash consume zero or more directories; trailing star pairs after a slash cross directories.
739
+ *
740
+ * @param pattern - normalized gitignore glob pattern
741
+ * @param index - index of the leading asterisk in pattern
742
+ * @returns regex source fragment and extra pattern character count consumed
743
+ */
449
744
  function gitIgnoreStarFragment(pattern: string, index: number): { source: string; skip: number } {
450
745
  const next = pattern[index + 1];
451
746
  const afterNext = pattern[index + 2];
@@ -461,8 +756,13 @@ function gitIgnoreStarFragment(pattern: string, index: number): { source: string
461
756
  return { source: "[^/]*", skip: 1 };
462
757
  }
463
758
 
464
- // Converts `[abc]`, `[!abc]`, and escaped class characters into regex class syntax. Split into
465
- // header/body helpers because git classes have positional exceptions that are easier to audit separately.
759
+ /**
760
+ * Converts the character class starting at index in pattern to regex source and an extra-character skip count.
761
+ *
762
+ * @param pattern - normalized gitignore glob pattern
763
+ * @param index - index of the opening bracket in pattern
764
+ * @returns regex fragment and skip count, or undefined for an unterminated or empty class so the caller matches `[` literally
765
+ */
466
766
  function gitIgnoreCharacterClassFragment(pattern: string, index: number): { source: string; skip: number } | undefined {
467
767
  const parsed = parseGitIgnoreCharacterClass(pattern, index);
468
768
  if (!parsed) {
@@ -478,8 +778,13 @@ interface GitIgnoreCharacterClass {
478
778
  skip: number;
479
779
  }
480
780
 
481
- // Walks a character class until the first valid closing `]`. The leading `]` exception is handled
482
- // before the loop because git treats `[]a]` as a class containing `]` and `a`.
781
+ /**
782
+ * Parses a character class beginning at index in pattern, including a literal `]` allowed first after optional negation.
783
+ *
784
+ * @param pattern - normalized gitignore glob pattern
785
+ * @param index - index of the opening bracket in pattern
786
+ * @returns regex body, negation flag, and extra-character skip count, or undefined when no valid closing bracket is found
787
+ */
483
788
  function parseGitIgnoreCharacterClass(pattern: string, index: number): GitIgnoreCharacterClass | undefined {
484
789
  const header = gitIgnoreCharacterClassHeader(pattern, index);
485
790
  let cursor = header.cursor;
@@ -496,7 +801,13 @@ function parseGitIgnoreCharacterClass(pattern: string, index: number): GitIgnore
496
801
  return undefined;
497
802
  }
498
803
 
499
- // Reads negation (`!`/`^`) and the special literal `]` when it appears first in the class body.
804
+ /**
805
+ * Parses optional negation (`!` or `^`) and an initial literal `]` after the opening bracket at index in pattern.
806
+ *
807
+ * @param pattern - normalized gitignore glob pattern
808
+ * @param index - index of the opening bracket in pattern
809
+ * @returns next body cursor, initial body text (empty unless `]` was consumed), and negation flag
810
+ */
500
811
  function gitIgnoreCharacterClassHeader(pattern: string, index: number): { cursor: number; body: string; isNegated: boolean } {
501
812
  let cursor = index + 1;
502
813
  const isNegated = pattern[cursor] === "!" || pattern[cursor] === "^";
@@ -509,8 +820,13 @@ function gitIgnoreCharacterClassHeader(pattern: string, index: number): { cursor
509
820
  return { cursor, body: "", isNegated };
510
821
  }
511
822
 
512
- // Returns the regex-ready body fragment for one class character, consuming an escaped literal pair
513
- // when gitignore used a backslash.
823
+ /**
824
+ * Builds the regex-ready body fragment for one class character, consuming an escaped literal pair when gitignore used a backslash.
825
+ *
826
+ * @param pattern - normalized gitignore glob pattern
827
+ * @param cursor - index of the current character inside the character class
828
+ * @returns escaped class character fragment and extra character skip count (1 for a backslash pair, 0 otherwise)
829
+ */
514
830
  function gitIgnoreClassBodyFragment(pattern: string, cursor: number): { source: string; skip: number } {
515
831
  if (pattern[cursor] === "\\" && pattern[cursor + 1]) {
516
832
  return { source: escapeRegexClassCharacter(pattern[cursor + 1] ?? ""), skip: 1 };
@@ -518,14 +834,24 @@ function gitIgnoreClassBodyFragment(pattern: string, cursor: number): { source:
518
834
  return { source: escapeRegexClassCharacter(pattern[cursor] ?? ""), skip: 0 };
519
835
  }
520
836
 
521
- // Escapes only characters with special meaning inside a regex character class. Escaping `-` would
522
- // change valid git ranges like `[a-z]`, so the set is intentionally narrower than normal regex escaping.
837
+ /**
838
+ * Escapes only characters with special meaning inside a regex character class, preserving hyphens so valid git ranges like `[a-z]` stay intact.
839
+ *
840
+ * @param character - single character to place inside a JavaScript RegExp character class
841
+ * @returns escaped character safe for regex character-class interpolation without altering range hyphens
842
+ */
523
843
  function escapeRegexClassCharacter(character: string): string {
524
844
  return character.replace(/[\\\]^]/g, "\\$&");
525
845
  }
526
846
 
527
- // Strips the basePath prefix so a rule from `subdir/.gitignore` is matched against paths relative
528
- // to `subdir`. Returns undefined when `display` is outside the base - those rules cannot apply.
847
+ /**
848
+ * Rebases display relative to basePath for matching rules owned by that directory.
849
+ * An empty basePath means the project root; the base itself yields an empty string and is not matched by the caller.
850
+ *
851
+ * @param basePath - project-relative owning directory of a .gitignore rule, or empty string for the root
852
+ * @param display - candidate project-relative display path
853
+ * @returns path relative to basePath, empty string for the base itself, or undefined when outside the base
854
+ */
529
855
  function pathRelativeToBase(basePath: string, display: string): string | undefined {
530
856
  if (basePath.length === 0) {
531
857
  return display === "." ? "" : display;
@@ -536,15 +862,27 @@ function pathRelativeToBase(basePath: string, display: string): string | undefin
536
862
  return display.startsWith(`${basePath}/`) ? display.slice(basePath.length + 1) : undefined;
537
863
  }
538
864
 
539
- // Guards against `..`-traversal and absolute-path inputs that point outside the requested root.
540
- // Required so a malformed CLI path cannot drag the .gitignore walker into the user's home directory.
865
+ /**
866
+ * Reports whether path is lexically equal to projectRoot or lies below it.
867
+ * The ignore walker uses this check to restrict project .gitignore lookup to paths within the requested root.
868
+ *
869
+ * @param projectRoot - root directory defining the project boundary
870
+ * @param path - filesystem path tested for lexical containment
871
+ * @returns true when path equals projectRoot or is a descendant of it
872
+ */
541
873
  function isInsideProject(projectRoot: string, path: string): boolean {
542
874
  const relativePath = relative(projectRoot, path).replaceAll("\\", "/");
543
875
  return relativePath === "" || (!relativePath.startsWith("../") && relativePath !== ".." && !isAbsolute(relativePath));
544
876
  }
545
877
 
546
- // User config ignore patterns. Simpler than gitignore: literal, `prefix/**`, glob with `*` / `**`,
547
- // or plain prefix. No negation - config ignores are additive on top of gitignore.
878
+ /**
879
+ * Reports whether the candidate path matches a user config ignore pattern; these exclusions are additive and have no negation.
880
+ * Supports literal directory prefixes, star globs, and patterns ending in slash and two stars for a literal prefix and its descendants.
881
+ *
882
+ * @param pattern - user config ignore pattern from config.ignoredPaths
883
+ * @param path - candidate display path to test
884
+ * @returns true when the candidate path matches the config ignore pattern
885
+ */
548
886
  function pathMatches(pattern: string, path: string): boolean {
549
887
  if (pattern === path) {
550
888
  return true;
@@ -561,8 +899,13 @@ function pathMatches(pattern: string, path: string): boolean {
561
899
  return path === prefix || path.startsWith(`${prefix}/`);
562
900
  }
563
901
 
564
- // Same absolute path can be reached through multiple CLI inputs. First-seen wins because that
565
- // preserves the deterministic sort imposed by `discoverSources` and keeps fingerprint stability.
902
+ /**
903
+ * Deduplicates files by absolute path because multiple CLI inputs can reach the same file.
904
+ * Keeps the first entry for each path in files to preserve the deterministic sort imposed by discoverSources.
905
+ *
906
+ * @param files - sorted list of discovered source file records
907
+ * @returns new array containing the first record for each unique absolutePath
908
+ */
566
909
  function uniqueFiles(files: SourceFile[]): SourceFile[] {
567
910
  const seen = new Set<string>();
568
911
  return files.filter((file) => {
@@ -574,7 +917,13 @@ function uniqueFiles(files: SourceFile[]): SourceFile[] {
574
917
  });
575
918
  }
576
919
 
577
- // Anchors a relative CLI argument against the project root; absolute paths pass through unchanged.
920
+ /**
921
+ * Anchors a relative CLI argument against the project root; absolute paths pass through unchanged.
922
+ *
923
+ * @param projectRoot - base directory used to resolve relative paths
924
+ * @param path - CLI path argument, either relative or absolute
925
+ * @returns resolved absolute path
926
+ */
578
927
  export function absolutize(projectRoot: string, path: string): string {
579
928
  return isAbsolute(path) ? path : join(projectRoot, path);
580
929
  }
@@ -583,26 +932,30 @@ export function absolutize(projectRoot: string, path: string): string {
583
932
  * Formats a scanned path for findings, diagnostics, and baselines.
584
933
  * Paths inside the run root stay relative; outside paths are absolute so editor and CI links remain usable.
585
934
  *
586
- * @param projectRoot - working directory that anchors relative report paths
935
+ * @param projectRoot - run root that anchors relative report paths
587
936
  * @param inputPath - scanned path; an empty path addresses the run root itself
588
- * @returns POSIX report path; `.` means the input is the run root
937
+ * @returns POSIX report path; a single dot means the input is the run root
589
938
  */
590
939
  export function displayPath(projectRoot: string, inputPath: string): string {
591
- // Relative CLI inputs are resolved from the run root before report formatting.
592
940
  const absoluteInputPath = isAbsolute(inputPath) ? inputPath : join(projectRoot, inputPath);
593
941
  const projectRelativePath = relative(projectRoot, absoluteInputPath).replaceAll("\\", "/");
594
942
  // The run root itself needs a non-empty label in reports.
595
943
  if (projectRelativePath === "") {
596
944
  return ".";
597
945
  }
598
- // A relative escape cannot serve as an editor or CI link from the run root.
946
+ // Give paths outside the run root an absolute label so report consumers can resolve them without the original run root.
599
947
  if (projectRelativePath === ".." || projectRelativePath.startsWith("../") || isAbsolute(projectRelativePath)) {
600
948
  return absoluteInputPath.replaceAll("\\", "/");
601
949
  }
602
950
  return projectRelativePath;
603
951
  }
604
952
 
605
- // Escapes the standard regex metacharacters so untrusted patterns can be embedded literally.
953
+ /**
954
+ * Escapes the standard regex metacharacters so untrusted patterns can be embedded literally.
955
+ *
956
+ * @param rawText - raw literal text to embed in a regular expression
957
+ * @returns text with regex metacharacters backslash-escaped
958
+ */
606
959
  function escapeRegex(rawText: string): string {
607
960
  return rawText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
608
961
  }