fallow-config 3.48.0

Configuration types and workspace discovery for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use fallow_types::discover::StableFileKey;
use globset::{GlobSet, GlobSetBuilder};

/// Compiled project-relative patterns for hiding source-owned findings.
///
/// Positive patterns select paths to hide. Negated patterns (prefixed with
/// `!`) select report exceptions. When every pattern is negated, all paths
/// outside those exceptions are hidden, matching Knip's `ignore` semantics.
#[derive(Debug, Clone, Default)]
pub struct FindingIgnoreMatcher {
    hidden: GlobSet,
    reported: GlobSet,
    usage: Option<Arc<PatternUsage>>,
}

/// Per-pattern hit state for the shared matcher.
///
/// The matcher is cloned along with the resolved config and consulted from
/// several pipeline stages, so the state lives behind an `Arc` and every clone
/// records into the same run.
#[derive(Debug)]
struct PatternUsage {
    patterns: Vec<String>,
    /// Original pattern index for each glob in `hidden`, in build order.
    hidden_origins: Vec<usize>,
    /// Original pattern index for each glob in `reported`, in build order.
    reported_origins: Vec<usize>,
    matched: Vec<AtomicBool>,
    consulted: AtomicBool,
}

impl PatternUsage {
    fn record(&self, origins: &[usize], set_indices: &[usize]) {
        for &index in set_indices {
            if let Some(&origin) = origins.get(index)
                && let Some(flag) = self.matched.get(origin)
            {
                flag.store(true, Ordering::Relaxed);
            }
        }
    }
}

/// Compiled glob sets plus the mapping back to the configured pattern order.
struct CompiledSets {
    hidden: GlobSet,
    reported: GlobSet,
    hidden_origins: Vec<usize>,
    reported_origins: Vec<usize>,
}

impl FindingIgnoreMatcher {
    #[expect(
        clippy::expect_used,
        reason = "ignoreFindings patterns are validated before config resolution"
    )]
    pub(crate) fn compile(patterns: &[String]) -> Self {
        if patterns.is_empty() {
            return Self::default();
        }

        let sets = Self::build_sets(patterns)
            .expect("ignoreFindings pattern sets were validated before config resolution");

        Self {
            hidden: sets.hidden,
            reported: sets.reported,
            usage: Some(Arc::new(PatternUsage {
                patterns: patterns.to_vec(),
                hidden_origins: sets.hidden_origins,
                reported_origins: sets.reported_origins,
                matched: patterns.iter().map(|_| AtomicBool::new(false)).collect(),
                consulted: AtomicBool::new(false),
            })),
        }
    }

    /// Compile `ignoreFindings` patterns outside config resolution.
    ///
    /// # Errors
    ///
    /// Returns the glob error of the first invalid pattern.
    pub fn try_compile(patterns: &[String]) -> Result<Self, globset::Error> {
        Self::build_sets(patterns)?;
        Ok(Self::compile(patterns))
    }

    pub(super) fn validate_compilation(patterns: &[String]) -> Result<(), globset::Error> {
        Self::build_sets(patterns).map(|_| ())
    }

    fn build_sets(patterns: &[String]) -> Result<CompiledSets, globset::Error> {
        let mut hidden = GlobSetBuilder::new();
        let mut reported = GlobSetBuilder::new();
        let mut hidden_origins = Vec::new();
        let mut reported_origins = Vec::new();

        for (index, pattern) in patterns.iter().enumerate() {
            let (builder, origins, pattern) = if let Some(pattern) = pattern.strip_prefix('!') {
                (&mut reported, &mut reported_origins, pattern)
            } else {
                (&mut hidden, &mut hidden_origins, pattern.as_str())
            };
            builder.add(super::compile_path_glob(pattern)?);
            origins.push(index);
        }

        Ok(CompiledSets {
            hidden: hidden.build()?,
            reported: reported.build()?,
            hidden_origins,
            reported_origins,
        })
    }

    /// Whether no finding-ignore patterns were configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.usage.is_none()
    }

    /// Whether a normalized project-root-relative source path is hidden.
    #[must_use]
    pub fn is_ignored(&self, path: &str) -> bool {
        let Some(usage) = self.usage.as_deref() else {
            return false;
        };
        usage.consulted.store(true, Ordering::Relaxed);

        // Both sets are matched unconditionally so a negated pattern is not
        // reported as a no-op merely because the positive set short-circuited.
        let mut indices = Vec::new();
        self.hidden.matches_into(path, &mut indices);
        let hidden_hit = !indices.is_empty();
        usage.record(&usage.hidden_origins, &indices);

        self.reported.matches_into(path, &mut indices);
        let reported_hit = !indices.is_empty();
        usage.record(&usage.reported_origins, &indices);

        (self.hidden.is_empty() || hidden_hit) && !reported_hit
    }

    /// Whether a source path is hidden, for an absolute or a root-relative path.
    ///
    /// An absolute path outside `root` is never hidden.
    #[must_use]
    pub fn is_ignored_path(&self, root: &Path, path: &Path) -> bool {
        if self.is_empty() {
            return false;
        }
        // Strip the root before the absolute check: a root such as `/project`
        // is not absolute on Windows, and a path below it must still match.
        let key = if let Ok(relative) = path.strip_prefix(root) {
            StableFileKey::from_relative(relative)
        } else if path.is_absolute() {
            return false;
        } else {
            StableFileKey::from_relative(path)
        };
        self.is_ignored(key.as_str())
    }

    /// Forget the pattern hits of an earlier analysis pass.
    ///
    /// A long-lived process (watch mode, the LSP, an engine session) keeps one
    /// resolved config for many passes. Each dead-code pass calls this first,
    /// so a pattern that matched in an earlier pass is reported again when its
    /// findings are gone.
    pub fn reset_usage(&self) {
        let Some(usage) = self.usage.as_deref() else {
            return;
        };
        usage.consulted.store(false, Ordering::Relaxed);
        for flag in &usage.matched {
            flag.store(false, Ordering::Relaxed);
        }
    }

    /// Configured patterns that matched no candidate finding path, in config
    /// order.
    ///
    /// Empty when nothing was configured or when the matcher was never
    /// consulted, because a run without candidate paths says nothing about
    /// whether a pattern is a typo.
    ///
    /// The list never holds a set of patterns whose joint removal changes
    /// which paths are hidden, because the diagnostic advises the removal of
    /// each pattern. Without every positive pattern, every path outside the
    /// exceptions is hidden. Without every negated pattern, no path is
    /// hidden. So an unmatched positive pattern beside negated patterns is
    /// listed only when another positive pattern matched, and an unmatched
    /// negated pattern without positive patterns only when another negated
    /// pattern matched.
    #[must_use]
    pub fn unmatched_patterns(&self) -> Vec<&str> {
        let Some(usage) = self.usage.as_deref() else {
            return Vec::new();
        };
        if !usage.consulted.load(Ordering::Relaxed) {
            return Vec::new();
        }
        let any_matched = |origins: &[usize]| {
            origins
                .iter()
                .any(|&origin| usage.matched[origin].load(Ordering::Relaxed))
        };
        let list_positives =
            usage.reported_origins.is_empty() || any_matched(&usage.hidden_origins);
        let list_negatives =
            !usage.hidden_origins.is_empty() || any_matched(&usage.reported_origins);
        usage
            .patterns
            .iter()
            .zip(&usage.matched)
            .filter(|(_, matched)| !matched.load(Ordering::Relaxed))
            .map(|(pattern, _)| pattern.as_str())
            .filter(|pattern| {
                if pattern.starts_with('!') {
                    list_negatives
                } else {
                    list_positives
                }
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn matcher(patterns: &[&str]) -> FindingIgnoreMatcher {
        FindingIgnoreMatcher::compile(
            &patterns
                .iter()
                .map(|pattern| (*pattern).to_string())
                .collect::<Vec<_>>(),
        )
    }

    #[test]
    fn validate_compilation_rejects_a_set_that_exceeds_matcher_limits() {
        let alternatives = (0..50_000)
            .map(|index| format!("name{index}"))
            .collect::<Vec<_>>()
            .join(",");
        let patterns = [format!("**/{{{alternatives}}}.ts")];
        assert!(FindingIgnoreMatcher::validate_compilation(&patterns).is_err());
    }

    #[test]
    fn empty_matcher_ignores_nothing() {
        let matcher = matcher(&[]);

        assert!(matcher.is_empty());
        assert!(!matcher.is_ignored("src/app.ts"));
    }

    #[test]
    fn positive_patterns_hide_matching_paths() {
        let matcher = matcher(&["**/*.test.ts"]);

        assert!(matcher.is_ignored("src/app.test.ts"));
        assert!(!matcher.is_ignored("src/app.ts"));
    }

    #[test]
    fn path_lookup_accepts_absolute_and_relative_paths() {
        let matcher = matcher(&["test/fixtures/**"]);
        // A path such as `/project` is not absolute on Windows, so build the
        // absolute paths from the platform temp directory.
        let base = std::env::temp_dir();
        let root = base.join("project");
        let root = root.as_path();

        assert!(matcher.is_ignored_path(root, &root.join("test/fixtures/bad.js")));
        assert!(matcher.is_ignored_path(root, Path::new("test/fixtures/bad.js")));
        assert!(!matcher.is_ignored_path(root, &root.join("src/app.js")));
        assert!(!matcher.is_ignored_path(root, &base.join("elsewhere/test/fixtures/bad.js")));
    }

    #[test]
    fn path_lookup_strips_a_root_that_is_not_absolute() {
        let matcher = matcher(&["test/fixtures/**"]);
        // `/project` has no drive prefix on Windows, so it is not absolute
        // there. A path below it must still match relative to the root.
        let root = Path::new("project");

        assert!(matcher.is_ignored_path(root, &root.join("test/fixtures/bad.js")));
        assert!(!matcher.is_ignored_path(root, &root.join("src/app.js")));
    }

    #[test]
    fn negated_patterns_keep_matching_paths_reported() {
        let matcher = matcher(&["**/*.ts", "!src/public/**"]);

        assert!(matcher.is_ignored("src/private/app.ts"));
        assert!(!matcher.is_ignored("src/public/app.ts"));
    }

    #[test]
    fn negated_only_patterns_report_only_matching_paths() {
        let matcher = matcher(&["!src/public/**"]);

        assert!(matcher.is_ignored("src/private/app.ts"));
        assert!(!matcher.is_ignored("src/public/app.ts"));
    }

    #[test]
    fn leading_dot_slash_is_normalized_after_negation() {
        let matcher = matcher(&["!./src/public/**"]);

        assert!(matcher.is_ignored("src/private/app.ts"));
        assert!(!matcher.is_ignored("src/public/app.ts"));
    }

    #[test]
    fn pattern_order_does_not_change_set_semantics() {
        let first = matcher(&["**/*.ts", "!src/public/**"]);
        let second = matcher(&["!src/public/**", "**/*.ts"]);

        for path in ["src/private/app.ts", "src/public/app.ts", "README.md"] {
            assert_eq!(first.is_ignored(path), second.is_ignored(path));
        }
    }

    #[test]
    fn empty_configuration_reports_no_unmatched_patterns() {
        let matcher = matcher(&[]);

        assert!(!matcher.is_ignored("src/app.ts"));
        assert!(matcher.unmatched_patterns().is_empty());
    }

    #[test]
    fn matching_pattern_is_not_reported_as_unmatched() {
        let matcher = matcher(&["**/*.test.ts"]);

        assert!(matcher.is_ignored("src/app.test.ts"));
        assert!(matcher.unmatched_patterns().is_empty());
    }

    #[test]
    fn pattern_matching_nothing_is_reported() {
        let matcher = matcher(&["**/*.test.ts", "src/legcy/**"]);

        assert!(matcher.is_ignored("src/app.test.ts"));
        assert_eq!(matcher.unmatched_patterns(), vec!["src/legcy/**"]);
    }

    #[test]
    fn unconsulted_matcher_reports_no_unmatched_patterns() {
        let matcher = matcher(&["src/legcy/**"]);

        assert!(matcher.unmatched_patterns().is_empty());
    }

    #[test]
    fn negated_pattern_matching_nothing_is_reported() {
        let matcher = matcher(&["**/*.ts", "!src/public/**", "!src/publik/**"]);

        assert!(matcher.is_ignored("src/private/app.ts"));
        assert!(!matcher.is_ignored("src/public/app.ts"));
        assert_eq!(matcher.unmatched_patterns(), vec!["!src/publik/**"]);
    }

    #[test]
    fn sole_positive_pattern_beside_exceptions_is_not_reported() {
        let matcher = matcher(&["legacy/**", "!**/*.test.ts"]);

        assert!(!matcher.is_ignored("src/app.test.ts"));
        assert!(
            matcher.unmatched_patterns().is_empty(),
            "removing the only positive pattern would hide every path outside the exceptions"
        );
    }

    #[test]
    fn sole_exception_without_positive_patterns_is_not_reported() {
        let matcher = matcher(&["!src/keep.ts"]);

        assert!(matcher.is_ignored("src/app.ts"));
        assert!(
            matcher.unmatched_patterns().is_empty(),
            "removing the only exception would stop hiding every path"
        );
    }

    #[test]
    fn one_of_several_exceptions_without_positive_patterns_is_reported() {
        let matcher = matcher(&["!src/keep.ts", "!src/publik/**"]);

        assert!(!matcher.is_ignored("src/keep.ts"));
        assert_eq!(matcher.unmatched_patterns(), vec!["!src/publik/**"]);
    }

    #[test]
    fn all_unmatched_positive_patterns_beside_exceptions_are_not_reported() {
        let matcher = matcher(&["legacy/**", "old/**", "!**/*.test.ts"]);

        assert!(!matcher.is_ignored("src/app.ts"));
        assert!(!matcher.is_ignored("src/app.test.ts"));
        assert!(
            matcher.unmatched_patterns().is_empty(),
            "removing every listed pattern would hide every path outside the exceptions"
        );
    }

    #[test]
    fn all_unmatched_exceptions_without_positive_patterns_are_not_reported() {
        let matcher = matcher(&["!src/a/**", "!src/b/**"]);

        assert!(matcher.is_ignored("src/app.ts"));
        assert!(
            matcher.unmatched_patterns().is_empty(),
            "removing every listed exception would stop hiding every path"
        );
    }

    #[test]
    fn unmatched_positive_pattern_beside_a_matched_one_is_reported() {
        let matcher = matcher(&["src/**", "legacy/**", "!**/*.test.ts"]);

        assert!(matcher.is_ignored("src/app.ts"));
        assert_eq!(
            matcher.unmatched_patterns(),
            vec!["legacy/**", "!**/*.test.ts"]
        );
    }

    #[test]
    fn usage_state_is_shared_across_clones() {
        let matcher = matcher(&["**/*.test.ts"]);
        let clone = matcher.clone();

        assert!(clone.is_ignored("src/app.test.ts"));
        assert!(matcher.unmatched_patterns().is_empty());
    }

    #[test]
    fn reset_usage_forgets_hits_of_an_earlier_pass() {
        let matcher = matcher(&["src/legacy/**"]);
        assert!(matcher.is_ignored("src/legacy/old.ts"));
        assert!(matcher.unmatched_patterns().is_empty());

        matcher.reset_usage();
        assert!(
            matcher.unmatched_patterns().is_empty(),
            "a pass that consulted nothing reports nothing"
        );
        assert!(!matcher.is_ignored("src/app.ts"));
        assert_eq!(matcher.unmatched_patterns(), vec!["src/legacy/**"]);
    }

    #[test]
    fn matches_dotfiles_and_forward_slash_paths() {
        let matcher = matcher(&["**/*.test.ts", ".storybook/**"]);

        assert!(matcher.is_ignored("packages/ui/src/button.test.ts"));
        assert!(matcher.is_ignored(".storybook/preview.ts"));
    }
}