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