fallow-config 3.43.1

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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Migration check for the single-segment `*` rule in config path globs.
//!
//! Before this rule, a single `*` or `?` in a config path glob also matched
//! `/`. Now only `**` crosses directories (see [`super::compile_path_glob`]).
//! A config that used a single `*` to match nested files silently matches
//! fewer files. This module finds those patterns and the files that they
//! lost, so fallow can print one warning for each pattern on stderr.

use std::path::Path;

use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};

use super::FallowConfig;
use super::glob_validation::compile_path_glob;
use crate::external_plugin::{ExternalPluginDef, PluginDetection};
use crate::rule_pack::RulePackDef;

/// The user path globs of one config list, for example one `overrides[]`
/// entry, where at least one pattern has a single-segment wildcard.
///
/// The other patterns of the same list are kept: a file that a sibling
/// pattern still matches did not lose its match.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegacyGlobGroup {
    /// Config field path, for example `health.ignore`.
    pub field: &'static str,
    /// Text placed before each pattern in the warning: `!` for an exception.
    pub prefix: &'static str,
    /// Every pattern of the list, as the user wrote it, without the prefix.
    pub patterns: Vec<String>,
}

impl LegacyGlobGroup {
    /// True when the list makes entry points. See
    /// [`LegacyGlobNarrowing::counts_entry_sources`].
    #[must_use]
    pub fn counts_entry_sources(&self) -> bool {
        ENTRY_SOURCE_FIELDS.contains(&self.field)
    }
}

/// A config pattern that matches fewer discovered files under the
/// single-segment rule than under the old rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegacyGlobNarrowing {
    /// Config field path, for example `health.ignore`.
    pub field: &'static str,
    /// The pattern as the user wrote it, with its `!` prefix.
    pub pattern: String,
    /// The discovered files that only the old rule matched, root-relative,
    /// with `/` separators, in sorted order.
    pub legacy_only_files: Vec<String>,
    /// A rewrite with `**` that keeps the old match.
    pub suggestion: String,
}

/// Config fields whose globs make entry points.
const ENTRY_SOURCE_FIELDS: [&str; 2] = ["entry", "dynamicallyLoaded"];

/// The count of files that the warning names before "and N more".
const NAMED_FILES: usize = 3;

impl LegacyGlobNarrowing {
    /// True when the pattern makes entry points. The check then waits for
    /// the other entry sources, because a file that another source declares
    /// loses nothing (see [`Self::retain_files`]).
    #[must_use]
    pub fn counts_entry_sources(&self) -> bool {
        ENTRY_SOURCE_FIELDS.contains(&self.field)
    }

    /// Keep only the files for which `keep` returns true. Returns false when
    /// no file remains, so the pattern needs no warning.
    pub fn retain_files(&mut self, mut keep: impl FnMut(&str) -> bool) -> bool {
        self.legacy_only_files.retain(|file| keep(file));
        !self.legacy_only_files.is_empty()
    }

    /// The stderr warning for this pattern.
    #[must_use]
    pub fn message(&self) -> String {
        let count = self.legacy_only_files.len();
        let (noun, lost) = if count == 1 {
            ("file", "This file no longer matches")
        } else {
            ("files", "These files no longer match")
        };
        let named = self.legacy_only_files[..count.min(NAMED_FILES)].join(", ");
        let files = if count > NAMED_FILES {
            format!("{named}, and {} more", count - NAMED_FILES)
        } else {
            named
        };
        format!(
            "fallow: {} glob \"{}\" matches {count} fewer {noun} than before fallow 3.34.0. A \
             single \"*\" or \"?\" now matches in one folder level only. {lost}: {files}. To \
             keep the one-level match and stop this warning, write the names in place of \"*\" \
             or \"?\", for example \"{{name1,name2}}\". To match nested folders again, use \
             \"{}\".",
            self.field, self.pattern, self.suggestion
        )
    }
}

fn normalize(pattern: &str) -> &str {
    pattern.strip_prefix("./").unwrap_or(pattern)
}

fn has_wildcard(segment: &str) -> bool {
    segment != "**" && segment.contains(['*', '?'])
}

/// True when `pattern` has a `*` or `?` that the old rule let match `/`.
///
/// A wildcard segment directly after a `**` segment matches the same files
/// under both rules, so it does not count.
#[must_use]
pub fn has_single_segment_wildcard(pattern: &str) -> bool {
    let mut after_globstar = false;
    for segment in normalize(pattern).split('/') {
        if has_wildcard(segment) && !after_globstar {
            return true;
        }
        after_globstar = segment == "**";
    }
    false
}

/// Rewrite `pattern` with `**` so that it matches nested files again.
///
/// A bare `*` segment becomes `**` (`src/x/*` to `src/x/**`). Another
/// wildcard segment gets a `**/` in front (`*.test.ts` to `**/*.test.ts`).
#[must_use]
pub fn suggest_cross_directory_rewrite(pattern: &str) -> String {
    let mut out: Vec<&str> = Vec::new();
    let mut after_globstar = false;
    for segment in pattern.split('/') {
        if segment == "**" {
            if !after_globstar {
                out.push("**");
            }
            after_globstar = true;
            continue;
        }
        if has_wildcard(segment) && !after_globstar {
            out.push("**");
            if segment == "*" {
                after_globstar = true;
                continue;
            }
        }
        out.push(segment);
        after_globstar = false;
    }
    out.join("/")
}

#[derive(Default)]
struct GroupCollector {
    groups: Vec<LegacyGlobGroup>,
}

impl GroupCollector {
    fn push<'a>(
        &mut self,
        field: &'static str,
        prefix: &'static str,
        patterns: impl IntoIterator<Item = &'a str>,
    ) {
        let patterns: Vec<String> = patterns.into_iter().map(str::to_owned).collect();
        if patterns.iter().any(|p| has_single_segment_wildcard(p)) {
            self.groups.push(LegacyGlobGroup {
                field,
                prefix,
                patterns,
            });
        }
    }

    fn push_list(&mut self, field: &'static str, patterns: &[String]) {
        self.push(field, "", patterns.iter().map(String::as_str));
    }

    fn push_detection(&mut self, detection: &PluginDetection) {
        match detection {
            PluginDetection::Dependency { .. } => {}
            PluginDetection::FileExists { pattern } => {
                self.push("framework[].detection.pattern", "", [pattern.as_str()]);
            }
            PluginDetection::All { conditions } | PluginDetection::Any { conditions } => {
                for condition in conditions {
                    self.push_detection(condition);
                }
            }
        }
    }

    fn push_config(&mut self, config: &FallowConfig) {
        self.push_list("entry", &config.entry);
        self.push_list("dynamicallyLoaded", &config.dynamically_loaded);
        let positive = |p: &&String| !p.starts_with('!');
        self.push(
            "ignorePatterns",
            "",
            config
                .ignore_patterns
                .iter()
                .filter(positive)
                .map(String::as_str),
        );
        self.push(
            "ignoreFindings",
            "",
            config
                .ignore_findings
                .iter()
                .filter(positive)
                .map(String::as_str),
        );
        self.push(
            "ignoreFindings",
            "!",
            config
                .ignore_findings
                .iter()
                .filter_map(|p| p.strip_prefix('!')),
        );
        for rule in &config.ignore_exports {
            self.push("ignoreExports[].file", "", [rule.file.as_str()]);
        }
        for rule in &config.ignore_catalog_references {
            if let Some(consumer) = &rule.consumer {
                self.push(
                    "ignoreCatalogReferences[].consumer",
                    "",
                    [consumer.as_str()],
                );
            }
        }
        for entry in &config.overrides {
            self.push_list("overrides[].files", &entry.files);
        }
        self.push_list("duplicates.ignore", &config.duplicates.ignore);
        self.push_list("similarCode.ignore", &config.similar_code.ignore);
        self.push_list("health.ignore", &config.health.ignore);
        for entry in &config.health.threshold_overrides {
            self.push_list("health.thresholdOverrides[].files", &entry.files);
        }
        for zone in &config.boundaries.zones {
            self.push_list("boundaries.zones[].patterns", &zone.patterns);
        }
        self.push_list(
            "boundaries.coverage.allowUnmatched",
            &config.boundaries.coverage.allow_unmatched,
        );
    }

    fn push_plugin(&mut self, plugin: &ExternalPluginDef) {
        for used in &plugin.used_exports {
            self.push(
                "framework[].usedExports[].pattern",
                "",
                [used.pattern.as_str()],
            );
        }
        for rule in &plugin.manifest_entries {
            self.push(
                "framework[].manifestEntries[].manifests",
                "",
                [rule.manifests.as_str()],
            );
        }
        if let Some(detection) = &plugin.detection {
            self.push_detection(detection);
        }
    }

    fn push_rule_pack(&mut self, pack: &RulePackDef) {
        for rule in &pack.rules {
            self.push_list("rulePacks rules[].files", &rule.files);
            self.push_list("rulePacks rules[].exclude", &rule.exclude);
            self.push_list("rulePacks rules[].allowedFiles", &rule.allowed_files);
        }
    }
}

/// Collect every user config path glob list that has a single-segment
/// wildcard, from the config file and from the loaded plugins and rule packs.
///
/// `ignorePatterns` exceptions (`!`) are left out: a file that an exception
/// no longer lifts is not discovered, so source discovery cannot count it.
pub(super) fn collect_config_legacy_glob_groups(config: &FallowConfig) -> Vec<LegacyGlobGroup> {
    let mut collector = GroupCollector::default();
    collector.push_config(config);
    collector.groups
}

/// Add the plugin and rule-pack glob lists to `groups`.
pub(super) fn extend_legacy_glob_groups(
    groups: &mut Vec<LegacyGlobGroup>,
    plugins: &[ExternalPluginDef],
    rule_packs: &[RulePackDef],
) {
    let mut collector = GroupCollector {
        groups: std::mem::take(groups),
    };
    for plugin in plugins {
        collector.push_plugin(plugin);
    }
    for pack in rule_packs {
        collector.push_rule_pack(pack);
    }
    *groups = collector.groups;
}

struct CompiledGroup<'a> {
    group: &'a LegacyGlobGroup,
    strict: GlobSet,
    /// Index into `group.patterns`, and the old-rule matcher of that pattern.
    legacy: Vec<(usize, GlobMatcher)>,
    /// The lost files of each `legacy` entry.
    lost: Vec<Vec<String>>,
}

impl CompiledGroup<'_> {
    fn record(&mut self, path: &Path) {
        let mut strict_match: Option<bool> = None;
        for (slot, (_, matcher)) in self.legacy.iter().enumerate() {
            if !matcher.is_match(path) {
                continue;
            }
            if !*strict_match.get_or_insert_with(|| self.strict.is_match(path)) {
                self.lost[slot].push(path.to_string_lossy().replace('\\', "/"));
            }
        }
    }
}

fn compile_group(group: &LegacyGlobGroup) -> Option<CompiledGroup<'_>> {
    let mut strict = GlobSetBuilder::new();
    let mut legacy = Vec::new();
    for (idx, pattern) in group.patterns.iter().enumerate() {
        let normalized = normalize(pattern);
        if let Ok(glob) = compile_path_glob(normalized) {
            strict.add(glob);
        }
        if has_single_segment_wildcard(normalized)
            && let Ok(glob) = Glob::new(normalized)
        {
            legacy.push((idx, glob.compile_matcher()));
        }
    }
    if legacy.is_empty() {
        return None;
    }
    let lost = vec![Vec::new(); legacy.len()];
    Some(CompiledGroup {
        group,
        strict: strict.build().ok()?,
        legacy,
        lost,
    })
}

/// Compare the old and the new glob rule on the discovered files.
///
/// `relative_paths` are project-root-relative. The result holds one entry
/// for each pattern where the old rule matched a file that no pattern of the
/// same list matches under the new rule, in config order.
#[must_use]
pub fn find_legacy_glob_narrowings(
    groups: &[LegacyGlobGroup],
    relative_paths: &[&Path],
) -> Vec<LegacyGlobNarrowing> {
    let mut compiled: Vec<CompiledGroup<'_>> = groups.iter().filter_map(compile_group).collect();
    if compiled.is_empty() {
        return Vec::new();
    }
    for path in relative_paths {
        for group in &mut compiled {
            group.record(path);
        }
    }
    let mut out = Vec::new();
    for group in compiled {
        let LegacyGlobGroup {
            field,
            prefix,
            patterns,
        } = group.group;
        for ((idx, _), mut files) in group.legacy.iter().zip(group.lost) {
            if files.is_empty() {
                continue;
            }
            files.sort_unstable();
            let pattern = &patterns[*idx];
            out.push(LegacyGlobNarrowing {
                field,
                pattern: format!("{prefix}{pattern}"),
                legacy_only_files: files,
                suggestion: format!("{prefix}{}", suggest_cross_directory_rewrite(pattern)),
            });
        }
    }
    out
}

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

    #[test]
    fn detects_single_segment_wildcards() {
        assert!(has_single_segment_wildcard("*"));
        assert!(has_single_segment_wildcard("*.test.ts"));
        assert!(has_single_segment_wildcard("src/x/*"));
        assert!(has_single_segment_wildcard("./src/x/*"));
        assert!(has_single_segment_wildcard("apps/*/docs/**"));
        assert!(has_single_segment_wildcard("src/?.ts"));
        assert!(has_single_segment_wildcard("src/**/foo/*.ts"));
        assert!(!has_single_segment_wildcard("**/*.test.ts"));
        assert!(!has_single_segment_wildcard("src/**/*.ts"));
        assert!(!has_single_segment_wildcard("src/generated/**"));
        assert!(!has_single_segment_wildcard("src/index.ts"));
    }

    #[test]
    fn suggests_globstar_rewrites() {
        assert_eq!(suggest_cross_directory_rewrite("src/x/*"), "src/x/**");
        assert_eq!(suggest_cross_directory_rewrite("*.test.ts"), "**/*.test.ts");
        assert_eq!(suggest_cross_directory_rewrite("*"), "**");
        assert_eq!(
            suggest_cross_directory_rewrite("apps/*/docs/**"),
            "apps/**/docs/**"
        );
        assert_eq!(
            suggest_cross_directory_rewrite("packages/cli/src/commands/*.ts"),
            "packages/cli/src/commands/**/*.ts"
        );
        assert_eq!(suggest_cross_directory_rewrite("*/*.ts"), "**/*.ts");
    }

    fn group(field: &'static str, patterns: &[&str]) -> LegacyGlobGroup {
        LegacyGlobGroup {
            field,
            prefix: "",
            patterns: patterns.iter().map(|p| (*p).to_owned()).collect(),
        }
    }

    fn paths<'a>(raw: &[&'a str]) -> Vec<&'a Path> {
        raw.iter().map(|p| Path::new(*p)).collect()
    }

    #[test]
    fn counts_files_only_the_old_rule_matched() {
        let files = paths(&[
            "a.test.ts",
            "src/b.test.ts",
            "src/deep/c.test.ts",
            "src/d.ts",
        ]);
        let found = find_legacy_glob_narrowings(&[group("health.ignore", &["*.test.ts"])], &files);
        assert_eq!(found.len(), 1);
        assert_eq!(
            found[0].legacy_only_files,
            ["src/b.test.ts", "src/deep/c.test.ts"]
        );
        assert_eq!(found[0].suggestion, "**/*.test.ts");
        assert_eq!(
            found[0].message(),
            "fallow: health.ignore glob \"*.test.ts\" matches 2 fewer files than before fallow \
             3.34.0. A single \"*\" or \"?\" now matches in one folder level only. These files no \
             longer match: src/b.test.ts, src/deep/c.test.ts. To keep the one-level match and \
             stop this warning, write the names in place of \"*\" or \"?\", for example \
             \"{name1,name2}\". To match nested folders again, use \"**/*.test.ts\"."
        );
    }

    #[test]
    fn the_message_names_three_files_then_the_remaining_count() {
        let files = paths(&[
            "src/e/e.ts",
            "src/a/a.ts",
            "src/d/d.ts",
            "src/c/c.ts",
            "src/b/b.ts",
        ]);
        let found = find_legacy_glob_narrowings(&[group("entry", &["src/*.ts"])], &files);
        assert_eq!(
            found[0].message(),
            "fallow: entry glob \"src/*.ts\" matches 5 fewer files than before fallow 3.34.0. A \
             single \"*\" or \"?\" now matches in one folder level only. These files no longer \
             match: src/a/a.ts, src/b/b.ts, src/c/c.ts, and 2 more. To keep the one-level match \
             and stop this warning, write the names in place of \"*\" or \"?\", for example \
             \"{name1,name2}\". To match nested folders again, use \"src/**/*.ts\"."
        );
    }

    #[test]
    fn the_message_uses_the_singular_for_one_file() {
        let files = paths(&["src/a/a.ts"]);
        let found = find_legacy_glob_narrowings(&[group("entry", &["src/*.ts"])], &files);
        assert!(
            found[0]
                .message()
                .contains("matches 1 fewer file than before fallow 3.34.0")
        );
        assert!(
            found[0]
                .message()
                .contains("This file no longer matches: src/a/a.ts. To keep")
        );
    }

    #[test]
    fn files_that_another_source_covers_are_removed() {
        let files = paths(&["src/a/a.ts", "src/b/b.ts"]);
        let mut found = find_legacy_glob_narrowings(&[group("entry", &["src/*.ts"])], &files);
        assert!(found[0].counts_entry_sources());
        assert!(!found[0].retain_files(|_| false));
        let mut partial = find_legacy_glob_narrowings(&[group("entry", &["src/*.ts"])], &files);
        assert!(partial[0].retain_files(|file| file == "src/b/b.ts"));
        assert_eq!(partial[0].legacy_only_files, ["src/b/b.ts"]);
        let health = find_legacy_glob_narrowings(&[group("health.ignore", &["src/*.ts"])], &files);
        assert!(!health[0].counts_entry_sources());
    }

    #[test]
    fn a_sibling_pattern_that_still_matches_suppresses_the_count() {
        let files = paths(&["src/deep/c.test.ts"]);
        let found = find_legacy_glob_narrowings(
            &[group("health.ignore", &["*.test.ts", "src/**/*.test.ts"])],
            &files,
        );
        assert!(found.is_empty());
    }

    #[test]
    fn no_narrowing_when_the_match_set_is_the_same() {
        let files = paths(&["a.test.ts", "src/b.ts"]);
        let found = find_legacy_glob_narrowings(&[group("health.ignore", &["*.test.ts"])], &files);
        assert!(found.is_empty());
    }

    #[test]
    fn exception_patterns_keep_their_prefix() {
        let files = paths(&["src/deep/c.ts"]);
        let mut exceptions = group("ignoreFindings", &["src/*"]);
        exceptions.prefix = "!";
        let found = find_legacy_glob_narrowings(&[exceptions], &files);
        assert_eq!(found[0].pattern, "!src/*");
        assert_eq!(found[0].suggestion, "!src/**");
    }
}