fallow_types/workspace.rs
1//! Workspace and source-discovery diagnostic data types.
2//!
3//! The serializable `WorkspaceDiagnostic` / `WorkspaceDiagnosticKind` pair
4//! lives here, upstream of both `fallow-config` (which owns the registry and
5//! emission logic and re-exports these types for back-compat) and
6//! `fallow-output` (which embeds `Vec<WorkspaceDiagnostic>` in its JSON
7//! envelopes). Keeping the data types in `fallow-types` lets the output layer
8//! reference the real, schema-bearing type instead of an opaque
9//! `serde_json::Value` newtype, so `workspace_diagnostics[]` keeps its typed
10//! `kind`/`path`/`message` shape (and the typed `kind` oneOf) in
11//! `docs/output-schema.json` without coupling output contracts to config
12//! loading.
13
14use std::path::{Path, PathBuf};
15
16use rustc_hash::FxHashSet;
17#[cfg(feature = "schema")]
18use schemars::JsonSchema;
19use serde::{Deserialize, Serialize};
20
21use crate::path_util::display_relative;
22use crate::serde_path;
23
24#[path = "workspace_config_entry.rs"]
25mod config_entry;
26#[path = "workspace_plugin_text.rs"]
27mod plugin_text;
28
29pub use config_entry::{OVERRIDE_REASON_BASE_RULE_OFF, OVERRIDE_REASON_PROJECT_LEVEL};
30
31/// Why the declared pnpm version ignores the `overrides` section of
32/// `pnpm-workspace.yaml`.
33#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
34#[cfg_attr(feature = "schema", derive(JsonSchema))]
35#[serde(rename_all = "kebab-case")]
36pub enum PnpmWorkspaceOverridesIgnoredCause {
37 /// pnpm 10 or earlier, and the root `package.json` declares non-empty
38 /// `pnpm.overrides` or `resolutions`. pnpm uses these entries in place
39 /// of the `pnpm-workspace.yaml` overrides.
40 PackageJsonOverrides,
41 /// pnpm before 10.5.1, which does not read the `overrides` section of
42 /// `pnpm-workspace.yaml`.
43 PnpmVersion,
44}
45
46/// Whether the project had a `node_modules` directory at a point in time.
47///
48/// A dead-code baseline records this when it is saved, so a later run in a
49/// different install state can say that its results can differ.
50#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
51#[cfg_attr(feature = "schema", derive(JsonSchema))]
52#[serde(rename_all = "kebab-case")]
53pub enum NodeModulesState {
54 /// `node_modules` existed, or the project legitimately runs without it.
55 Present,
56 /// `node_modules` did not exist.
57 Missing,
58}
59
60impl NodeModulesState {
61 /// The wire token, as it appears in JSON.
62 #[must_use]
63 pub const fn as_str(self) -> &'static str {
64 match self {
65 Self::Present => "present",
66 Self::Missing => "missing",
67 }
68 }
69}
70
71/// Why a workspace-discovery candidate was rejected, or why a sibling
72/// directory looked workspace-like but was not declared.
73///
74/// Wire-format names are kebab-case so JSON consumers (CI integrations, MCP
75/// agents, LSP clients) get a stable, language-neutral identifier.
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
77#[cfg_attr(feature = "schema", derive(JsonSchema))]
78#[serde(tag = "kind", rename_all = "kebab-case")]
79pub enum WorkspaceDiagnosticKind {
80 /// A directory contains `package.json` but is not declared as a workspace
81 /// in `package.json` `workspaces`, `pnpm-workspace.yaml`, or
82 /// `tsconfig.json` `references`. Surfaced by
83 /// `find_undeclared_workspaces`.
84 UndeclaredWorkspace,
85 /// A declared workspace's `package.json` failed to parse. The directory is
86 /// dropped from discovery, but analysis still proceeds (degraded).
87 MalformedPackageJson {
88 /// `serde_json` parse error text.
89 error: String,
90 },
91 /// A workspace glob pattern matched a directory that contains no
92 /// `package.json`. Honors the extended skip list and `ignorePatterns`
93 /// before emitting.
94 GlobMatchedNoPackageJson {
95 /// The glob pattern that matched the directory.
96 pattern: String,
97 },
98 /// A workspace entry is an absolute path or has `..` segments that lead
99 /// above the project root, so it can name directories outside the root. Fallow skips the entry
100 /// before it reads the disk and analyzes no package from it. `path` is
101 /// the file that declares the entry (`package.json`,
102 /// `pnpm-workspace.yaml`, `deno.json` or `deno.jsonc`), or the project
103 /// root for an entry of the fallow config `workspaces.patterns`. The
104 /// diagnostic never names a directory outside the root.
105 ///
106 /// npm, pnpm and yarn accept such an entry, so fallow does not exit with
107 /// an error on it. The project root is the security boundary of a run.
108 WorkspaceGlobOutsideRoot {
109 /// The workspace entry, as written in the file.
110 pattern: String,
111 },
112 /// A positive workspace pattern names a directory that does not exist.
113 /// The check reads the literal part of the pattern before the first
114 /// segment with a glob character (`vite` for `vite/packages/*`). A pattern
115 /// without a literal part (`**/pkg`) never gets this diagnostic, and a
116 /// literal directory that exists but holds no package does not get it
117 /// either. `path` is the file that declares the pattern, or the project
118 /// root for an entry of the fallow config `workspaces.patterns`.
119 ///
120 /// A repository that clones other repositories into the workspace in CI
121 /// declares such patterns. The packages there can consume catalog
122 /// entries, so the run does not report `unused-catalog-entries` while a
123 /// pattern of this kind exists. For a `packages` entry of the
124 /// `pnpm-workspace.yaml` of a nested pnpm project, the pattern is
125 /// relative to that file, and the run does not report the unused entries
126 /// of that catalog only.
127 WorkspacePatternDirMissing {
128 /// The workspace pattern, as written in the file.
129 pattern: String,
130 },
131 /// A directory has its own `package.json` and `pnpm-workspace.yaml`, and
132 /// no workspace pattern of the root manifests declares it. pnpm installs
133 /// it as an independent project. Fallow analyzes it as a workspace, so its
134 /// `package.json` owns its files and dependencies. The members that the
135 /// `packages` list of its `pnpm-workspace.yaml` declares are workspaces
136 /// too. The `catalog:` references of the project and its members resolve
137 /// against its own catalog, not against the root catalog.
138 ///
139 /// Information only: nothing is lost from the analysis, so
140 /// `degrades_analysis` is false.
141 NestedProjectRoot,
142 /// The root `tsconfig.json`, or a config in its `extends` chain, exists
143 /// but failed to parse. `path` names the file that failed. Fallow ignores
144 /// the project references, path aliases and compiler options of that file.
145 MalformedTsconfig {
146 /// JSONC parse error text.
147 error: String,
148 },
149 /// `tsconfig.json` lists a `references[].path` that does not point to an
150 /// existing directory.
151 TsconfigReferenceDirMissing,
152 /// `pnpm-workspace.yaml` exists but failed to parse as YAML. The catalog
153 /// checks are skipped and dependency-override analysis proceeds without
154 /// the file's entries (degraded) until the syntax is fixed.
155 MalformedPnpmWorkspaceYaml {
156 /// YAML parse error text.
157 error: String,
158 },
159 /// A source file was skipped at discovery because it exceeds the configured
160 /// per-file size limit (`--max-file-size` / `FALLOW_MAX_FILE_SIZE`, default
161 /// 5 MB). The file is never read, parsed, or analyzed, guarding against the
162 /// out-of-memory blowup a single multi-MB generated/vendored/bundled file
163 /// causes (issue #1086). Surfaced by source discovery, not workspace
164 /// discovery, but shares this channel so the skip is visible in
165 /// `workspace_diagnostics[]` on `fallow dead-code / dupes / health` JSON.
166 SkippedLargeFile {
167 /// On-disk size of the skipped file in bytes.
168 size_bytes: u64,
169 },
170 /// A large JavaScript bundle was skipped at discovery because it appears to
171 /// be minified generated output. The file is never parsed or analyzed,
172 /// guarding against sub-limit bundles that can still create very large ASTs
173 /// and extraction payloads (issue #1086). Use `--max-file-size 0` when the
174 /// bundled file really should be analyzed.
175 SkippedMinifiedFile {
176 /// On-disk size of the skipped file in bytes.
177 size_bytes: u64,
178 },
179 /// A dot-prefixed directory was not traversed by source discovery even
180 /// though it contains at least one source file the project has not
181 /// excluded. Hidden directories are skipped by default apart from a small
182 /// convention allowlist (`.storybook`, `.vitepress`, `.well-known`,
183 /// `.changeset`, `.github`) and the directories an active framework plugin
184 /// or a `package.json` script reference contributes, so files inside are
185 /// never parsed and their imports and exports are invisible to every
186 /// analysis. A file, export or dependency that only the directory uses can
187 /// be reported as unused. A `!<dir>/**` entry in `ignorePatterns` adds the
188 /// directory to traversal (issue #2452). Or add the file to `entry`, the
189 /// export to `ignoreExports` or the dependency to `ignoreDependencies` to
190 /// stop that false positive, or add the directory to `ignorePatterns` to
191 /// silence this (issue #461). Running
192 /// fallow with `--root` against the directory analyzes it on its own and
193 /// does not fix the main run (issue #2797).
194 ///
195 /// "Not excluded" is measured the way the run measures it: a directory
196 /// whose contents are gitignored, or excluded by `ignorePatterns`, or (on
197 /// a `--production` run) excluded as test or story files, never earns this
198 /// diagnostic, because the advertised remedies would find nothing there
199 /// either. Generated tool output and non-git VCS metadata are excluded by
200 /// name.
201 ///
202 /// The advisory is best-effort and bounded: one run inspects a fixed
203 /// number of skipped directories with a fixed I/O budget, in sorted path
204 /// order, so a pathological tree yields a deterministic prefix rather than
205 /// an unbounded array or an unbounded scan. The stderr note says "at
206 /// least" when a ceiling bound the run.
207 ///
208 /// Surfaced by source discovery, not workspace discovery, but shares this
209 /// channel so the skip is visible in `workspace_diagnostics[]` on
210 /// `fallow dead-code / dupes / health` JSON.
211 ///
212 /// Unlike the two skipped-file kinds beside it, this one is CAPPED. To
213 /// bound the directory reads the check costs, a run classifies at most 64
214 /// candidate directories and spends at most 1024 directory entries across
215 /// all of them, so on a project that exceeds either ceiling the array is a
216 /// prefix of the skipped directories rather than all of them, and the
217 /// stderr note says "at least N". No measured repository comes close to
218 /// either ceiling. A consumer needing an exact total should run fallow
219 /// with `--root` against the tree rather than infer one from this array.
220 SkippedSourceDotdir,
221 /// A source discovered with a stable [`FileId`](crate::discover::FileId)
222 /// could not be read before parsing. Analysis continues with the remaining
223 /// sparse module IDs and reports the underlying filesystem or UTF-8 error.
224 SourceReadFailure {
225 /// Filesystem or UTF-8 decoding error from `read_to_string`.
226 error: String,
227 },
228 /// A source file was read but parsed with diagnostics, so the module
229 /// extracted from it may be missing imports, exports, or references after
230 /// the first error. Analysis proceeds with the partial module, which is why
231 /// this is reported: an import the parser never saw credits nothing, and its
232 /// target can surface as a confident `unused-file` or `unused-export`
233 /// finding with a `delete-file` or `remove-export` action on it.
234 ///
235 /// Recorded by the parse stage, alongside `source-read-failure`, and never
236 /// used to withhold a finding. oxc reports recoverable errors for valid
237 /// syntax newer than the parser as well as for genuinely broken files, so
238 /// gating findings on this would mute real results project-wide instead of
239 /// just the affected file.
240 ///
241 /// A file that `ignoreFindings` covers is not reported. The user marked it
242 /// as broken on purpose, so its partial parse also adds no caveat to other
243 /// findings and does not count for the parse-error gate.
244 SourceParseDegraded {
245 /// Number of parser diagnostics reported for the file.
246 error_count: u32,
247 /// `true` when the parser abandoned the file instead of recovering, so
248 /// the extracted module is a fragment at best.
249 panicked: bool,
250 },
251 /// A source file nests brackets deeper than the parser cap, or needs more
252 /// stack than fallow reserves, so it was not parsed at all. The file can be
253 /// valid code, so this is not reported as a syntax error, but it degrades
254 /// the run in the same way: its imports credit nothing. It counts for the
255 /// parse-error gate and adds the same caveats as `source-parse-degraded`.
256 SourceNestingTooDeep {
257 /// The bracket nesting cap of the pre-parse scan.
258 limit: u32,
259 },
260 /// Dependency-override resolution was skipped because bun's legacy binary
261 /// `bun.lockb` sits next to this `package.json`, fallow cannot read the
262 /// binary format, and no parseable text lockfile was found to use
263 /// instead: no `bun.lock` that parses, and no readable `pnpm-lock.yaml`,
264 /// `package-lock.json`, or `npm-shrinkwrap.json`. A `yarn.lock` is never
265 /// consulted (yarn ignores `overrides`), so it does not prevent the skip
266 /// either. The manifest declares overrides, so the
267 /// `unused-dependency-overrides` check would otherwise have run; without
268 /// resolution ground truth it would flag every transitive-only pin, so no
269 /// unused-override findings are reported at all (issue #2358). Surfaced
270 /// by the override analysis, not workspace discovery, but shares this
271 /// channel so the skip is visible in `workspace_diagnostics[]` JSON and
272 /// as a stderr warning.
273 BunLockbOverrideResolutionSkipped,
274 /// Dependency-override resolution was skipped because bun's text
275 /// `bun.lock` exists but could not be parsed and no readable pnpm or npm
276 /// lockfile was available as independent resolution ground truth.
277 BunLockOverrideResolutionSkipped,
278 /// Dependency-override resolution was skipped because `pnpm-lock.yaml`
279 /// exists but could not be parsed, for example because it still holds
280 /// unresolved merge-conflict markers, and no other parseable lockfile was
281 /// available as independent resolution ground truth.
282 PnpmLockOverrideResolutionSkipped,
283 /// Dependency-override resolution was skipped because `package-lock.json`
284 /// or `npm-shrinkwrap.json` exists but could not be parsed, for example
285 /// because it still holds unresolved merge-conflict markers, and no other
286 /// parseable lockfile was available as independent resolution ground
287 /// truth.
288 NpmLockOverrideResolutionSkipped,
289 /// A bun manifest declares both `overrides` and a non-empty `resolutions`
290 /// object. Bun applies `overrides` and ignores `resolutions`, so fallow
291 /// reports the shadowed configuration without offering removal advice.
292 BunResolutionsShadowedByOverrides,
293 /// The declared pnpm version ignores the `overrides` section of
294 /// `pnpm-workspace.yaml`. pnpm does not print a warning. Fallow reports
295 /// no findings for the ignored entries. `cause` tells why pnpm ignores
296 /// the section.
297 PnpmWorkspaceOverridesIgnored {
298 /// Why pnpm ignores the section. The cause decides the remedy.
299 cause: PnpmWorkspaceOverridesIgnoredCause,
300 },
301 /// The project has no `node_modules` directory and is not a Deno project
302 /// that legitimately runs without one. Analysis proceeds, but three things
303 /// degrade silently: package `exports` and conditional exports cannot be
304 /// read, so imports into a dependency's subpaths resolve less precisely;
305 /// framework plugins that activate on an installed package stay inactive,
306 /// so their entry points and path aliases are missing; and a dependency's
307 /// installed shape cannot be inspected, so type-only dependency
308 /// classification falls back to declaration-based heuristics.
309 ///
310 /// Recorded once per run by the source walk, anchored at the missing
311 /// `node_modules` directory so the reported path is a real location rather
312 /// than the empty string a root-anchored diagnostic would render. This used
313 /// to be a bare `tracing::warn!` duplicated in two pipelines, so it never
314 /// reached JSON output and never reached `fallow doctor`, which reported
315 /// `pass` on a tree that had never been installed.
316 NodeModulesMissing,
317 /// `boundaries` is empty while `boundary-violation` is not `off`, so the
318 /// boundary detector never ran. Its summary counters are therefore
319 /// structurally zero and say nothing about the project.
320 ///
321 /// This is the UNCONFIGURED zero, not the user-chosen one: a project that
322 /// sets `boundary-violation: off` asked for silence and can see that
323 /// choice in `fallow config`. A project that left `boundaries` empty
324 /// cannot distinguish "no violations" from "nothing was measured".
325 BoundariesNotConfigured,
326 /// `rulePacks` is empty while `policy-violation` is not `off`, so the
327 /// policy detector never ran and its summary counters are structurally
328 /// zero. The unconfigured counterpart of
329 /// [`Self::BoundariesNotConfigured`].
330 RulePacksNotConfigured,
331 /// `client-server-leak` is not `off`, but no analyzed file has a
332 /// top-level `"use client"` directive. The detector starts only from those
333 /// files, so it had no starting point and its zero count measures
334 /// nothing. React Router Framework Mode and a plain Vite SPA are typical
335 /// projects of this shape: their client code carries no directive.
336 ///
337 /// Like [`Self::BoundariesNotConfigured`], an analyze pass with the rule
338 /// `off` does not report it. `fallow security` raises a top-level `off`
339 /// to `warn` before the pass, so that command always reports it.
340 ClientServerLeakNoClientRoots,
341 /// One of fallow's built-in discovery ignore patterns (`**/dist/**`,
342 /// `**/build/**`, `**/coverage/**`, and the four minified-bundle globs)
343 /// removed at least one candidate source file from this walk. The files
344 /// are never read, so their imports and exports are invisible to every
345 /// analysis, and until issue #2638 the drop was completely silent:
346 /// pointing fallow at a directory a built-in pattern matches returned a
347 /// clean report with exit 0 and nothing said why.
348 ///
349 /// `**/node_modules/**` is carved out and never appears in `pattern`:
350 /// installed dependencies are not the first-party source this diagnostic
351 /// is about, and a project that does not gitignore them would get a
352 /// five-figure count with no useful remedy. `**/.git/**` cannot fire,
353 /// because hidden directories are not traversed.
354 ///
355 /// One entry per pattern, never per file or per directory, so the array
356 /// grows by at most the number of built-in patterns on a project of any
357 /// size. `path` anchors at the matched directory holding the most excluded
358 /// files for that pattern, ties broken by the lexicographically first
359 /// path, so two runs on one tree report the same location. On a nested
360 /// match it is the DEEPEST segment the pattern matched
361 /// (`build/tools/build`, not `build`), because that is the directory the
362 /// `--root` remedy names and re-rooting at a shallower one would leave a
363 /// matching segment behind. That directory is the
364 /// largest group and not a majority: a flat monorepo can spread ten
365 /// excluded files over ten sibling `dist/` directories and every one of
366 /// them is then "the largest". `file_count` spans all of them, and
367 /// `directory_count` says how many there were, so a reader can tell a
368 /// single tree from a scattered one without a directory list in the
369 /// payload.
370 ///
371 /// Three properties of the population are load-bearing and easy to
372 /// misread:
373 ///
374 /// - **Gitignored trees count zero.** Source discovery honors
375 /// `.gitignore`, `.git/info/exclude`, and the global gitignore, and
376 /// prunes those directories before this check runs. The honest reading
377 /// is "candidate source files git did not already hide and a built-in
378 /// pattern then dropped", which is why a repository that gitignores its
379 /// own `dist/` never sees this diagnostic.
380 /// - **A user `ignorePatterns` entry is not a surprise.** The compiled
381 /// ignore set is the union of `ignorePatterns` and the built-ins, so a
382 /// file both matched was an explicit project choice and is attributed to
383 /// no pattern here. A `!` entry in `ignorePatterns` lifts a built-in for
384 /// the paths it matches (issue #2940), and a lifted file is discovered,
385 /// so it is never counted here.
386 /// - **The remedy depends on the pattern's shape.** A directory-shaped
387 /// built-in (`**/dist/**`) is matched against the path relative to the
388 /// run root, so re-rooting inside the matched directory removes the
389 /// matched segment and the files become visible: the message advertises
390 /// `fallow --root <dir>`. A file-shaped built-in (`**/*.min.js` and the
391 /// three other bundle globs) matches on the file name and keeps matching
392 /// at any root, so the message says so and points at renaming instead of
393 /// handing out a command that provably does nothing.
394 ///
395 /// Deliberately NOT one of the [`Self::source_never_analyzed`] kinds. These
396 /// exclusions are the product's designed behavior on generated output, not
397 /// a degraded run: answering `true` would attach `IncompleteFileAnalysis`
398 /// and `IncompleteImportGraph` caveats to findings on nearly every project
399 /// that keeps a non-gitignored `dist/` or `coverage/`, and make `fallow
400 /// fix` withhold `delete-file` and `remove-export` actions project-wide.
401 ExcludedByDefaultIgnore {
402 /// The built-in glob that matched, verbatim (for example
403 /// `**/build/**`).
404 pattern: String,
405 /// Candidate source files this pattern excluded in this walk, across
406 /// every directory it matched, not just the one `path` anchors at.
407 /// Exact: the walk counts each excluded candidate once.
408 file_count: u32,
409 /// Distinct directories this pattern matched at, `path` included, and
410 /// not the number of directories that held the files. A
411 /// directory-shaped pattern (`**/dist/**`) matches at the directory it
412 /// names, so an excluded subtree counts once however many nested
413 /// directories inside it held source: a `dist/` holding files in three
414 /// sub-directories reports `1`. A file-shaped pattern (`**/*.min.js`)
415 /// has no directory to collapse to and counts each matched file's own
416 /// parent. Exact either way, and anything above `1` says `path` names
417 /// one matched location out of several.
418 directory_count: u32,
419 },
420 /// The walk finished with no source file to analyze at all, so every
421 /// finding count this run reports is zero because nothing was measured
422 /// rather than because the project is clean (issue #2686).
423 ///
424 /// Distinct from [`Self::ExcludedByDefaultIgnore`], which reports one
425 /// pattern's exclusions and is designed behavior on generated output. The
426 /// alarm is not the exclusion, it is having nothing left afterwards, and
427 /// that condition also fires with no exclusion at all: a docs-only
428 /// repository, a workspace member with no TypeScript, or a path filter that
429 /// matched nothing. `excluded_file_count` names the built-in-ignore
430 /// contribution so the common cause is still attributable, and is `0` when
431 /// no built-in pattern took part.
432 ///
433 /// This is the kind a CI consumer reads to tell "measured zero" from
434 /// "measured nothing": the human report has said so since 3.26.0, but only
435 /// in human format and only under the built-in-ignore cause, so `--quiet
436 /// --format json` saw a clean green either way.
437 NoSourceFilesAnalyzed {
438 /// Candidate source files the built-in ignore patterns removed from
439 /// this walk, summed across every pattern. `0` when the walk found no
440 /// candidate to exclude in the first place.
441 excluded_file_count: u32,
442 },
443 /// Per-file health scoring failed, so the score list is empty and the
444 /// scored-file count is `0` because nothing was measured rather than
445 /// because the project has no files worth scoring. Every score-derived
446 /// number (the average maintainability index, the refactoring targets, the
447 /// hotspot complexity half) is then structurally zero (issue #2689).
448 FileScoresUnavailable {
449 /// Scoring error text.
450 error: String,
451 },
452 /// Churn-based hotspot analysis was skipped, so the hotspots, churn and
453 /// ownership sections report nothing at all. The remaining health sections
454 /// are unaffected.
455 HotspotsSkipped {
456 /// Which input stopped it, as a kebab-case token: `not-a-repository`,
457 /// `no-commits`, `invalid-since` or `churn-file-unreadable`. The set is
458 /// open.
459 ///
460 /// The cause decides the remedy, which is why it is on the wire: a run
461 /// outside a repository is fixed by running fallow inside one, a
462 /// branch without a commit by committing, a malformed `--since` by
463 /// respelling the flag, and a churn file that changed under the run by
464 /// rerunning it. A consumer reading only the kind would offer the first
465 /// remedy for all four.
466 cause: String,
467 },
468 /// Change coupling found no pairs because the history cannot show them.
469 /// The `change_coupling` section is present with an empty `pairs` list,
470 /// and this entry tells why the list is empty.
471 ChangeCouplingSkipped {
472 /// Kebab-case token: `shallow-clone` (the fetched history is
473 /// incomplete) or `too-few-commits` (fewer analyzed commits than the
474 /// minimum revisions of one file). The set is open.
475 cause: String,
476 },
477 /// The repository is a shallow clone, so churn is measured over the fetched
478 /// history only and every hotspot figure is incomplete.
479 ShallowClone {
480 /// `true` when the run also asked for ownership attribution, which a
481 /// shallow clone skews further by inflating single-author dominance.
482 ownership_requested: bool,
483 },
484 /// No commit timestamp was available, so churn recency and ownership
485 /// staleness were measured against the wall clock and drift between two
486 /// runs over the same commit.
487 UnpinnedClock,
488 /// Ownership attribution was requested but its inputs did not load, so
489 /// hotspot entries carry degraded or absent owner signals.
490 OwnershipUnavailable {
491 /// Which input failed, as a kebab-case token: `invalid-bot-pattern` or
492 /// `codeowners-parse-failed`. The set is open.
493 cause: String,
494 /// Underlying error text.
495 error: String,
496 },
497 /// A saved health snapshot could not be read or parsed, so the trend is
498 /// computed over fewer snapshots than the project has on disk and a
499 /// direction can flip on the missing point alone.
500 TrendSnapshotUnreadable {
501 /// Filesystem or JSON error text.
502 error: String,
503 },
504 /// A grouped health run asked for a trend, but the baseline snapshot holds
505 /// no group data that matches this run, so the groups carry no trend. The
506 /// project trend is not affected. `path` names the baseline snapshot.
507 TrendGroupBaselineUnavailable {
508 /// Why the groups have no baseline, as a kebab-case token:
509 /// `snapshot-has-no-groups` or `grouped-by-mismatch`. The set is open.
510 cause: String,
511 },
512 /// A framework plugin read a build config and could not read one of its
513 /// keys in full, so part of what the key declares never reached the
514 /// analysis. `path` names the config file.
515 ///
516 /// The reader is syntactic, so a key whose value is computed at build time
517 /// is invisible to it: a Module Federation `exposes: makeExposes()` or a
518 /// `remotes` map spread from an environment module declares entries this
519 /// run does not know about. The consequence is a finding, not a missing
520 /// number: an unread `exposes` target is not registered as an entry point
521 /// and its file can surface as `unused-file`, and an unread `remotes` alias
522 /// is not treated as provided by a remote container and its import can
523 /// surface as an unlisted dependency.
524 ///
525 /// Recorded by the plugin stage, which runs before analysis and is not
526 /// cached, so the entry is present on a warm cache too. A bare
527 /// `tracing::warn!` from inside the plugin reaches no envelope and no CI
528 /// consumer (issue #2736).
529 ///
530 /// A source file that calls the Module Federation runtime API gets the same
531 /// entry: `path` names the source file, `key` names the runtime function
532 /// (`registerRemotes`, `loadRemote`, `init`, `createInstance`) and
533 /// `reason` is `dynamic-argument` when the call receives a value that is
534 /// not a static literal. The analysis records it from the facts of the
535 /// parse, which a warm cache restores (issue #2795). A `.vue` or `.svelte`
536 /// file gets it for a call in its `<script>` blocks (issue #2876).
537 PluginConfigUnreadable {
538 /// The plugin that read the config, as it labels itself:
539 /// `module-federation` for a standalone `module-federation.config.*`,
540 /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`) that
541 /// read the same options inline from its own config.
542 plugin: String,
543 /// The config key that was present and not fully readable (`exposes`,
544 /// `remotes`), or the Module Federation runtime function whose
545 /// argument was not readable (`registerRemotes`, `loadRemote`, `init`,
546 /// `createInstance`). The set is open.
547 key: String,
548 /// Why it could not be read, as a kebab-case token:
549 /// `not-object-literal`, `array-form`, `spread`,
550 /// `unreadable-entries`, `unrecognized-call`,
551 /// `import-target-unreadable` or `dynamic-argument`. The set is open.
552 ///
553 /// The reason decides the remedy, which is why it is on the wire: a
554 /// value that is not an object literal is fixed by writing one, while
555 /// unreadable entries are fixed by naming those entries in the config
556 /// option the message points at.
557 reason: String,
558 },
559 /// A framework plugin read a config key it understands, does not model
560 /// that key's effect, and therefore stood a modeled default down. `path`
561 /// names the config file.
562 ///
563 /// A file can also be the `path`: a Nuxt file that reads `#components` or
564 /// `#imports` in a way fallow cannot narrow to names, such as a spread of
565 /// a namespace import, has `key` set to that module and `reason` set to
566 /// `key-effect-not-modeled`. Every name of the module then counts as used.
567 ///
568 /// The Nuxt auto-import gate is the case this exists for. With
569 /// `autoImports` enabled fallow drops the Nuxt convention entry patterns
570 /// so a genuinely unreferenced convention file is reported, and a
571 /// `components:` or `imports:` block whose effect it cannot model keeps
572 /// them, which silently costs the user the findings they opted in for.
573 ///
574 /// Deliberately NOT one of the [`Self::warns_on_stderr`] kinds. Nothing
575 /// was lost that the run could have measured: the patterns stayed, so
576 /// findings are suppressed rather than invented, and a project in this
577 /// state would otherwise warn on every run forever with "write different
578 /// config" as the only remedy, which is the reason
579 /// `boundaries-not-configured` is off stderr as well.
580 PluginEffectNotModeled {
581 /// The plugin that read the config, as it labels itself (`nuxt`).
582 plugin: String,
583 /// The config key whose effect is not modeled (`components`,
584 /// `imports`), or the virtual module a file reads (`#components`,
585 /// `#imports`). The set is open.
586 key: String,
587 /// Why the effect is not modeled, as a kebab-case token:
588 /// `key-effect-not-modeled` when the key's own value is the reason,
589 /// `config-property-unreadable` when a top-level property of the same
590 /// config file could not be read statically, so no surface in it can
591 /// be classified at all. The set is open.
592 reason: String,
593 },
594 /// Test coverage was auto-detected on disk rather than passed with
595 /// `--coverage`, and `path` names the file that fed the CRAP scores.
596 ///
597 /// Deliberately NOT one of the [`Self::warns_on_stderr`] kinds: nothing
598 /// degraded, the run measured exactly what it found. It is provenance, and
599 /// it is on the wire because a score computed against a file the user did
600 /// not name is not reproducible and nothing else says which file it was.
601 CoverageAutoDetected,
602 /// `fallow flags --retirement` asked for flag age, but the repository is
603 /// a shallow clone. Blame and pickaxe see the fetched history only, so
604 /// every age would be too young. The report gives no age.
605 FlagAgeShallowClone,
606 /// `fallow flags --retirement` asked for flag age, but git history is
607 /// not available. The report gives no age.
608 FlagAgeUnavailable {
609 /// Why no history is available, as a kebab-case token:
610 /// `not-a-repository` or `no-commits`. The set is open.
611 cause: String,
612 },
613 /// A glob in `ignoreDependencies` matched no dependency that a
614 /// `package.json` of the project declares, so the entry had no effect in
615 /// this run. The usual cause is a typo in the scope or the name.
616 ///
617 /// The dead-code run records it only when the unused-dependency check ran
618 /// and the run reports dependency findings. A run filtered to other issue
619 /// types (`--unused-files`) or scoped to files (`--file`) does not record
620 /// it. An exact-name entry never produces it. `path` is the project root.
621 ///
622 /// Not a degraded run: the analysis measured what it was asked to, so
623 /// `degrades_analysis` is false and no finding carries a caveat.
624 IgnoreDependenciesGlobUnmatched {
625 /// The `ignoreDependencies` entry, as written in the config.
626 pattern: String,
627 },
628 /// A pattern in `ignoreFindings` matched no finding of the dead-code run,
629 /// so the entry had no effect in this run. The usual cause is a typo in
630 /// the path.
631 ///
632 /// The pattern is compared with every finding the analysis produced,
633 /// before issue-type filters and scope filters, so a filtered run does not
634 /// make a pattern look unused. `path` is the project root.
635 ///
636 /// Not a degraded run, for the same reason as
637 /// [`Self::IgnoreDependenciesGlobUnmatched`].
638 IgnoreFindingsPatternUnmatched {
639 /// The `ignoreFindings` entry, as written in the config.
640 pattern: String,
641 },
642 /// An `entry` pattern matched only files that another source (a
643 /// `package.json` field or script, a plugin, `dynamicallyLoaded`) makes
644 /// runtime entry points (issue #3824). Not for a pattern that matches no
645 /// file, nor a `--production` run. `path` is the root. Not degraded.
646 EntryPatternRedundant {
647 /// The `entry` pattern, as written in the config.
648 pattern: String,
649 },
650 /// An `ignoreDependencies` entry hid no dependency finding (issue #3824).
651 /// A glob that matches no declared dependency is
652 /// [`Self::IgnoreDependenciesGlobUnmatched`] instead. Same conditions as
653 /// that kind, and not a `--production` run. `path` is the root.
654 IgnoreDependenciesEntryRedundant {
655 /// The `ignoreDependencies` entry, as written in the config.
656 pattern: String,
657 },
658 /// An `ignorePatterns` glob excluded no file that the run would otherwise
659 /// analyze (issue #3824). Never a `!` exception, a glob that names a
660 /// hidden directory, or a `--production` run. A glob for build output has
661 /// an effect only after a build. `path` is the root. Not degraded.
662 IgnorePatternsEntryRedundant {
663 /// The `ignorePatterns` glob, as written in the config.
664 pattern: String,
665 },
666 /// An `overrides` rule cannot change the result (issue #4065). `reason` is
667 /// `project-level` (fallow reads only the top-level severity of the rule)
668 /// or `base-rule-off` (the top-level rule is off after CLI flags, so its
669 /// detector does not run). The token set is open. `path` is the root. Not
670 /// degraded, and no finding or exit code changes.
671 OverrideRuleIneffective {
672 /// The canonical rule name, also when the config uses an alias.
673 rule: String,
674 /// The `overrides[].files` globs, as written in the config.
675 files: Vec<String>,
676 /// Why the rule has no effect, as a kebab-case token.
677 reason: String,
678 },
679 /// An explicit issue-type selection asked for a rule that the config sets
680 /// to `off`, so that check did not run (issue #4067). One entry per rule.
681 /// The opt-in flags that turn their rule on and a run with no selection
682 /// never report it. `path` is the root. Not degraded: the run measured
683 /// what the config asked for, and no finding or exit code changes.
684 RequestedRuleOff {
685 /// The canonical rule name in `rules`.
686 rule: String,
687 /// The canonical CLI selector of the request, such as `--unused-deps`.
688 /// A typed API or MCP request reports the same selector.
689 flag: String,
690 },
691 /// The dead-code baseline was saved in a different install state than
692 /// this run: one of the two runs had `node_modules` and the other did not.
693 /// Findings that need installed packages (dependency, unlisted,
694 /// unresolved-import and script-binary findings) can differ, so the run
695 /// can report baseline findings as new. `path` is the baseline file.
696 ///
697 /// Only a baseline that records its install state can report this. A
698 /// legacy baseline has no record, so the state is unknown.
699 BaselineInstallStateMismatch {
700 /// The install state when the baseline was saved.
701 baseline_node_modules: NodeModulesState,
702 /// The install state of this run.
703 run_node_modules: NodeModulesState,
704 },
705}
706
707impl WorkspaceDiagnosticKind {
708 /// Stable kebab-case identifier used in dedupe keys and tracing payloads.
709 #[must_use]
710 pub const fn id(&self) -> &'static str {
711 match self {
712 Self::UndeclaredWorkspace => "undeclared-workspace",
713 Self::MalformedPackageJson { .. } => "malformed-package-json",
714 Self::GlobMatchedNoPackageJson { .. } => "glob-matched-no-package-json",
715 Self::WorkspaceGlobOutsideRoot { .. } => "workspace-glob-outside-root",
716 Self::WorkspacePatternDirMissing { .. } => "workspace-pattern-dir-missing",
717 Self::NestedProjectRoot => "nested-project-root",
718 Self::MalformedTsconfig { .. } => "malformed-tsconfig",
719 Self::TsconfigReferenceDirMissing => "tsconfig-reference-dir-missing",
720 Self::MalformedPnpmWorkspaceYaml { .. } => "malformed-pnpm-workspace-yaml",
721 Self::SkippedLargeFile { .. } => "skipped-large-file",
722 Self::SkippedMinifiedFile { .. } => "skipped-minified-file",
723 Self::SkippedSourceDotdir => "skipped-source-dotdir",
724 Self::SourceReadFailure { .. } => "source-read-failure",
725 Self::SourceParseDegraded { .. } => "source-parse-degraded",
726 Self::SourceNestingTooDeep { .. } => "source-nesting-too-deep",
727 Self::BunLockbOverrideResolutionSkipped => "bun-lockb-override-resolution-skipped",
728 Self::BunLockOverrideResolutionSkipped => "bun-lock-override-resolution-skipped",
729 Self::PnpmLockOverrideResolutionSkipped => "pnpm-lock-override-resolution-skipped",
730 Self::NpmLockOverrideResolutionSkipped => "npm-lock-override-resolution-skipped",
731 Self::BunResolutionsShadowedByOverrides => "bun-resolutions-shadowed-by-overrides",
732 Self::PnpmWorkspaceOverridesIgnored { .. } => "pnpm-workspace-overrides-ignored",
733 Self::NodeModulesMissing => "node-modules-missing",
734 Self::BoundariesNotConfigured => "boundaries-not-configured",
735 Self::RulePacksNotConfigured => "rule-packs-not-configured",
736 Self::ClientServerLeakNoClientRoots => "client-server-leak-no-client-roots",
737 Self::ExcludedByDefaultIgnore { .. } => "excluded-by-default-ignore",
738 Self::NoSourceFilesAnalyzed { .. } => "no-source-files-analyzed",
739 Self::FileScoresUnavailable { .. } => "file-scores-unavailable",
740 Self::HotspotsSkipped { .. } => "hotspots-skipped",
741 Self::ChangeCouplingSkipped { .. } => "change-coupling-skipped",
742 Self::ShallowClone { .. } => "shallow-clone",
743 Self::UnpinnedClock => "unpinned-clock",
744 Self::OwnershipUnavailable { .. } => "ownership-unavailable",
745 Self::TrendSnapshotUnreadable { .. } => "trend-snapshot-unreadable",
746 Self::TrendGroupBaselineUnavailable { .. } => "trend-group-baseline-unavailable",
747 Self::PluginConfigUnreadable { .. } => "plugin-config-unreadable",
748 Self::PluginEffectNotModeled { .. } => "plugin-effect-not-modeled",
749 Self::CoverageAutoDetected => "coverage-auto-detected",
750 Self::FlagAgeShallowClone => "flag-age-shallow-clone",
751 Self::FlagAgeUnavailable { .. } => "flag-age-unavailable",
752 Self::IgnoreDependenciesGlobUnmatched { .. } => "ignore-dependencies-glob-unmatched",
753 Self::IgnoreFindingsPatternUnmatched { .. } => "ignore-findings-pattern-unmatched",
754 Self::EntryPatternRedundant { .. } => "entry-pattern-redundant",
755 Self::IgnoreDependenciesEntryRedundant { .. } => "ignore-dependencies-entry-redundant",
756 Self::IgnorePatternsEntryRedundant { .. } => "ignore-patterns-entry-redundant",
757 Self::OverrideRuleIneffective { .. } => "override-rule-ineffective",
758 Self::RequestedRuleOff { .. } => "requested-rule-off",
759 Self::BaselineInstallStateMismatch { .. } => "baseline-install-state-mismatch",
760 }
761 }
762
763 /// Whether this diagnostic is worth a `tracing::warn!` line on stderr, on
764 /// top of its permanent entry in `workspace_diagnostics[]`.
765 ///
766 /// A warning is for a run whose RESULTS are degraded: something the user
767 /// installed, wrote, or expected did not reach the analysis. The two
768 /// unconfigured-check kinds are not that. They fire in the product's
769 /// default state, on every project that never opted into boundaries or
770 /// rule packs, and they will keep firing forever, because the remedy they
771 /// offer is to write configuration in order to silence a warning about not
772 /// having written configuration. They stay in the structured array, where a
773 /// consumer that wants to distinguish "measured zero" from "measured
774 /// nothing" can read them, and off the stderr surface that every other
775 /// command shares.
776 ///
777 /// `coverage-auto-detected` answers false for a third reason: it reports
778 /// the provenance of an input that DID load, so a consumer sentence about a
779 /// degraded run would state something untrue about it. Its own note is
780 /// printed by the health pipeline.
781 ///
782 /// `plugin-effect-not-modeled` answers false for the first reason: the
783 /// config was readable and nothing the run could have measured was lost,
784 /// so it would warn forever on a project whose `nuxt.config` fallow does
785 /// not model. Its sibling `plugin-config-unreadable` answers true, because
786 /// there a declaration the user wrote did not reach the analysis and
787 /// findings can be wrong in either direction.
788 #[must_use]
789 pub const fn warns_on_stderr(&self) -> bool {
790 match self {
791 Self::BoundariesNotConfigured
792 | Self::RulePacksNotConfigured
793 | Self::ClientServerLeakNoClientRoots
794 | Self::ExcludedByDefaultIgnore { .. }
795 | Self::PluginEffectNotModeled { .. }
796 | Self::CoverageAutoDetected
797 | Self::TrendGroupBaselineUnavailable { .. }
798 | Self::ChangeCouplingSkipped { .. }
799 | Self::IgnoreDependenciesGlobUnmatched { .. }
800 | Self::IgnoreFindingsPatternUnmatched { .. }
801 | Self::EntryPatternRedundant { .. }
802 | Self::IgnoreDependenciesEntryRedundant { .. }
803 | Self::IgnorePatternsEntryRedundant { .. }
804 | Self::OverrideRuleIneffective { .. }
805 | Self::RequestedRuleOff { .. }
806 | Self::NestedProjectRoot => false,
807 Self::UndeclaredWorkspace
808 | Self::MalformedPackageJson { .. }
809 | Self::GlobMatchedNoPackageJson { .. }
810 | Self::WorkspaceGlobOutsideRoot { .. }
811 | Self::WorkspacePatternDirMissing { .. }
812 | Self::MalformedTsconfig { .. }
813 | Self::TsconfigReferenceDirMissing
814 | Self::MalformedPnpmWorkspaceYaml { .. }
815 | Self::SkippedLargeFile { .. }
816 | Self::SkippedMinifiedFile { .. }
817 | Self::SkippedSourceDotdir
818 | Self::SourceReadFailure { .. }
819 | Self::SourceParseDegraded { .. }
820 | Self::SourceNestingTooDeep { .. }
821 | Self::BunLockbOverrideResolutionSkipped
822 | Self::BunLockOverrideResolutionSkipped
823 | Self::PnpmLockOverrideResolutionSkipped
824 | Self::NpmLockOverrideResolutionSkipped
825 | Self::BunResolutionsShadowedByOverrides
826 | Self::PnpmWorkspaceOverridesIgnored { .. }
827 | Self::NodeModulesMissing
828 | Self::NoSourceFilesAnalyzed { .. }
829 | Self::FileScoresUnavailable { .. }
830 | Self::HotspotsSkipped { .. }
831 | Self::ShallowClone { .. }
832 | Self::UnpinnedClock
833 | Self::OwnershipUnavailable { .. }
834 | Self::TrendSnapshotUnreadable { .. }
835 | Self::PluginConfigUnreadable { .. }
836 | Self::FlagAgeShallowClone
837 | Self::FlagAgeUnavailable { .. }
838 | Self::BaselineInstallStateMismatch { .. } => true,
839 }
840 }
841
842 /// Whether this diagnostic is produced by SOURCE discovery (the file walk in
843 /// `discover_files`) rather than WORKSPACE discovery (config load). Source-
844 /// discovery diagnostics are APPENDED to the registry after config load, so
845 /// `stash_workspace_diagnostics` must preserve them when it replaces the
846 /// workspace-discovery set, otherwise the per-analysis config re-loads in
847 /// combined-mode (`fallow` with no subcommand re-loads config for check,
848 /// dupes, and health) wipe them before the JSON envelope is built (issue
849 /// #1086).
850 #[must_use]
851 pub const fn is_source_discovery(&self) -> bool {
852 matches!(
853 self,
854 Self::SkippedLargeFile { .. }
855 | Self::SkippedMinifiedFile { .. }
856 | Self::SkippedSourceDotdir
857 | Self::SourceReadFailure { .. }
858 | Self::SourceParseDegraded { .. }
859 | Self::SourceNestingTooDeep { .. }
860 | Self::NodeModulesMissing
861 | Self::ExcludedByDefaultIgnore { .. }
862 | Self::NoSourceFilesAnalyzed { .. }
863 )
864 }
865
866 /// Whether this diagnostic is written by the source file WALK
867 /// (`discover_files`), the subset of [`Self::is_source_discovery`] that a
868 /// walk replaces wholesale for its root. `source-read-failure` is the
869 /// other source-discovery kind and is NOT one of these: the parse stage
870 /// records it after the walk, so it has to keep reaching consumers through
871 /// the registry.
872 ///
873 /// A walk-recorded entry must reach an analysis from its OWN walk's return
874 /// value. Combined mode runs the dead-code and duplication walks under
875 /// `rayon::join` whenever a per-analysis `production` split stops them from
876 /// sharing a file list, so a registry read answers "whichever walk wrote
877 /// last" and varies between runs of the same command (issue #2366).
878 #[must_use]
879 pub const fn is_source_walk_recorded(&self) -> bool {
880 matches!(
881 self,
882 Self::SkippedLargeFile { .. }
883 | Self::SkippedMinifiedFile { .. }
884 | Self::SkippedSourceDotdir
885 | Self::NodeModulesMissing
886 | Self::ExcludedByDefaultIgnore { .. }
887 | Self::NoSourceFilesAnalyzed { .. }
888 )
889 }
890
891 /// Whether this diagnostic reports a source file whose contents this run
892 /// never analyzed, so every import and export the file holds is invisible
893 /// to the module graph.
894 ///
895 /// This is the class `reachability_caveats[]` exists for. A file the run
896 /// never read credits nothing, so the modules it imports surface as
897 /// confident `unused-file` and `unused-export` findings carrying
898 /// `delete-file` and `remove-export` actions, and `fallow fix` would
899 /// otherwise apply the removal against source that still imports the
900 /// target.
901 ///
902 /// All four discovery-side kinds qualify, for the same reason and with the
903 /// same consequence:
904 ///
905 /// - `skipped-large-file` and `skipped-minified-file`: the file is in the
906 /// project tree and was never opened, so its import list is unknown.
907 /// - `skipped-source-dotdir`: the directory holds at least one source file
908 /// the project did not exclude, and none of them were traversed. The
909 /// diagnostic is capped, so it under-reports rather than over-reports;
910 /// its presence still proves unseen source exists.
911 /// - `source-read-failure`: the file was discovered and then could not be
912 /// read, so nothing was extracted from it at all.
913 ///
914 /// `source-parse-degraded` is deliberately NOT one of these, though it
915 /// belongs to the same family. Neither is `excluded-by-default-ignore`,
916 /// for a different reason: that one reports designed behavior on generated
917 /// output rather than a degraded run, and its own doc comment carries the
918 /// argument.
919 ///
920 /// `source-parse-degraded`: that file WAS read, so it has a module and
921 /// a graph node and its reachability is observable, which lets the caveat
922 /// pass narrow it: a degraded module that is itself unreachable cannot
923 /// change a reachability verdict. Every kind above has no node to ask (a
924 /// read failure has one with nothing extracted into it), so no narrowing
925 /// is available and the caveat they raise is run-level.
926 ///
927 /// The match is exhaustive on purpose: a new "the run did not see this
928 /// file" kind has to be classified here, and answering `true` is the only
929 /// wiring its findings need in order to inherit both the caveat and the
930 /// `fallow fix` withholding that follows it.
931 #[must_use]
932 pub const fn source_never_analyzed(&self) -> bool {
933 match self {
934 Self::SkippedLargeFile { .. }
935 | Self::SkippedMinifiedFile { .. }
936 | Self::SkippedSourceDotdir
937 | Self::SourceReadFailure { .. } => true,
938 Self::UndeclaredWorkspace
939 | Self::MalformedPackageJson { .. }
940 | Self::GlobMatchedNoPackageJson { .. }
941 | Self::WorkspaceGlobOutsideRoot { .. }
942 | Self::WorkspacePatternDirMissing { .. }
943 | Self::NestedProjectRoot
944 | Self::MalformedTsconfig { .. }
945 | Self::TsconfigReferenceDirMissing
946 | Self::MalformedPnpmWorkspaceYaml { .. }
947 | Self::SourceParseDegraded { .. }
948 | Self::SourceNestingTooDeep { .. }
949 | Self::BunLockbOverrideResolutionSkipped
950 | Self::BunLockOverrideResolutionSkipped
951 | Self::PnpmLockOverrideResolutionSkipped
952 | Self::NpmLockOverrideResolutionSkipped
953 | Self::BunResolutionsShadowedByOverrides
954 | Self::PnpmWorkspaceOverridesIgnored { .. }
955 | Self::NodeModulesMissing
956 | Self::BoundariesNotConfigured
957 | Self::RulePacksNotConfigured
958 | Self::ClientServerLeakNoClientRoots
959 | Self::ExcludedByDefaultIgnore { .. }
960 | Self::NoSourceFilesAnalyzed { .. }
961 | Self::FileScoresUnavailable { .. }
962 | Self::HotspotsSkipped { .. }
963 | Self::ChangeCouplingSkipped { .. }
964 | Self::ShallowClone { .. }
965 | Self::UnpinnedClock
966 | Self::OwnershipUnavailable { .. }
967 | Self::TrendSnapshotUnreadable { .. }
968 | Self::TrendGroupBaselineUnavailable { .. }
969 | Self::PluginConfigUnreadable { .. }
970 | Self::PluginEffectNotModeled { .. }
971 | Self::CoverageAutoDetected
972 | Self::FlagAgeShallowClone
973 | Self::FlagAgeUnavailable { .. }
974 | Self::IgnoreDependenciesGlobUnmatched { .. }
975 | Self::IgnoreFindingsPatternUnmatched { .. }
976 | Self::EntryPatternRedundant { .. }
977 | Self::IgnoreDependenciesEntryRedundant { .. }
978 | Self::IgnorePatternsEntryRedundant { .. }
979 | Self::OverrideRuleIneffective { .. }
980 | Self::RequestedRuleOff { .. }
981 | Self::BaselineInstallStateMismatch { .. } => false,
982 }
983 }
984
985 /// Whether this diagnostic is recorded by the ANALYZE stage (the
986 /// dependency-catalog and override detectors) rather than by workspace or
987 /// source discovery. Analysis-stage diagnostics reach the registry through
988 /// `record_workspace_diagnostics` after config load, so
989 /// `stash_workspace_diagnostics` must preserve them across combined-mode's
990 /// per-analysis config re-loads, and every analyze pass clears its previous
991 /// entries before re-recording so a fixed cause drops out on the next run
992 /// (issue #2366). The match is exhaustive on purpose: a new kind must be
993 /// classified here before it compiles.
994 ///
995 /// Classify a kind `true` ONLY when a detector reachable from the dead-code
996 /// analyze pass (`find_dead_code_full`) re-records it, because that pass is
997 /// the single clear site. A kind recorded exclusively by another stage would
998 /// be cleared by the next dead-code pass and never come back.
999 #[must_use]
1000 pub const fn is_analysis_stage(&self) -> bool {
1001 match self {
1002 Self::MalformedPnpmWorkspaceYaml { .. }
1003 | Self::BunLockbOverrideResolutionSkipped
1004 | Self::BunLockOverrideResolutionSkipped
1005 | Self::PnpmLockOverrideResolutionSkipped
1006 | Self::NpmLockOverrideResolutionSkipped
1007 | Self::BunResolutionsShadowedByOverrides
1008 | Self::PnpmWorkspaceOverridesIgnored { .. }
1009 | Self::BoundariesNotConfigured
1010 | Self::RulePacksNotConfigured
1011 | Self::ClientServerLeakNoClientRoots => true,
1012 Self::UndeclaredWorkspace
1013 | Self::MalformedPackageJson { .. }
1014 | Self::GlobMatchedNoPackageJson { .. }
1015 | Self::WorkspaceGlobOutsideRoot { .. }
1016 | Self::WorkspacePatternDirMissing { .. }
1017 | Self::NestedProjectRoot
1018 | Self::MalformedTsconfig { .. }
1019 | Self::TsconfigReferenceDirMissing
1020 | Self::SkippedLargeFile { .. }
1021 | Self::SkippedMinifiedFile { .. }
1022 | Self::SkippedSourceDotdir
1023 | Self::SourceReadFailure { .. }
1024 | Self::SourceParseDegraded { .. }
1025 | Self::SourceNestingTooDeep { .. }
1026 | Self::NodeModulesMissing
1027 | Self::ExcludedByDefaultIgnore { .. }
1028 | Self::NoSourceFilesAnalyzed { .. }
1029 | Self::FileScoresUnavailable { .. }
1030 | Self::HotspotsSkipped { .. }
1031 | Self::ChangeCouplingSkipped { .. }
1032 | Self::ShallowClone { .. }
1033 | Self::UnpinnedClock
1034 | Self::OwnershipUnavailable { .. }
1035 | Self::TrendSnapshotUnreadable { .. }
1036 | Self::TrendGroupBaselineUnavailable { .. }
1037 | Self::PluginConfigUnreadable { .. }
1038 | Self::PluginEffectNotModeled { .. }
1039 | Self::CoverageAutoDetected
1040 | Self::FlagAgeShallowClone
1041 | Self::FlagAgeUnavailable { .. }
1042 | Self::IgnoreDependenciesGlobUnmatched { .. }
1043 | Self::IgnoreFindingsPatternUnmatched { .. }
1044 | Self::EntryPatternRedundant { .. }
1045 | Self::IgnoreDependenciesEntryRedundant { .. }
1046 | Self::IgnorePatternsEntryRedundant { .. }
1047 | Self::OverrideRuleIneffective { .. }
1048 | Self::RequestedRuleOff { .. }
1049 | Self::BaselineInstallStateMismatch { .. } => false,
1050 }
1051 }
1052
1053 /// Whether this diagnostic is recorded by the HEALTH pipeline (scoring,
1054 /// churn, ownership, trend, coverage input resolution) rather than by
1055 /// workspace discovery, source discovery or the analyze stage.
1056 ///
1057 /// Health-stage diagnostics are appended to the registry after config
1058 /// load, so `stash_workspace_diagnostics` must preserve them across
1059 /// combined mode's per-analysis config re-loads, and the health run clears
1060 /// its previous entries before re-recording so a fixed CODEOWNERS drops out
1061 /// on the next run (issue #2689).
1062 ///
1063 /// They are deliberately NOT [`Self::is_analysis_stage`], although they
1064 /// share both of those properties. That predicate additionally means "the
1065 /// dead-code analyze pass re-records this", and the pass clears every kind
1066 /// answering it on entry. Health computes file scores by running that same
1067 /// pass, so a health-stage kind classified there would be wiped mid-run by
1068 /// the analysis it is reporting on.
1069 #[must_use]
1070 pub const fn is_health_stage(&self) -> bool {
1071 match self {
1072 Self::FileScoresUnavailable { .. }
1073 | Self::HotspotsSkipped { .. }
1074 | Self::ChangeCouplingSkipped { .. }
1075 | Self::ShallowClone { .. }
1076 | Self::UnpinnedClock
1077 | Self::OwnershipUnavailable { .. }
1078 | Self::TrendSnapshotUnreadable { .. }
1079 | Self::TrendGroupBaselineUnavailable { .. }
1080 | Self::CoverageAutoDetected => true,
1081 Self::UndeclaredWorkspace
1082 | Self::MalformedPackageJson { .. }
1083 | Self::GlobMatchedNoPackageJson { .. }
1084 | Self::WorkspaceGlobOutsideRoot { .. }
1085 | Self::WorkspacePatternDirMissing { .. }
1086 | Self::NestedProjectRoot
1087 | Self::MalformedTsconfig { .. }
1088 | Self::TsconfigReferenceDirMissing
1089 | Self::MalformedPnpmWorkspaceYaml { .. }
1090 | Self::SkippedLargeFile { .. }
1091 | Self::SkippedMinifiedFile { .. }
1092 | Self::SkippedSourceDotdir
1093 | Self::SourceReadFailure { .. }
1094 | Self::SourceParseDegraded { .. }
1095 | Self::SourceNestingTooDeep { .. }
1096 | Self::BunLockbOverrideResolutionSkipped
1097 | Self::BunLockOverrideResolutionSkipped
1098 | Self::PnpmLockOverrideResolutionSkipped
1099 | Self::NpmLockOverrideResolutionSkipped
1100 | Self::BunResolutionsShadowedByOverrides
1101 | Self::PnpmWorkspaceOverridesIgnored { .. }
1102 | Self::NodeModulesMissing
1103 | Self::BoundariesNotConfigured
1104 | Self::RulePacksNotConfigured
1105 | Self::ClientServerLeakNoClientRoots
1106 | Self::ExcludedByDefaultIgnore { .. }
1107 | Self::PluginConfigUnreadable { .. }
1108 | Self::PluginEffectNotModeled { .. }
1109 | Self::NoSourceFilesAnalyzed { .. }
1110 | Self::FlagAgeShallowClone
1111 | Self::FlagAgeUnavailable { .. }
1112 | Self::IgnoreDependenciesGlobUnmatched { .. }
1113 | Self::IgnoreFindingsPatternUnmatched { .. }
1114 | Self::EntryPatternRedundant { .. }
1115 | Self::IgnoreDependenciesEntryRedundant { .. }
1116 | Self::IgnorePatternsEntryRedundant { .. }
1117 | Self::OverrideRuleIneffective { .. }
1118 | Self::RequestedRuleOff { .. }
1119 | Self::BaselineInstallStateMismatch { .. } => false,
1120 }
1121 }
1122
1123 /// Whether this diagnostic is recorded by the PLUGIN stage (framework
1124 /// plugins reading their own build configs) rather than by workspace
1125 /// discovery, source discovery, the analyze stage or the health pipeline.
1126 ///
1127 /// Plugin-stage diagnostics are recorded after config load, so
1128 /// `stash_workspace_diagnostics` must preserve them across combined mode's
1129 /// per-analysis config re-loads, and each plugin run replaces the previous
1130 /// run's set so a fixed config drops out on the next run (issue #2736).
1131 ///
1132 /// They are deliberately NOT [`Self::is_analysis_stage`], although they
1133 /// share both of those properties. That predicate additionally means "the
1134 /// dead-code analyze pass re-records this", and the pass clears every kind
1135 /// answering it on entry. Plugins run in the prelude of that same pass, so
1136 /// a plugin-stage kind classified there would be wiped inside the run that
1137 /// produced it.
1138 ///
1139 /// The match is exhaustive on purpose: a new kind must be classified here
1140 /// before it compiles.
1141 #[must_use]
1142 pub const fn is_plugin_stage(&self) -> bool {
1143 match self {
1144 Self::PluginConfigUnreadable { .. } | Self::PluginEffectNotModeled { .. } => true,
1145 Self::UndeclaredWorkspace
1146 | Self::MalformedPackageJson { .. }
1147 | Self::GlobMatchedNoPackageJson { .. }
1148 | Self::WorkspaceGlobOutsideRoot { .. }
1149 | Self::WorkspacePatternDirMissing { .. }
1150 | Self::NestedProjectRoot
1151 | Self::MalformedTsconfig { .. }
1152 | Self::TsconfigReferenceDirMissing
1153 | Self::MalformedPnpmWorkspaceYaml { .. }
1154 | Self::SkippedLargeFile { .. }
1155 | Self::SkippedMinifiedFile { .. }
1156 | Self::SkippedSourceDotdir
1157 | Self::SourceReadFailure { .. }
1158 | Self::SourceParseDegraded { .. }
1159 | Self::SourceNestingTooDeep { .. }
1160 | Self::BunLockbOverrideResolutionSkipped
1161 | Self::BunLockOverrideResolutionSkipped
1162 | Self::PnpmLockOverrideResolutionSkipped
1163 | Self::NpmLockOverrideResolutionSkipped
1164 | Self::BunResolutionsShadowedByOverrides
1165 | Self::PnpmWorkspaceOverridesIgnored { .. }
1166 | Self::NodeModulesMissing
1167 | Self::BoundariesNotConfigured
1168 | Self::RulePacksNotConfigured
1169 | Self::ClientServerLeakNoClientRoots
1170 | Self::ExcludedByDefaultIgnore { .. }
1171 | Self::NoSourceFilesAnalyzed { .. }
1172 | Self::FileScoresUnavailable { .. }
1173 | Self::HotspotsSkipped { .. }
1174 | Self::ChangeCouplingSkipped { .. }
1175 | Self::ShallowClone { .. }
1176 | Self::UnpinnedClock
1177 | Self::OwnershipUnavailable { .. }
1178 | Self::TrendSnapshotUnreadable { .. }
1179 | Self::TrendGroupBaselineUnavailable { .. }
1180 | Self::CoverageAutoDetected
1181 | Self::FlagAgeShallowClone
1182 | Self::FlagAgeUnavailable { .. }
1183 | Self::IgnoreDependenciesGlobUnmatched { .. }
1184 | Self::IgnoreFindingsPatternUnmatched { .. }
1185 | Self::EntryPatternRedundant { .. }
1186 | Self::IgnoreDependenciesEntryRedundant { .. }
1187 | Self::IgnorePatternsEntryRedundant { .. }
1188 | Self::OverrideRuleIneffective { .. }
1189 | Self::RequestedRuleOff { .. }
1190 | Self::BaselineInstallStateMismatch { .. } => false,
1191 }
1192 }
1193}
1194
1195/// Render a byte count as a megabyte figure with one decimal place for
1196/// human-readable diagnostic messages (e.g. `12.3 MB`).
1197#[must_use]
1198fn format_size_mb(bytes: u64) -> String {
1199 #[expect(
1200 clippy::cast_precision_loss,
1201 reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
1202 )]
1203 let mb = bytes as f64 / (1024.0 * 1024.0);
1204 format!("{mb:.1} MB")
1205}
1206
1207/// A diagnostic about a workspace-discovery candidate.
1208///
1209/// The `message` field is a human-readable rendering derived from `kind`. It
1210/// always ends with a concrete next step ("fix the JSON syntax", "remove from
1211/// `workspaces`", "add to `ignorePatterns`") so first-time users have a path
1212/// forward.
1213#[derive(Debug, Clone, Serialize, Deserialize)]
1214#[cfg_attr(feature = "schema", derive(JsonSchema))]
1215pub struct WorkspaceDiagnostic {
1216 /// Path to the directory or file that triggered the diagnostic.
1217 #[serde(serialize_with = "serde_path::serialize")]
1218 pub path: PathBuf,
1219 /// Kind discriminator with the typed payload.
1220 #[serde(flatten)]
1221 pub kind: WorkspaceDiagnosticKind,
1222 /// Human-readable rendering derived from `kind` + `path`. Always ends
1223 /// with a next-step hint.
1224 pub message: String,
1225 /// True when this diagnostic reports a run whose RESULTS are degraded:
1226 /// something the user installed, wrote, or expected did not reach the
1227 /// analysis. Projected from [`WorkspaceDiagnosticKind::warns_on_stderr`],
1228 /// which is the same classification that decides whether the CLI prints a
1229 /// stderr line, so a CI log built from this field and a local non-quiet run
1230 /// say the same thing.
1231 ///
1232 /// Omitted when false, which is what keeps every clean run byte-identical.
1233 /// The two unconfigured-check kinds answer false on purpose: they fire in
1234 /// the product's default state on every project that never opted into
1235 /// boundaries or rule packs, so warning on them would warn forever. So does
1236 /// `excluded-by-default-ignore`, which is designed behavior on generated
1237 /// output; the alarm for that case is `no-source-files-analyzed`.
1238 ///
1239 /// Read this instead of hardcoding a kind allowlist: a degrading kind added
1240 /// in a later release then reaches an unchanged consumer.
1241 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1242 pub degrades_analysis: bool,
1243}
1244
1245impl WorkspaceDiagnostic {
1246 /// Construct a diagnostic with the message rendered from `kind` + `path`.
1247 ///
1248 /// `root` is used to produce project-relative paths in the message text
1249 /// AND inside the variant payload (e.g. the `error` field of
1250 /// `MalformedPackageJson` / `MalformedTsconfig` which embed the absolute
1251 /// file path from `PackageJson::load()`'s error text). Without the
1252 /// payload-side normalisation the embedded path would survive
1253 /// environment-specific differences (CI vs Docker vs local) because the
1254 /// post-serialisation `strip_root_prefix` only catches whole-string
1255 /// matches, not paths embedded mid-sentence.
1256 ///
1257 /// If `path` is not under `root` (e.g. canonicalisation crossed a
1258 /// symlink), the absolute path is emitted instead.
1259 ///
1260 /// `path` also loses any no-op `.` component, for the same reason the
1261 /// payload loses a glob's `./` prefix: one directory reached through two
1262 /// spellings of one glob must be one diagnostic.
1263 #[must_use]
1264 pub fn new(root: &Path, path: PathBuf, kind: WorkspaceDiagnosticKind) -> Self {
1265 let path = normalise_diagnostic_path(path);
1266 let kind = normalise_payload_paths(root, kind);
1267 let message = render_message(root, &path, &kind);
1268 let degrades_analysis = kind.warns_on_stderr();
1269 Self {
1270 path,
1271 kind,
1272 message,
1273 degrades_analysis,
1274 }
1275 }
1276
1277 /// Return this diagnostic with `path` rewritten relative to `root`.
1278 ///
1279 /// `path` is stored absolute so callers can act on it. Every JSON envelope
1280 /// emits it project-relative instead: the analysis envelopes get there
1281 /// through the post-serialisation `strip_root_prefix` pass, which the
1282 /// `fallow workspaces` / `fallow list --workspaces` envelope and the MCP
1283 /// `project_info` tool never run, so those emitted the absolute path while
1284 /// the sibling `workspaces[].path` next to it was relative. They normalise
1285 /// at the typed layer with this method instead.
1286 ///
1287 /// Paths outside `root` (canonicalisation crossed a symlink) are left
1288 /// absolute, matching how [`Self::new`] renders the message.
1289 ///
1290 /// A diagnostic anchored at the root itself becomes `.`, not the empty
1291 /// path: an empty string is not a location, and the analysis envelopes'
1292 /// post-serialisation strip only removes a `root + separator` prefix, so a
1293 /// root-anchored path that stays absolute here leaks a host path.
1294 #[must_use]
1295 pub fn into_root_relative(mut self, root: &Path) -> Self {
1296 if let Ok(relative) = self.path.strip_prefix(root) {
1297 self.path = if relative.as_os_str().is_empty() {
1298 PathBuf::from(".")
1299 } else {
1300 relative.to_path_buf()
1301 };
1302 }
1303 self
1304 }
1305}
1306
1307/// Rebuild `path` from its components so one directory has one spelling.
1308///
1309/// The dedupe key was never the problem: [`Path`] equality already ignores an
1310/// interior `.`, so `<root>/./pkgs/aaa` and `<root>/pkgs/aaa` are one key. The
1311/// stored bytes were. A workspace glob spelled `./pkgs/*` in `package.json`
1312/// expands to the first spelling and the same glob spelled `pkgs/*` in
1313/// `pnpm-workspace.yaml` expands to the second, and the two envelope families
1314/// make a project-relative path differently: the analysis envelopes strip the
1315/// root as a string (leaving `./pkgs/aaa`) while the workspace listing
1316/// envelope uses [`WorkspaceDiagnostic::into_root_relative`] (leaving
1317/// `pkgs/aaa`). Whichever
1318/// manifest happened to be read first then decided which shape every consumer
1319/// saw. Collapsing at construction gives them one answer (issue #2366).
1320///
1321/// A path that is already component-clean rebuilds to itself. Serialization
1322/// normalises separators, so the rebuild is wire-invisible on Windows.
1323fn normalise_diagnostic_path(path: PathBuf) -> PathBuf {
1324 let rebuilt: PathBuf = path.components().collect();
1325 if rebuilt.as_os_str() == path.as_os_str() {
1326 path
1327 } else {
1328 rebuilt
1329 }
1330}
1331
1332/// Strip the project root from absolute paths embedded inside variant
1333/// payloads (the `error` field of malformed-config and source-read failures),
1334/// and drop a glob pattern's no-op `./` prefix.
1335///
1336/// Mirrors the per-platform `display()` byte sequence so the substring match
1337/// works on Windows too.
1338///
1339/// The pattern prefix matters because the payload is part of the dedupe key in
1340/// [`merge_workspace_diagnostics`]. A repository whose `package.json` declares
1341/// `"./apps/**"` and whose `pnpm-workspace.yaml` declares `apps/**` names one
1342/// glob twice, and without this both spellings would report every package-less
1343/// directory under `apps/` a second time (issue #2366).
1344fn normalise_payload_paths(root: &Path, kind: WorkspaceDiagnosticKind) -> WorkspaceDiagnosticKind {
1345 let root_str = root.display().to_string();
1346 let root_alt = root_str.replace('\\', "/");
1347 let normalise = |text: String| -> String {
1348 let stripped = text
1349 .replace(&format!("{root_str}/"), "")
1350 .replace(&format!("{root_alt}/"), "");
1351 stripped
1352 .replace(&format!("{root_str}\\"), "")
1353 .replace(&format!("{root_alt}\\"), "")
1354 };
1355 match kind {
1356 WorkspaceDiagnosticKind::MalformedPackageJson { error } => {
1357 WorkspaceDiagnosticKind::MalformedPackageJson {
1358 error: normalise(error),
1359 }
1360 }
1361 WorkspaceDiagnosticKind::MalformedTsconfig { error } => {
1362 WorkspaceDiagnosticKind::MalformedTsconfig {
1363 error: normalise(error),
1364 }
1365 }
1366 WorkspaceDiagnosticKind::SourceReadFailure { error } => {
1367 WorkspaceDiagnosticKind::SourceReadFailure {
1368 error: normalise(error),
1369 }
1370 }
1371 WorkspaceDiagnosticKind::FileScoresUnavailable { error } => {
1372 WorkspaceDiagnosticKind::FileScoresUnavailable {
1373 error: normalise(error),
1374 }
1375 }
1376 WorkspaceDiagnosticKind::OwnershipUnavailable { cause, error } => {
1377 WorkspaceDiagnosticKind::OwnershipUnavailable {
1378 cause,
1379 error: normalise(error),
1380 }
1381 }
1382 WorkspaceDiagnosticKind::TrendSnapshotUnreadable { error } => {
1383 WorkspaceDiagnosticKind::TrendSnapshotUnreadable {
1384 error: normalise(error),
1385 }
1386 }
1387 WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => {
1388 WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
1389 pattern: canonical_glob_pattern(pattern),
1390 }
1391 }
1392 WorkspaceDiagnosticKind::WorkspaceGlobOutsideRoot { pattern } => {
1393 WorkspaceDiagnosticKind::WorkspaceGlobOutsideRoot {
1394 pattern: canonical_glob_pattern(pattern),
1395 }
1396 }
1397 WorkspaceDiagnosticKind::WorkspacePatternDirMissing { pattern } => {
1398 WorkspaceDiagnosticKind::WorkspacePatternDirMissing {
1399 pattern: canonical_glob_pattern(pattern),
1400 }
1401 }
1402 other => other,
1403 }
1404}
1405
1406/// Drop the leading `./` (or `.\`) a workspace glob may carry, so the same
1407/// pattern declared in two manifests is one payload.
1408///
1409/// A pattern that is nothing BUT the prefix (`"./"`, the root itself) keeps
1410/// its spelling: stripping it would report an empty `pattern` field and an
1411/// empty quoted glob in the warning text, which names no glob at all.
1412fn canonical_glob_pattern(pattern: String) -> String {
1413 for prefix in ["./", ".\\"] {
1414 if let Some(rest) = pattern.strip_prefix(prefix)
1415 && !rest.is_empty()
1416 {
1417 return rest.to_owned();
1418 }
1419 }
1420 pattern
1421}
1422
1423/// Concatenate two diagnostic lists, keeping the first occurrence of each
1424/// `(kind, path)` pair and the order of `primary` followed by the entries only
1425/// `secondary` has.
1426///
1427/// The single place diagnostics from two observation points are folded
1428/// together: an engine session's own capture plus the process registry, and
1429/// the combined run's per-analysis lists (issue #2366). A combined run walks
1430/// the project once per analysis, and per-analysis `production` modes can make
1431/// those walks see different file sets, so no single observation point holds
1432/// everything the run recorded; the union does, and folding it the same way
1433/// everywhere is what keeps the CLI and the programmatic route answering
1434/// identically.
1435///
1436/// The key is the WHOLE kind, payload included, not its
1437/// [`id`](WorkspaceDiagnosticKind::id). Two entries can share a kind id and a
1438/// path and still be two distinct diagnostics: overlapping workspace globs
1439/// (`["packages/*", "packages/*/*"]`) each report the same package-less
1440/// directory with their own `pattern`, and the standalone envelopes report
1441/// both. An id-keyed fold silently dropped the second one.
1442#[must_use]
1443pub fn merge_workspace_diagnostics(
1444 primary: Vec<WorkspaceDiagnostic>,
1445 secondary: Vec<WorkspaceDiagnostic>,
1446) -> Vec<WorkspaceDiagnostic> {
1447 let mut merged = Vec::with_capacity(primary.len() + secondary.len());
1448 let mut seen: FxHashSet<(WorkspaceDiagnosticKind, PathBuf)> = FxHashSet::default();
1449 for diagnostic in primary.into_iter().chain(secondary) {
1450 let key = (diagnostic.kind.clone(), diagnostic.path.clone());
1451 if seen.insert(key) {
1452 merged.push(diagnostic);
1453 }
1454 }
1455 merged
1456}
1457
1458/// Keep the first occurrence of each `(kind, path)` pair in one list.
1459///
1460/// The single-list form of [`merge_workspace_diagnostics`], applied where
1461/// diagnostics are produced rather than where two observation points are
1462/// folded: workspace discovery reads `package.json` `workspaces`,
1463/// `pnpm-workspace.yaml` `packages`, `deno.json` `workspace` and the root
1464/// `tsconfig.json` references additively, so a repository that declares one
1465/// glob in two of them reports every package-less directory under it twice.
1466/// Deduplicating at that source is what keeps the JSON envelopes, the
1467/// aggregated stderr warning and the process registry telling one story
1468/// (issue #2366).
1469#[must_use]
1470pub fn dedupe_workspace_diagnostics(
1471 diagnostics: Vec<WorkspaceDiagnostic>,
1472) -> Vec<WorkspaceDiagnostic> {
1473 merge_workspace_diagnostics(diagnostics, Vec::new())
1474}
1475
1476/// The first segment of a glob that contains no glob metacharacter, so it
1477/// names a real directory rather than a wildcard.
1478///
1479/// Source discovery uses it to decide which directory a built-in ignore
1480/// pattern excluded a file "at"; `render_message` uses it to decide which
1481/// remedy is true for that pattern. The two have to agree, so the function
1482/// lives here rather than once per crate: a pattern with such a segment
1483/// (`**/dist/**`) is lifted by re-rooting inside the matched directory,
1484/// because the glob is matched against the path relative to the run root. A
1485/// pattern without one (`**/*.min.js`) matches on the file name and keeps
1486/// matching at every root.
1487#[must_use]
1488pub fn glob_first_literal_segment(pattern: &str) -> Option<&str> {
1489 pattern.split('/').find(|segment| {
1490 !segment.is_empty()
1491 && !segment.contains(['*', '?', '[', ']', '{', '}'])
1492 && *segment != "."
1493 && *segment != ".."
1494 })
1495}
1496
1497/// The catalog entries that a `workspace-pattern-dir-missing` diagnostic
1498/// keeps out of the run, as the subject of a sentence. `source_display` is
1499/// the declaring file, relative to the project root.
1500///
1501/// A missing directory of a root pattern hides consumers of every catalog. A
1502/// missing directory of a `packages` entry of a nested `pnpm-workspace.yaml`
1503/// hides consumers of the catalog of that file only.
1504#[must_use]
1505pub fn missing_pattern_dir_skipped_entries(source_display: &str) -> &'static str {
1506 if source_display.contains('/') && source_display.ends_with("pnpm-workspace.yaml") {
1507 "Unused entries of the catalog in that file"
1508 } else {
1509 "Unused catalog entries"
1510 }
1511}
1512
1513/// The directory part of a workspace pattern: the segments before the first
1514/// segment with a glob character, joined with `/`.
1515///
1516/// `vite/packages/*` gives `vite/packages`, `vite` gives `vite`, and a
1517/// pattern that starts with a glob segment (`**/pkg`, `{a,b}/*`) gives
1518/// `None`. A leading `./` and empty or `.` segments are dropped. Workspace
1519/// discovery uses it to find a pattern whose directory does not exist, and
1520/// the diagnostic message uses it to name that directory, so both read the
1521/// same part of the pattern.
1522#[must_use]
1523pub fn workspace_pattern_literal_dir(pattern: &str) -> Option<String> {
1524 let literal: Vec<&str> = pattern
1525 .split(['/', '\\'])
1526 .filter(|segment| !segment.is_empty() && *segment != ".")
1527 .take_while(|segment| !segment.contains(['*', '?', '[', ']', '{', '}']))
1528 .collect();
1529 if literal.is_empty() {
1530 None
1531 } else {
1532 Some(literal.join("/"))
1533 }
1534}
1535
1536fn render_message(root: &Path, path: &Path, kind: &WorkspaceDiagnosticKind) -> String {
1537 let display = display_relative(root, path);
1538 match kind {
1539 WorkspaceDiagnosticKind::UndeclaredWorkspace => format!(
1540 "Directory '{display}' contains package.json but is not declared as a workspace. \
1541 Add it to package.json workspaces or pnpm-workspace.yaml, or add it to ignorePatterns."
1542 ),
1543 WorkspaceDiagnosticKind::MalformedPackageJson { error } => format!(
1544 "Dropped workspace '{display}': package.json is not valid JSON ({error}). \
1545 Fix the JSON syntax or remove '{display}' from the workspaces pattern."
1546 ),
1547 WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => format!(
1548 "Glob '{pattern}' matched '{display}' but no package.json is present. \
1549 Add a package.json, narrow the pattern, or add '{display}' to ignorePatterns."
1550 ),
1551 WorkspaceDiagnosticKind::WorkspaceGlobOutsideRoot { pattern } => {
1552 let source = if display.is_empty() {
1553 "the fallow config `workspaces.patterns`".to_owned()
1554 } else {
1555 format!("'{display}'")
1556 };
1557 format!(
1558 "Skipped workspace entry '{pattern}' in {source}: it is an absolute path \
1559 or its '..' segments lead above the project root, so it can match directories \
1560 outside the root. \
1561 Fallow analyzes no package from it. Move the package inside the project root, \
1562 or run fallow with --root set to a directory that holds both."
1563 )
1564 }
1565 WorkspaceDiagnosticKind::WorkspacePatternDirMissing { pattern } => {
1566 let source = if display.is_empty() {
1567 "the fallow config `workspaces.patterns`".to_owned()
1568 } else {
1569 format!("'{display}'")
1570 };
1571 let dir = workspace_pattern_literal_dir(pattern).unwrap_or_else(|| pattern.clone());
1572 let skipped = missing_pattern_dir_skipped_entries(&display);
1573 format!(
1574 "Workspace pattern '{pattern}' in {source} names directory '{dir}', which does \
1575 not exist. Fallow analyzes no package from it. {skipped} are not \
1576 reported in this run, because packages in that directory can use them. \
1577 Create the directory before the run, or remove the pattern."
1578 )
1579 }
1580 WorkspaceDiagnosticKind::NestedProjectRoot => format!(
1581 "Directory '{display}' has its own pnpm-workspace.yaml, so it is an independent \
1582 project. Fallow analyzes it as a workspace: its package.json owns its files and \
1583 dependencies, the packages that its pnpm-workspace.yaml declares are workspaces, \
1584 and their catalog references resolve against its own catalog. Add '{display}' to \
1585 ignorePatterns to exclude it."
1586 ),
1587 WorkspaceDiagnosticKind::MalformedTsconfig { error } => format!(
1588 "tsconfig at '{display}' failed to parse ({error}); \
1589 its project references, path aliases and compiler options are ignored. \
1590 Fix the JSON syntax."
1591 ),
1592 WorkspaceDiagnosticKind::TsconfigReferenceDirMissing => format!(
1593 "tsconfig.json references '{display}' but the directory does not exist. \
1594 Update or remove the reference, or restore the missing directory."
1595 ),
1596 WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml { error } => format!(
1597 "'{display}' is not valid YAML ({error}). Catalog checks are skipped \
1598 and its override entries are ignored until it parses. pnpm install \
1599 can accept this file, but `pnpm add` and YAML formatters reject it. \
1600 Indent each continuation line of a quoted value or a `[...]` / \
1601 `{{...}}` list deeper than its key."
1602 ),
1603 WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes } => format!(
1604 "Skipped '{display}' ({size}): exceeds the max file size limit. \
1605 Its imports and exports are not analyzed. Raise the limit with \
1606 --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add '{display}' \
1607 to ignorePatterns.",
1608 size = format_size_mb(*size_bytes)
1609 ),
1610 WorkspaceDiagnosticKind::SkippedMinifiedFile { size_bytes } => format!(
1611 "Skipped '{display}' ({size}): appears to be minified generated JavaScript. \
1612 Its imports and exports are not analyzed. Add '{display}' to ignorePatterns, \
1613 rename it with a .min.js suffix, or use --max-file-size 0 if this file \
1614 should be analyzed.",
1615 size = format_size_mb(*size_bytes)
1616 ),
1617 WorkspaceDiagnosticKind::SkippedSourceDotdir => format!(
1618 "Skipped hidden directory '{display}': it contains source files but hidden \
1619 directories are not traversed. Its imports and exports are not analyzed. \
1620 A file, export or dependency that only this directory uses can be reported as \
1621 unused. To analyze it, add '!{display}/**' to ignorePatterns. To stop \
1622 that false positive without that, add the file to entry, the export to \
1623 ignoreExports or the dependency to ignoreDependencies. To silence this message, \
1624 add '{display}/**' to ignorePatterns. fallow --root {display} analyzes only \
1625 that directory on its own and does not fix this run."
1626 ),
1627 WorkspaceDiagnosticKind::SourceReadFailure { error } => format!(
1628 "Could not read source '{display}' ({error}). Restore the file or its read permissions, \
1629 ensure it contains valid UTF-8 text, or add '{display}' to ignorePatterns."
1630 ),
1631 WorkspaceDiagnosticKind::SourceParseDegraded {
1632 error_count,
1633 panicked,
1634 } => {
1635 let outcome = if *panicked {
1636 "the parser stopped there"
1637 } else {
1638 "the parser recovered and continued"
1639 };
1640 format!(
1641 "Parsed '{display}' with {error_count} error(s); {outcome}. Imports, exports, and \
1642 references it did not reach are missing from this run, so files and symbols it \
1643 uses can be reported as unused. Fix the syntax, or ignore this if the file uses \
1644 syntax newer than fallow's parser."
1645 )
1646 }
1647 WorkspaceDiagnosticKind::SourceNestingTooDeep { limit } => format!(
1648 "Did not parse '{display}': it nests brackets deeper than {limit} levels, or it \
1649 needs more stack than fallow reserves, so a parse could overflow the stack. Its \
1650 imports and exports are missing from this run, so files and symbols it uses can be \
1651 reported as unused, and while the file is reachable `fallow fix` holds back its \
1652 actions for the whole project. Add '{display}' to ignoreFindings if it is generated \
1653 code, or reduce its nesting."
1654 ),
1655 WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped => format!(
1656 "Skipped dependency-override resolution for '{display}': bun's legacy binary bun.lockb \
1657 sits next to it, fallow cannot read the binary format, and no parseable text lockfile \
1658 (bun.lock, pnpm-lock.yaml, package-lock.json, or npm-shrinkwrap.json) was found to \
1659 use instead, so unused-dependency-overrides findings are not reported. Run bun install \
1660 --save-text-lockfile (bun 1.2 or newer) to write a text bun.lock, or delete the stale \
1661 bun.lockb if this repository no longer uses bun."
1662 ),
1663 WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped => format!(
1664 "Skipped dependency-override resolution because '{display}' could not be parsed and \
1665 no readable pnpm or npm lockfile was available, so unused-dependency-overrides \
1666 findings are not reported. Run bun install to regenerate the text lockfile, then \
1667 rerun fallow."
1668 ),
1669 WorkspaceDiagnosticKind::PnpmLockOverrideResolutionSkipped => format!(
1670 "Skipped dependency-override resolution because '{display}' could not be parsed and \
1671 no other parseable lockfile was available, so unused-dependency-overrides findings \
1672 are not reported. Resolve any merge-conflict markers in the lockfile, or run pnpm \
1673 install to regenerate it, then rerun fallow."
1674 ),
1675 WorkspaceDiagnosticKind::NpmLockOverrideResolutionSkipped => format!(
1676 "Skipped dependency-override resolution because '{display}' could not be parsed and \
1677 no other parseable lockfile was available, so unused-dependency-overrides findings \
1678 are not reported. Resolve any merge-conflict markers in the lockfile, or run npm \
1679 install to regenerate it, then rerun fallow."
1680 ),
1681 WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides => format!(
1682 "'{display}' declares both `overrides` and non-empty `resolutions`; bun applies \
1683 `overrides` and ignores `resolutions`. Move the intended pins into `overrides` or \
1684 remove the shadowed `resolutions` entries."
1685 ),
1686 WorkspaceDiagnosticKind::PnpmWorkspaceOverridesIgnored {
1687 cause: PnpmWorkspaceOverridesIgnoredCause::PackageJsonOverrides,
1688 } => format!(
1689 "pnpm 10 and earlier ignore the `overrides` in '{display}' because the root package.json \
1690 declares `pnpm.overrides` or `resolutions`, so fallow does not check them. Move the \
1691 entries into one source."
1692 ),
1693 WorkspaceDiagnosticKind::PnpmWorkspaceOverridesIgnored {
1694 cause: PnpmWorkspaceOverridesIgnoredCause::PnpmVersion,
1695 } => format!(
1696 "pnpm versions before 10.5.1 do not read the `overrides` in '{display}', so fallow \
1697 does not check them. Update `packageManager` to pnpm 10.5.1 or later, or move the \
1698 entries into `pnpm.overrides` in the root package.json."
1699 ),
1700 WorkspaceDiagnosticKind::NodeModulesMissing => format!(
1701 "'{display}' does not exist. Package exports and conditional exports cannot be read, \
1702 framework plugins that activate on an installed package stay inactive, and \
1703 dependency classification degrades, so imports and dependencies can be \
1704 misreported. Run npm install / pnpm install / yarn / bun install first."
1705 ),
1706 WorkspaceDiagnosticKind::BoundariesNotConfigured => {
1707 "No architecture boundaries are configured, so the boundary detector did not run and \
1708 its violation counts are zero because nothing was measured. Add `boundaries` to the \
1709 config, or set `boundary-violation` to off to state that the check is not wanted."
1710 .to_string()
1711 }
1712 WorkspaceDiagnosticKind::RulePacksNotConfigured => {
1713 "No rule packs are configured, so the policy detector did not run and its violation \
1714 counts are zero because nothing was measured. Add `rulePacks` to the config, or set \
1715 `policy-violation` to off to state that the check is not wanted."
1716 .to_string()
1717 }
1718 WorkspaceDiagnosticKind::ClientServerLeakNoClientRoots => {
1719 "No file has a top-level \"use client\" directive, so the client-server-leak \
1720 detector had no starting point and its zero count measures nothing. The rule does \
1721 not apply to projects whose client code has no \"use client\" directive, such as \
1722 React Router Framework Mode or a Vite SPA."
1723 .to_string()
1724 }
1725 WorkspaceDiagnosticKind::NoSourceFilesAnalyzed {
1726 excluded_file_count,
1727 } => {
1728 if *excluded_file_count == 0 {
1729 "No source files were analyzed, so every finding count this run reports is zero \
1730 because nothing was measured. Check the analysis root, ignorePatterns, and any \
1731 path or workspace filter this run applied."
1732 .to_owned()
1733 } else {
1734 format!(
1735 "No source files were analyzed. Fallow's built-in ignore patterns excluded \
1736 {excluded_file_count} candidate files, so every finding count this run \
1737 reports is zero because nothing was measured; run with --explain-skipped \
1738 for the breakdown."
1739 )
1740 }
1741 }
1742 WorkspaceDiagnosticKind::FileScoresUnavailable { error } => format!(
1743 "Could not compute per-file health scores ({error}), so the score list is empty and \
1744 the scored-file count is 0 because nothing was measured rather than because the \
1745 project has nothing to score. Rerun with --no-cache, or scope the run to a \
1746 subdirectory to find the input that fails."
1747 ),
1748 WorkspaceDiagnosticKind::HotspotsSkipped { cause } => match cause.as_str() {
1749 "invalid-since" => "Hotspot analysis was skipped because --since could not be read \
1750 as a time window, so the hotspots, churn and ownership sections report nothing \
1751 rather than zero. Spell it as a duration such as 6m or 90d, or drop it to use \
1752 the default window."
1753 .to_owned(),
1754 "no-commits" => "Hotspot analysis was skipped because the current branch has no \
1755 commits yet, so the hotspots, churn and ownership sections report nothing \
1756 rather than zero. Commit the project to give churn a history, or pass \
1757 --churn-file with exported change history."
1758 .to_owned(),
1759 "churn-file-unreadable" => format!(
1760 "Hotspot analysis was skipped because the churn file '{display}' could no longer \
1761 be read after it was validated, so the hotspots, churn and ownership sections \
1762 report nothing rather than zero. Make sure nothing rewrites the file while \
1763 fallow runs, and rerun."
1764 ),
1765 // The original single cause, whose wording predates the token and
1766 // is kept byte-identical: a consumer matching on this sentence is
1767 // reading the same run it always was.
1768 _ => "Hotspot analysis was skipped because no git repository was found at the \
1769 project root, so the hotspots, churn and ownership sections report nothing \
1770 rather than zero. Run fallow inside the repository, or pass --churn-file with \
1771 exported change history."
1772 .to_owned(),
1773 },
1774 WorkspaceDiagnosticKind::ChangeCouplingSkipped { cause } => match cause.as_str() {
1775 "shallow-clone" => "Change coupling was not measured because the repository is a \
1776 shallow clone, so no change coupling pairs are reported. Fetch the full \
1777 history with `git fetch --unshallow` to measure it."
1778 .to_owned(),
1779 _ => "Change coupling found no pairs because the history window has fewer \
1780 analyzed commits than the minimum revisions of one file. Widen the window \
1781 with --since, or lower health.changeCoupling.minRevisions."
1782 .to_owned(),
1783 },
1784 WorkspaceDiagnosticKind::ShallowClone {
1785 ownership_requested,
1786 } => {
1787 let ownership = if *ownership_requested {
1788 " Ownership signals are skewed too, because a shallow clone inflates \
1789 single-author dominance."
1790 } else {
1791 ""
1792 };
1793 format!(
1794 "This is a shallow clone, so churn covers only the fetched history and every \
1795 hotspot figure is incomplete.{ownership} Run git fetch --unshallow for the full \
1796 history."
1797 )
1798 }
1799 WorkspaceDiagnosticKind::UnpinnedClock => {
1800 "No commit timestamp was available, so churn recency and ownership staleness were \
1801 measured against the wall clock and drift between runs over the same commit. Set \
1802 FALLOW_CLOCK_EPOCH to pin the run clock."
1803 .to_owned()
1804 }
1805 WorkspaceDiagnosticKind::OwnershipUnavailable { cause, error } => {
1806 if cause == "codeowners-parse-failed" {
1807 format!(
1808 "Ownership signals are degraded: CODEOWNERS could not be parsed ({error}), \
1809 so hotspot entries carry no declared owner. Fix the CODEOWNERS syntax, or \
1810 drop --ownership for this run."
1811 )
1812 } else {
1813 format!(
1814 "Ownership signals are degraded: health.ownership.botPatterns contains an \
1815 invalid glob ({error}), so no author is classified as a bot and bot commits \
1816 count towards ownership. Fix the pattern, or remove it from the config."
1817 )
1818 }
1819 }
1820 WorkspaceDiagnosticKind::TrendSnapshotUnreadable { error } => format!(
1821 "Skipped health snapshot '{display}' ({error}), so the trend is computed over fewer \
1822 snapshots than this project has on disk. Delete the unreadable file, or rewrite it \
1823 with fallow health --save-snapshot."
1824 ),
1825 WorkspaceDiagnosticKind::TrendGroupBaselineUnavailable { cause } => {
1826 if cause == "grouped-by-mismatch" {
1827 format!(
1828 "Health snapshot '{display}' was saved with a different --group-by mode, so \
1829 the groups have no trend. The project trend is not affected. Save a new \
1830 snapshot with the same --group-by mode."
1831 )
1832 } else {
1833 format!(
1834 "Health snapshot '{display}' holds no group data, so the groups have no \
1835 trend. The project trend is not affected. Save a new snapshot with \
1836 --group-by and --save-snapshot."
1837 )
1838 }
1839 }
1840 WorkspaceDiagnosticKind::CoverageAutoDetected => format!(
1841 "Coverage was auto-detected at '{display}' rather than passed with --coverage, so the \
1842 CRAP scores depend on whichever coverage file is on disk at run time. Pass --coverage \
1843 '{display}' explicitly for reproducible scores."
1844 ),
1845 WorkspaceDiagnosticKind::FlagAgeShallowClone => {
1846 "This is a shallow clone, so the flag retirement report gives no flag age. Run git \
1847 fetch --unshallow for the full history, or pass --flag-age off."
1848 .to_owned()
1849 }
1850 WorkspaceDiagnosticKind::BaselineInstallStateMismatch {
1851 baseline_node_modules,
1852 ..
1853 } => {
1854 let (saved, now, remedy) = match baseline_node_modules {
1855 NodeModulesState::Present => (
1856 "present",
1857 "has no node_modules",
1858 "Install dependencies before you compare",
1859 ),
1860 NodeModulesState::Missing => (
1861 "missing",
1862 "has node_modules",
1863 "Compare without installed dependencies",
1864 ),
1865 };
1866 format!(
1867 "The baseline '{display}' was saved with node_modules {saved}, and this run \
1868 {now}. Findings that need installed packages (dependency, unlisted, \
1869 unresolved-import and script-binary findings) can differ, so the run can report \
1870 baseline findings as new. {remedy}, or save the baseline again in the same \
1871 install state."
1872 )
1873 }
1874 WorkspaceDiagnosticKind::IgnoreDependenciesGlobUnmatched { .. }
1875 | WorkspaceDiagnosticKind::IgnoreFindingsPatternUnmatched { .. }
1876 | WorkspaceDiagnosticKind::EntryPatternRedundant { .. }
1877 | WorkspaceDiagnosticKind::IgnoreDependenciesEntryRedundant { .. }
1878 | WorkspaceDiagnosticKind::IgnorePatternsEntryRedundant { .. }
1879 | WorkspaceDiagnosticKind::OverrideRuleIneffective { .. }
1880 | WorkspaceDiagnosticKind::RequestedRuleOff { .. } => {
1881 config_entry::config_entry_message(kind)
1882 }
1883 WorkspaceDiagnosticKind::FlagAgeUnavailable { cause } => {
1884 if cause == "no-commits" {
1885 "The flag retirement report gives no flag age, because the current branch has no \
1886 commit. Commit the code, or pass --flag-age off."
1887 .to_owned()
1888 } else {
1889 "The flag retirement report gives no flag age, because no git repository was \
1890 found at the project root. Run fallow inside the repository, or pass --flag-age \
1891 off."
1892 .to_owned()
1893 }
1894 }
1895 WorkspaceDiagnosticKind::PluginConfigUnreadable {
1896 plugin,
1897 key,
1898 reason,
1899 } => {
1900 let (consequence, advice) = plugin_text::unreadable_key_consequence(key, reason);
1901 format!(
1902 "Plugin '{plugin}': `{key}` in '{display}' {situation}, so {consequence}. {advice}",
1903 situation = plugin_text::unreadable_situation(reason)
1904 )
1905 }
1906 WorkspaceDiagnosticKind::PluginEffectNotModeled {
1907 plugin,
1908 key,
1909 reason,
1910 } => {
1911 // Two causes, one effect, one remedy. Each cause gets its own
1912 // sentence: the cause and the effect on the findings are separate
1913 // facts, and one sentence with two `so` clauses states neither fact
1914 // clearly.
1915 let effect = "`autoImports` kept the convention entry patterns for that surface, and \
1916 fallow reports no unused file there. Write the setting as static \
1917 literals, or remove the key to use the framework defaults.";
1918 if key.starts_with('#') {
1919 format!(
1920 "Plugin '{plugin}': fallow cannot read which names '{display}' takes from \
1921 `{key}`, so every name of `{key}` counts as used, and fallow reports no \
1922 unused file for these names. Read each name with a member access such as \
1923 `C.Card`, or import it by name."
1924 )
1925 } else if reason == "config-property-unreadable" {
1926 format!(
1927 "Plugin '{plugin}': fallow cannot read a top-level property in '{display}', so \
1928 it cannot classify the `{key}` surface. {effect}"
1929 )
1930 } else {
1931 format!(
1932 "Plugin '{plugin}': fallow does not model the effect of `{key}` in \
1933 '{display}'. {effect}"
1934 )
1935 }
1936 }
1937 WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
1938 pattern,
1939 file_count,
1940 directory_count,
1941 } => {
1942 // `path` is a location, and an empty string is not one: a built-in
1943 // that matched a file sitting directly at the analysis root
1944 // anchors at the root itself.
1945 let display = if display.is_empty() {
1946 ".".to_owned()
1947 } else {
1948 display
1949 };
1950 // The payload carries no directory list, so the message names the
1951 // one directory `path` anchors at. With several excluded
1952 // directories that is the largest group and NOT a majority, so the
1953 // sentence says which claim it is making and how many directories
1954 // it is leaving unnamed.
1955 let location = if *directory_count > 1 {
1956 format!(
1957 "Skipped {file_count} source files across {directory_count} directories, \
1958 the largest group under '{display}'"
1959 )
1960 } else if *file_count == 1 {
1961 format!("Skipped 1 source file under '{display}'")
1962 } else {
1963 format!("Skipped {file_count} source files under '{display}'")
1964 };
1965 let singular = *file_count == 1 && *directory_count <= 1;
1966 let (subject, effect) = if singular {
1967 ("it matches", "it imports, exports, or defines")
1968 } else {
1969 ("they match", "they import, export, or define")
1970 };
1971 // Only a directory-shaped built-in is lifted by re-rooting. Telling
1972 // a user with a `vendor/lib.min.js` to run `fallow --root vendor`
1973 // hands them a command that excludes the same file again.
1974 let remedy = if glob_first_literal_segment(pattern).is_some() {
1975 format!(
1976 "To analyze first-party source there, add '!{display}/**' to \
1977 ignorePatterns, or analyze that directory on its own with \
1978 fallow --root {display}."
1979 )
1980 } else {
1981 "This pattern matches a file name rather than a directory, so re-running under \
1982 a different --root excludes the same files again. Rename first-party source \
1983 that only looks generated, dropping the '.min' or '.bundle' infix, or add a \
1984 '!' entry for the file to ignorePatterns."
1985 .to_owned()
1986 };
1987 format!(
1988 "{location}: {subject} fallow's built-in ignore pattern '{pattern}', so nothing \
1989 {effect} is visible to this run. {remedy}"
1990 )
1991 }
1992 }
1993}
1994
1995#[cfg(test)]
1996#[path = "workspace_tests.rs"]
1997mod tests;