fallow-config 3.49.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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Source positions of config list entries.
//!
//! The loaded config keeps no source positions. An editor that marks one
//! entry of a list setting (for example an `ignoreDependencies` glob that
//! matched nothing) finds the entry again with [`FallowConfig::locate_list_entry`].

use std::path::{Path, PathBuf};

use super::FallowConfig;
use super::override_effect::key_sets_rule;
use super::parsing::{ConfigFormat, parse_config_to_value};

/// The place where a config file declares one entry of a list setting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigEntrySpan {
    /// The canonical path of the config file that declares the entry. For an
    /// `extends` chain, this is the file whose list is in effect.
    pub path: PathBuf,
    /// The byte offset where the entry starts, at its opening quote.
    pub start: usize,
    /// The byte offset where the entry ends, after its closing quote.
    pub end: usize,
}

impl FallowConfig {
    /// Find where the config at `config_path` declares `entry` in the
    /// top-level list setting `setting` (for example `ignoreFindings`).
    ///
    /// A list in a file replaces the list of the configs it extends, so the
    /// entry belongs to the last source in merge order that sets `setting`.
    /// Returns `None` when the extends chain does not resolve, when a remote
    /// `https://` config can set the list, or when the declaring file does not
    /// hold `entry` as a string in the list.
    #[must_use]
    pub fn locate_list_entry(
        config_path: &Path,
        setting: &str,
        entry: &str,
    ) -> Option<ConfigEntrySpan> {
        Self::locate_in_setting(config_path, setting, |path, content| {
            entry_range(path, content, setting, entry)
        })
    }

    /// Find the key that sets `rule` in the `overrides` entry with exactly
    /// these `files` globs. `rule` is the canonical name, and the key can be
    /// an alias. The rules of [`Self::locate_list_entry`] apply, because a
    /// config file replaces the whole `overrides` list of what it extends.
    #[must_use]
    pub fn locate_override_rule(
        config_path: &Path,
        rule: &str,
        files: &[String],
    ) -> Option<ConfigEntrySpan> {
        Self::locate_in_setting(config_path, "overrides", |path, content| {
            override_rule_range(path, content, rule, files)
        })
    }

    /// Find the glob `pattern` in the `files` list of the `overrides` entry
    /// with exactly these `files` globs. The rules of
    /// [`Self::locate_override_rule`] apply.
    #[must_use]
    pub fn locate_override_glob(
        config_path: &Path,
        files: &[String],
        pattern: &str,
    ) -> Option<ConfigEntrySpan> {
        Self::locate_in_setting(config_path, "overrides", |path, content| {
            override_glob_range(path, content, files, pattern)
        })
    }

    /// Run `range_in` on the last source in merge order that sets `setting`.
    fn locate_in_setting(
        config_path: &Path,
        setting: &str,
        range_in: impl Fn(&Path, &str) -> Option<(usize, usize)>,
    ) -> Option<ConfigEntrySpan> {
        let merge_order = Self::merge_order(config_path)?;
        for source in merge_order.iter().rev() {
            let path = source.as_deref()?;
            let sets_list =
                parse_config_to_value(path).is_ok_and(|value| value.get(setting).is_some());
            if !sets_list {
                continue;
            }
            let content = fallow_types::read_guard::read_to_string_bounded(
                path,
                fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
            )
            .ok()?;
            let (start, end) = range_in(path, &content)?;
            return Some(ConfigEntrySpan {
                path: path.to_path_buf(),
                start,
                end,
            });
        }
        None
    }
}

/// The byte range of the key that sets `rule` in one config file. The loader
/// skips a leading byte order mark, so the range counts it back in.
fn override_rule_range(
    path: &Path,
    content: &str,
    rule: &str,
    files: &[String],
) -> Option<(usize, usize)> {
    let text = content.trim_start_matches('\u{FEFF}');
    let offset = content.len() - text.len();
    let (start, end) = match ConfigFormat::from_path(path) {
        ConfigFormat::Json => json_override_rule_range(text, rule, files),
        ConfigFormat::Toml => toml_override_rule_range(text, rule, files),
    }?;
    Some((start + offset, end + offset))
}

/// The byte range of the glob `pattern` in the `files` list of the override
/// with exactly these `files` globs, in one config file.
fn override_glob_range(
    path: &Path,
    content: &str,
    files: &[String],
    pattern: &str,
) -> Option<(usize, usize)> {
    let text = content.trim_start_matches('\u{FEFF}');
    let offset = content.len() - text.len();
    let (start, end) = match ConfigFormat::from_path(path) {
        ConfigFormat::Json => json_override_glob_range(text, files, pattern),
        ConfigFormat::Toml => toml_override_glob_range(text, files, pattern),
    }?;
    Some((start + offset, end + offset))
}

fn json_override_glob_range(
    content: &str,
    files: &[String],
    pattern: &str,
) -> Option<(usize, usize)> {
    let parsed = parse_json_ast(content)?;
    let jsonc_parser::ast::Value::Object(root) = parsed.value.as_ref()? else {
        return None;
    };
    json_override_entries(root, files).find_map(|entry| {
        entry
            .get_array("files")?
            .elements
            .iter()
            .find_map(|glob| match glob {
                jsonc_parser::ast::Value::StringLit(literal) if literal.value == pattern => {
                    Some((literal.range.start, literal.range.end))
                }
                _ => None,
            })
    })
}

fn toml_override_glob_range(
    content: &str,
    files: &[String],
    pattern: &str,
) -> Option<(usize, usize)> {
    let document = parse_toml_document(content)?;
    toml_override_entries(&document, files)
        .into_iter()
        .find_map(|entry| {
            entry
                .get("files")?
                .as_array()?
                .iter()
                .find(|glob| glob.as_str() == Some(pattern))?
                .span()
                .map(|span| (span.start, span.end))
        })
}

fn parse_json_ast(content: &str) -> Option<jsonc_parser::ParseResult<'_>> {
    jsonc_parser::parse_to_ast(
        content,
        &jsonc_parser::CollectOptions::default(),
        &crate::jsonc::parse_options(),
    )
    .ok()
}

/// The `overrides` entries whose `files` list is exactly `files`, in config
/// order. Two entries can have the same list and set other rules.
fn json_override_entries<'a>(
    root: &'a jsonc_parser::ast::Object<'a>,
    files: &'a [String],
) -> impl Iterator<Item = &'a jsonc_parser::ast::Object<'a>> {
    root.get_array("overrides")
        .into_iter()
        .flat_map(|overrides| overrides.elements.iter())
        .filter_map(move |element| {
            let jsonc_parser::ast::Value::Object(entry) = element else {
                return None;
            };
            let globs = entry.get_array("files")?;
            let same_files = globs.elements.len() == files.len()
                && globs.elements.iter().zip(files).all(|(glob, file)| {
                    matches!(glob, jsonc_parser::ast::Value::StringLit(literal)
                        if literal.value == file.as_str())
                });
            same_files.then_some(entry)
        })
}

fn json_override_rule_range(content: &str, rule: &str, files: &[String]) -> Option<(usize, usize)> {
    let parsed = parse_json_ast(content)?;
    let jsonc_parser::ast::Value::Object(root) = parsed.value.as_ref()? else {
        return None;
    };
    json_override_entries(root, files).find_map(|entry| {
        entry
            .get_object("rules")?
            .properties
            .iter()
            .find_map(|property| {
                let (name, range) = match &property.name {
                    jsonc_parser::ast::ObjectPropName::String(literal) => {
                        (literal.value.as_ref(), literal.range)
                    }
                    jsonc_parser::ast::ObjectPropName::Word(word) => (word.value, word.range),
                };
                key_sets_rule(name, rule).then_some((range.start, range.end))
            })
    })
}

/// Parse the text of a TOML config file. This text comes from a second read
/// of the file, so it can differ from the text that the loader checked.
/// [`crate::toml_input::check_nesting`] runs first, so crafted nesting cannot
/// overflow the stack of the parser.
fn parse_toml_document(content: &str) -> Option<toml_edit::Document<&str>> {
    crate::toml_input::check_nesting(content).ok()?;
    toml_edit::Document::parse(content).ok()
}

fn toml_override_rule_range(content: &str, rule: &str, files: &[String]) -> Option<(usize, usize)> {
    let document = parse_toml_document(content)?;
    toml_override_entries(&document, files)
        .into_iter()
        .find_map(|entry| {
            let rules = entry.get("rules")?.as_table_like()?;
            rules.iter().find_map(|(name, _)| {
                if !key_sets_rule(name, rule) {
                    return None;
                }
                let span = rules.key(name)?.span()?;
                Some((span.start, span.end))
            })
        })
}

/// The `overrides` entries whose `files` list is exactly `files`, in config
/// order: tables of an array of tables, or inline tables of an array.
fn toml_override_entries<'a>(
    document: &'a toml_edit::Document<&str>,
    files: &[String],
) -> Vec<&'a dyn toml_edit::TableLike> {
    let Some(overrides) = document.as_table().get("overrides") else {
        return Vec::new();
    };
    let entries: Vec<&dyn toml_edit::TableLike> = match overrides.as_array_of_tables() {
        Some(tables) => tables
            .iter()
            .map(|table| table as &dyn toml_edit::TableLike)
            .collect(),
        None => overrides
            .as_array()
            .into_iter()
            .flat_map(toml_edit::Array::iter)
            .filter_map(toml_edit::Value::as_inline_table)
            .map(|table| table as &dyn toml_edit::TableLike)
            .collect(),
    };
    entries
        .into_iter()
        .filter(|entry| {
            entry
                .get("files")
                .and_then(toml_edit::Item::as_array)
                .is_some_and(|globs| {
                    globs.len() == files.len()
                        && globs
                            .iter()
                            .zip(files)
                            .all(|(glob, file)| glob.as_str() == Some(file.as_str()))
                })
        })
        .collect()
}

/// The byte range of `entry` in the `setting` list of one config file. The
/// loader skips a leading byte order mark, so the range counts it back in.
fn entry_range(path: &Path, content: &str, setting: &str, entry: &str) -> Option<(usize, usize)> {
    let text = content.trim_start_matches('\u{FEFF}');
    let offset = content.len() - text.len();
    let (start, end) = match ConfigFormat::from_path(path) {
        ConfigFormat::Json => json_entry_range(text, setting, entry),
        ConfigFormat::Toml => toml_entry_range(text, setting, entry),
    }?;
    Some((start + offset, end + offset))
}

fn json_entry_range(content: &str, setting: &str, entry: &str) -> Option<(usize, usize)> {
    let parsed = jsonc_parser::parse_to_ast(
        content,
        &jsonc_parser::CollectOptions::default(),
        &crate::jsonc::parse_options(),
    )
    .ok()?;
    let jsonc_parser::ast::Value::Object(root) = parsed.value? else {
        return None;
    };
    root.get_array(setting)?
        .elements
        .iter()
        .find_map(|element| match element {
            jsonc_parser::ast::Value::StringLit(literal) if literal.value == entry => {
                Some((literal.range.start, literal.range.end))
            }
            _ => None,
        })
}

fn toml_entry_range(content: &str, setting: &str, entry: &str) -> Option<(usize, usize)> {
    let document = parse_toml_document(content)?;
    document
        .as_table()
        .get(setting)?
        .as_array()?
        .iter()
        .find(|value| value.as_str() == Some(entry))?
        .span()
        .map(|span| (span.start, span.end))
}

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

    fn located_text(span: &ConfigEntrySpan) -> String {
        let content = std::fs::read_to_string(&span.path).expect("read config");
        content[span.start..span.end].to_string()
    }

    fn canonical(path: &Path) -> PathBuf {
        dunce::canonicalize(path).expect("canonical path")
    }

    #[test]
    fn finds_an_override_rule_by_its_alias_in_jsonc() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(".fallowrc.jsonc");
        std::fs::write(
            &path,
            r#"{
  "overrides": [
    { "files": ["src/**"], "rules": { "unused-files": "off" } },
    { "files": ["tools/**"], "rules": { "unused-files": "off", "dev-dependency-in-production": "off" } },
  ],
}"#,
        )
        .expect("write config");
        let files = ["tools/**".to_owned()];

        let span =
            FallowConfig::locate_override_rule(&path, "dev-dependencies-in-production", &files)
                .expect("rule is found");
        assert_eq!(located_text(&span), "\"dev-dependency-in-production\"");

        let other = ["other/**".to_owned()];
        assert!(FallowConfig::locate_override_rule(&path, "unused-files", &other).is_none());
    }

    #[test]
    fn finds_an_override_rule_in_toml_tables_and_inline_tables() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("fallow.toml");
        std::fs::write(
            &path,
            "[[overrides]]\nfiles = [\"tools/**\"]\n\n[overrides.rules]\nduplicate-exports = \"off\"\n",
        )
        .expect("write config");
        let files = ["tools/**".to_owned()];
        let span = FallowConfig::locate_override_rule(&path, "duplicate-exports", &files)
            .expect("rule is found");
        assert_eq!(located_text(&span), "duplicate-exports");

        std::fs::write(
            &path,
            "overrides = [{ files = [\"tools/**\"], rules = { re-export-cycle = \"off\" } }]\n",
        )
        .expect("write config");
        let span = FallowConfig::locate_override_rule(&path, "re-export-cycle", &files)
            .expect("rule is found");
        assert_eq!(located_text(&span), "re-export-cycle");
    }

    #[test]
    fn finds_an_override_rule_in_a_later_entry_with_the_same_files() {
        let dir = tempfile::tempdir().expect("tempdir");
        let files = ["src/**".to_owned()];
        let json = dir.path().join(".fallowrc.json");
        std::fs::write(
            &json,
            "{\"overrides\": [{\"files\": [\"src/**\"], \"rules\": {\"unused-exports\": \"off\"}}, {\"files\": [\"src/**\"], \"rules\": {\"unused-dependencies\": \"off\"}}]}\n",
        )
        .expect("write config");
        let span = FallowConfig::locate_override_rule(&json, "unused-dependencies", &files)
            .expect("rule of the second entry is found");
        assert_eq!(located_text(&span), "\"unused-dependencies\"");

        let toml = dir.path().join("fallow.toml");
        std::fs::write(
            &toml,
            "[[overrides]]\nfiles = [\"src/**\"]\n[overrides.rules]\nunused-exports = \"off\"\n\n[[overrides]]\nfiles = [\"src/**\"]\n[overrides.rules]\nunused-dependencies = \"off\"\n",
        )
        .expect("write config");
        let span = FallowConfig::locate_override_rule(&toml, "unused-dependencies", &files)
            .expect("rule of the second entry is found");
        assert_eq!(located_text(&span), "unused-dependencies");
    }

    #[test]
    fn finds_an_override_glob_in_jsonc_and_toml() {
        let dir = tempfile::tempdir().expect("tempdir");
        let files = ["src/**".to_owned(), "vendor/x.css".to_owned()];
        let json = dir.path().join(".fallowrc.json");
        std::fs::write(
            &json,
            "{\n  // other entry first\n  \"overrides\": [\n    { \"files\": [\"vendor/x.css\"], \"rules\": {} },\n    { \"files\": [\"src/**\", \"vendor/x.css\"], \"rules\": {} }\n  ]\n}\n",
        )
        .expect("write config");
        let span = FallowConfig::locate_override_glob(&json, &files, "vendor/x.css").expect("glob");
        assert_eq!(located_text(&span), "\"vendor/x.css\"");
        let content = std::fs::read_to_string(&json).expect("read");
        assert!(
            span.start > content.find("src/**").expect("second entry"),
            "the glob of the entry with the same files list"
        );

        let toml = dir.path().join("fallow.toml");
        std::fs::write(
            &toml,
            "[[overrides]]\nfiles = [\"src/**\", \"vendor/x.css\"]\n\n[overrides.rules]\n",
        )
        .expect("write config");
        let span = FallowConfig::locate_override_glob(&toml, &files, "vendor/x.css").expect("glob");
        assert_eq!(located_text(&span), "\"vendor/x.css\"");
        assert!(FallowConfig::locate_override_glob(&toml, &files, "lib/**").is_none());
    }

    #[test]
    fn finds_an_override_rule_in_the_extended_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path().join("base.json");
        std::fs::write(
            &base,
            r#"{"overrides": [{"files": ["src/**"], "rules": {"duplicate-exports": "off"}}]}"#,
        )
        .expect("write base");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(&path, r#"{"extends": ["./base.json"]}"#).expect("write config");
        let files = ["src/**".to_owned()];

        let span = FallowConfig::locate_override_rule(&path, "duplicate-exports", &files)
            .expect("rule is found");

        assert_eq!(span.path, canonical(&base));
        assert_eq!(located_text(&span), "\"duplicate-exports\"");
    }

    #[test]
    fn finds_an_entry_in_a_jsonc_config() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(".fallowrc.jsonc");
        std::fs::write(
            &path,
            "{\n  // a comment\n  \"ignoreDependencies\": [\"react\", \"@acme/*\",],\n}\n",
        )
        .expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreDependencies", "@acme/*")
            .expect("entry is found");

        assert_eq!(span.path, canonical(&path));
        assert_eq!(located_text(&span), "\"@acme/*\"");
    }

    #[test]
    fn finds_an_entry_in_a_toml_config() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("fallow.toml");
        std::fs::write(
            &path,
            "ignoreFindings = [\n  \"src/generated/**\",\n  'legacy/**',\n]\n",
        )
        .expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreFindings", "legacy/**")
            .expect("entry is found");

        assert_eq!(located_text(&span), "'legacy/**'");
    }

    #[test]
    fn finds_an_entry_in_the_extended_file_that_declares_the_list() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path().join("base.json");
        std::fs::write(&base, r#"{"ignoreFindings": ["src/old/**"]}"#).expect("write base");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(
            &path,
            r#"{"extends": ["./base.json"], "entry": ["src/main.ts"]}"#,
        )
        .expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreFindings", "src/old/**")
            .expect("entry is found");

        assert_eq!(span.path, canonical(&base));
        assert_eq!(located_text(&span), "\"src/old/**\"");
    }

    #[test]
    fn a_list_in_the_extending_file_replaces_the_base_list() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("base.json"),
            r#"{"ignoreFindings": ["src/old/**"]}"#,
        )
        .expect("write base");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(
            &path,
            r#"{"extends": ["./base.json"], "ignoreFindings": ["src/old/**"]}"#,
        )
        .expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreFindings", "src/old/**")
            .expect("entry is found");

        assert_eq!(span.path, canonical(&path));
    }

    #[test]
    fn a_later_extends_target_overrides_an_earlier_one() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("a.json"), r#"{"ignoreFindings": ["x/**"]}"#)
            .expect("write a");
        let second = dir.path().join("b.json");
        std::fs::write(&second, r#"{"ignoreFindings": ["x/**"]}"#).expect("write b");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(&path, r#"{"extends": ["./a.json", "./b.json"]}"#).expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreFindings", "x/**").expect("entry");

        assert_eq!(span.path, canonical(&second));
    }

    #[test]
    fn a_reused_extends_target_brings_its_own_extends_chain_again() {
        let dir = tempfile::tempdir().expect("tempdir");
        let deepest = dir.path().join("e.json");
        std::fs::write(&deepest, r#"{"ignoreFindings": ["x/**"]}"#).expect("write e");
        std::fs::write(dir.path().join("d.json"), r#"{"extends": ["./e.json"]}"#).expect("write d");
        std::fs::write(dir.path().join("f.json"), r#"{"ignoreFindings": ["x/**"]}"#)
            .expect("write f");
        std::fs::write(dir.path().join("g.json"), r#"{"extends": ["./d.json"]}"#).expect("write g");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(
            &path,
            r#"{"extends": ["./d.json", "./f.json", "./g.json"]}"#,
        )
        .expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreFindings", "x/**").expect("entry");

        assert_eq!(span.path, canonical(&deepest));
    }

    #[test]
    fn a_remote_source_after_the_local_ones_gives_no_location() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(&path, r#"{"extends": ["https://example.com/fallow.json"]}"#)
            .expect("write config");

        assert_eq!(
            FallowConfig::locate_list_entry(&path, "ignoreFindings", "x/**"),
            None
        );
    }

    #[test]
    fn a_byte_order_mark_does_not_shift_the_range() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(&path, "\u{FEFF}{\"ignoreFindings\": [\"a/**\"]}").expect("write config");

        let span = FallowConfig::locate_list_entry(&path, "ignoreFindings", "a/**").expect("entry");

        assert_eq!(located_text(&span), "\"a/**\"");
    }

    /// Each `[]` inside an inline table that expects a key lowers the depth
    /// counter of the TOML parser. Without a nesting check before the parse,
    /// the nested array that follows overflows the stack.
    fn toml_that_evades_the_parser_depth_limit() -> String {
        const REPEATS: usize = 200_000;
        format!(
            "a = {{{}}}\nb = {}{}\n",
            "[]".repeat(REPEATS),
            "[".repeat(REPEATS),
            "]".repeat(REPEATS)
        )
    }

    #[test]
    fn toml_entry_range_rejects_nesting_that_evades_the_parser_limit() {
        let source = toml_that_evades_the_parser_depth_limit();
        assert_eq!(toml_entry_range(&source, "b", "x"), None);
    }

    #[test]
    fn toml_override_rule_range_rejects_nesting_that_evades_the_parser_limit() {
        let source = toml_that_evades_the_parser_depth_limit();
        assert_eq!(
            toml_override_rule_range(&source, "unused-files", &["a".to_string()]),
            None
        );
    }

    #[test]
    fn an_entry_that_is_not_in_the_list_gives_no_location() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(&path, r#"{"ignoreFindings": ["a/**"]}"#).expect("write config");

        assert_eq!(
            FallowConfig::locate_list_entry(&path, "ignoreFindings", "b/**"),
            None
        );
        assert_eq!(
            FallowConfig::locate_list_entry(&path, "ignoreDependencies", "a/**"),
            None
        );
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn an_oversize_source_gives_no_span() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path().join("base.json");
        let file = std::fs::File::create(&base).expect("create base");
        file.set_len(fallow_types::read_guard::DEFAULT_MAX_READ_BYTES + 1)
            .expect("size base");
        let path = dir.path().join(".fallowrc.json");
        std::fs::write(
            &path,
            r#"{"extends": "./base.json", "ignoreDependencies": ["a"]}"#,
        )
        .expect("write config");

        assert_eq!(
            FallowConfig::locate_list_entry(&path, "ignoreDependencies", "a"),
            None
        );
    }
}