jsonvet-cli 3.5.1

The jsonvet command: checks JSON, I-JSON, JSONC, JWCC (HuJSON), JSON5 and JSON Lines files, with JSON Schema checks, SARIF output, fixes and a formatter.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
//! What to check for each file: the dialect patterns and rule severities from the config file
//! and the command line, in that order, so the command line wins.

use std::borrow::Cow;
use std::collections::HashMap;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use jsonvet::{Config, Dialect, Indent, Rule, Severity};
use toml::Spanned;
use toml::Table;
use toml::de::{DeTable, DeValue};

use crate::args::ConfigSource;
use crate::glob::{self, Glob, Target};
use crate::messages;
use crate::output::printable;

/// A dialect for files matching a pattern, or for every file when the pattern is `None`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct DialectPattern {
    pub(crate) files: Option<Glob>,
    /// `None` means `auto`: the default for the file's extension.
    pub(crate) dialect: Option<Dialect>,
    /// The absolute directory of the config file the pattern comes from, normalized, which
    /// `files` is relative to. `None` for the command line, whose patterns match the path as
    /// given.
    pub(crate) base: Option<String>,
}

impl DialectPattern {
    /// Parse `DIALECT` or `DIALECT:GLOB`, where `DIALECT` may be `auto`.
    pub(crate) fn parse(value: &str) -> Result<Self, String> {
        let (name, files) = match value.split_once(':') {
            Some((name, files)) => (name, Some(Glob::new(files))),
            None => (value, None),
        };
        Ok(DialectPattern {
            files,
            dialect: parse_dialect(name)?,
            base: None,
        })
    }
}

/// Rule severities for the files matching a pattern, or for every file when the pattern is
/// `None`: the top-level `rules`, a `per-file-rules` entry, or an option on the command line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RulePattern {
    pub(crate) files: Option<Glob>,
    pub(crate) rules: Vec<(Rule, Severity)>,
    /// The folder `files` is relative to, as for [`DialectPattern`].
    pub(crate) base: Option<String>,
}

impl RulePattern {
    /// Severities for every file.
    pub(crate) fn every_file(rules: Vec<(Rule, Severity)>) -> Self {
        RulePattern {
            files: None,
            rules,
            base: None,
        }
    }
}

fn parse_dialect(name: &str) -> Result<Option<Dialect>, String> {
    if name == "auto" {
        return Ok(None);
    }
    name.parse()
        .map(Some)
        .map_err(|_: jsonvet::UnknownDialect| {
            let names: Vec<&str> = Dialect::ALL
                .iter()
                .map(|d| d.name())
                .chain(Dialect::ALIASES.iter().map(|&(alias, _)| alias))
                .collect();
            messages::fill(
                "error.unknown-dialect",
                &[
                    ("name", &name),
                    ("hint", &messages::did_you_mean(name, names.iter().copied())),
                    ("names", &names.join(messages::text("list.separator"))),
                ],
            )
        })
}

pub(crate) fn parse_severity(name: &str) -> Result<Severity, String> {
    match name {
        "error" => Ok(Severity::Error),
        "warning" | "warn" => Ok(Severity::Warning),
        "ignore" | "off" => Ok(Severity::Off),
        _ => Err(messages::fill(
            "error.unknown-severity",
            &[
                ("name", &name),
                (
                    "hint",
                    &messages::did_you_mean(name, ["error", "warning", "warn", "ignore", "off"]),
                ),
            ],
        )),
    }
}

/// A rule id from the command line or a settings file. File and schema errors cannot be
/// turned down, so they get their own message rather than "unknown rule".
pub(crate) fn parse_rule(id: &str) -> Result<Rule, String> {
    if matches!(id, crate::sarif::SCHEMA | crate::sarif::UNREADABLE) {
        return Err(messages::fill("error.fixed-rule", &[("id", &id)]));
    }
    id.parse().map_err(|_: jsonvet::UnknownRule| {
        let ids: Vec<&str> = Rule::ALL.iter().map(|r| r.id()).collect();
        messages::fill(
            "error.unknown-rule",
            &[
                ("id", &id),
                ("hint", &messages::did_you_mean(id, ids.iter().copied())),
                ("ids", &ids.join(messages::text("list.separator"))),
            ],
        )
    })
}

/// Dialect patterns, rule severities and excluded paths, merged from every source in order.
#[derive(Clone, Debug, Default)]
pub(crate) struct Settings {
    pub(crate) dialects: Vec<DialectPattern>,
    /// In the order they apply: a config file's `rules`, then its `per-file-rules`, then the
    /// command line's.
    pub(crate) rules: Vec<RulePattern>,
    /// Patterns for paths a directory walk skips, each with the absolute directory of the
    /// config file it comes from, normalized, which it is relative to.
    pub(crate) exclude: Vec<(Glob, String)>,
    /// Schemas for the files matching a pattern, from a config file's `schemas`.
    pub(crate) schemas: Vec<SchemaPattern>,
    /// The `[format]` table of a config file.
    pub(crate) format: FormatSettings,
    pub(crate) per_file_format: Vec<FormatPattern>,
    /// Whether these come from the user's own config file, which sits below `.editorconfig` for
    /// layout, rather than from the project's or one named with `--config`.
    pub(crate) user: bool,
}

/// The `[format]` table: what `jsonvet fmt` is told to do, where a key is set.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct FormatSettings {
    pub(crate) indent: Option<Indent>,
    pub(crate) width: Option<usize>,
    pub(crate) normalize_json5: Option<bool>,
    pub(crate) bracket_spacing: Option<bool>,
    pub(crate) fill_numbers: Option<bool>,
}

impl FormatSettings {
    fn overridden_by(self, later: Self) -> Self {
        Self {
            indent: later.indent.or(self.indent),
            width: later.width.or(self.width),
            normalize_json5: later.normalize_json5.or(self.normalize_json5),
            bracket_spacing: later.bracket_spacing.or(self.bracket_spacing),
            fill_numbers: later.fill_numbers.or(self.fill_numbers),
        }
    }
}

/// Formatting overrides for files matching a glob relative to the config file's folder.
#[derive(Clone, Debug)]
pub(crate) struct FormatPattern {
    files: Glob,
    base: Option<String>,
    format: FormatSettings,
}

/// A schema for the files matching a glob, from a config file.
#[derive(Clone, Debug)]
pub(crate) struct SchemaPattern {
    pub(crate) files: Glob,
    /// The schema file, as the config file's own folder joined with the path it gives, relative
    /// to the working directory when the folder is in it, as a `$schema` is: its errors name it
    /// by this, so they read the same on every machine.
    pub(crate) schema: PathBuf,
    /// The absolute directory `files` is relative to, normalized, as for [`DialectPattern`].
    pub(crate) base: String,
    /// From a project config: then the schema sits inside the project, and an error in it
    /// quotes nothing from it ([`confined`]). The user's own config is not confined.
    pub(crate) confined: bool,
}

impl Settings {
    /// Add `later` after `self`, so `later` wins where both say something.
    pub(crate) fn overridden_by(mut self, later: Settings) -> Settings {
        self.dialects.extend(later.dialects);
        self.rules.extend(later.rules);
        self.exclude.extend(later.exclude);
        self.schemas.extend(later.schemas);
        self.format = self.format.overridden_by(later.format);
        self.per_file_format.extend(later.per_file_format);
        self
    }

    /// The `[format]` defaults followed by each matching override in file order.
    pub(crate) fn format_for(&self, path: &str) -> FormatSettings {
        let mut located = Located::new(path);
        self.per_file_format
            .iter()
            .filter(|entry| located.matches(Some(&entry.files), entry.base.as_deref()))
            .fold(self.format, |format, entry| {
                format.overridden_by(entry.format)
            })
    }

    /// The schema the config file names for `path`, if any: the last matching entry wins, as
    /// for dialects.
    pub(crate) fn schema_for(&self, path: &str) -> Option<&SchemaPattern> {
        let mut located = Located::new(path);
        self.schemas.iter().rev().find(|entry| {
            located
                .in_base(&entry.base)
                .is_some_and(|path| entry.files.matches(path))
        })
    }

    /// Whether a directory walk skips `path`, a file or a folder.
    pub(crate) fn excluded(&self, path: &Path) -> bool {
        let path = path.to_string_lossy();
        let mut located = Located::new(&path);
        self.exclude
            .iter()
            .any(|(glob, base)| located.in_base(base).is_some_and(|path| glob.matches(path)))
    }

    /// The checking config for one file: the last matching dialect pattern wins.
    pub(crate) fn config_for(&self, path: &str) -> Config {
        let auto = || Dialect::for_path(Path::new(path)).unwrap_or(Dialect::Json5);
        let mut located = Located::new(path);
        let dialect = self
            .dialects
            .iter()
            .rev()
            .find(|rule| located.matches(rule.files.as_ref(), rule.base.as_deref()))
            .and_then(|rule| rule.dialect)
            .unwrap_or_else(auto);
        self.config(path, dialect)
    }

    /// The checking config for the file at `path` in `dialect`: the severity of each rule is the
    /// one the last matching [`RulePattern`] gives it, else the dialect's default.
    pub(crate) fn config(&self, path: &str, dialect: Dialect) -> Config {
        let mut located = Located::new(path);
        self.rules
            .iter()
            .filter(|entry| located.matches(entry.files.as_ref(), entry.base.as_deref()))
            .flat_map(|entry| &entry.rules)
            .fold(Config::new(dialect), |config, &(rule, severity)| {
                config.rule(rule, severity)
            })
    }
}

/// A path, made absolute and relative to a config file's folder only when a pattern needs it,
/// and once for each folder rather than once for each pattern: a walk matches every pattern
/// against every entry.
struct Located<'p> {
    path: &'p str,
    /// The path as given, for the command line's patterns, once one needs it.
    given: std::cell::OnceCell<Target>,
    /// The path made absolute and normalized, once a pattern needs it.
    absolute: std::cell::OnceCell<Option<String>>,
    /// The last folder asked for, and the path relative to it, if inside it.
    relative: Option<(&'p str, Option<Target>)>,
}

impl<'p> Located<'p> {
    fn new(path: &'p str) -> Located<'p> {
        Located {
            path,
            given: std::cell::OnceCell::new(),
            absolute: std::cell::OnceCell::new(),
            relative: None,
        }
    }

    /// Whether the glob `files` matches the path: relative to `base`, the folder of the config
    /// file it comes from, or as given, from the command line. No glob matches every path.
    fn matches(&mut self, files: Option<&Glob>, base: Option<&'p str>) -> bool {
        match (files, base) {
            (None, _) => true,
            (Some(glob), None) => glob.matches(self.given.get_or_init(|| Target::new(self.path))),
            (Some(glob), Some(base)) => self.in_base(base).is_some_and(|path| glob.matches(path)),
        }
    }

    /// The path relative to the normalized folder `base`, or `None` when it is outside it,
    /// which matches none of its patterns.
    fn in_base(&mut self, base: &'p str) -> Option<&Target> {
        if self.relative.as_ref().is_none_or(|(last, _)| *last != base) {
            let absolute = self.absolute.get_or_init(|| absolute(self.path));
            let relative = absolute
                .as_deref()
                .and_then(|absolute| glob::relative(absolute, base))
                .map(Target::new);
            self.relative = Some((base, relative));
        }
        self.relative
            .as_ref()
            .and_then(|(_, relative)| relative.as_ref())
    }
}

/// `path` made absolute and normalized, or `None` for an empty path, as `std::path::absolute`
/// gives. The working directory is asked for once rather than for each path: jsonvet never
/// changes it.
fn absolute(path: &str) -> Option<String> {
    let path = Path::new(path);
    let absolute = match cwd() {
        Some(cwd) if path.is_relative() && !path.as_os_str().is_empty() => {
            std::path::absolute(cwd.join(path))
        }
        _ => std::path::absolute(path),
    };
    absolute
        .ok()
        .map(|absolute| glob::normalize(&absolute.to_string_lossy()))
}

/// The working directory, asked for once: jsonvet never changes it.
fn cwd() -> Option<&'static PathBuf> {
    working_dir().ok()
}

/// The working directory, or why it cannot be read.
fn working_dir() -> Result<&'static PathBuf, &'static str> {
    static CWD: std::sync::OnceLock<Result<PathBuf, String>> = std::sync::OnceLock::new();
    CWD.get_or_init(|| {
        std::env::current_dir().map_err(|e| messages::fill("error.working-dir", &[("error", &e)]))
    })
    .as_ref()
    .map_err(String::as_str)
}

/// The settings for each file: the nearest config file above it, or the one `--config` names,
/// with the command line's settings on top.
pub(crate) struct Resolver {
    /// The command line's settings: all there is when no config file applies.
    cli: Arc<Settings>,
    /// The settings for every file, with `--config` or `--no-config`: then nothing is searched.
    fixed: Option<Arc<Settings>>,
    /// The settings found for each folder searched so far, by its absolute path.
    found: HashMap<PathBuf, Arc<Settings>>,
    /// The working directory, asked for once rather than for each file.
    cwd: PathBuf,
    /// The nearest folder at or above the working directory with a `.git` entry, if any.
    repo: Option<PathBuf>,
    /// The settings of the user's own config file, read the first time a search finds no
    /// project config file: `None` until then.
    user: Option<Arc<Settings>>,
    /// The folder of the last file looked up, as given, and its settings. Files come a folder at
    /// a time, so this skips most lookups, which took 0.5 µs a file.
    last: Option<(PathBuf, Arc<Settings>)>,
}

impl Resolver {
    /// Read the file `--config` names, if any, so a bad one fails before any file is checked.
    pub(crate) fn new(config: &ConfigSource, cli: Settings) -> Result<Resolver, String> {
        Resolver::rooted(working_dir()?, config, cli)
    }

    /// As [`Resolver::new`], with the absolute folder `here` in place of the working directory,
    /// as the language server takes an editor's workspace folder.
    pub(crate) fn rooted(
        here: &Path,
        config: &ConfigSource,
        cli: Settings,
    ) -> Result<Resolver, String> {
        let here = lexical(here);
        let repo = here
            .ancestors()
            .find(|dir| dir.join(".git").exists())
            .map(Path::to_owned);
        let fixed = match config {
            ConfigSource::Search => None,
            ConfigSource::None => Some(Arc::new(cli.clone())),
            // The person running jsonvet named it, so like `--schema` it is not confined.
            ConfigSource::File(path) => {
                Some(Arc::new(load(path, None)?.overridden_by(cli.clone())))
            }
        };
        Ok(Resolver {
            cli: Arc::new(cli),
            fixed,
            found: HashMap::new(),
            cwd: here,
            repo,
            user: None,
            last: None,
        })
    }

    /// A language-server workspace is a search boundary even inside a larger repository.
    pub(crate) fn workspace(here: &Path) -> Result<Resolver, String> {
        let mut resolver = Self::rooted(here, &ConfigSource::Search, Settings::default())?;
        resolver.repo = None;
        Ok(resolver)
    }

    /// The project the file at `path` sits in, made canonical: where [`Resolver::for_file`]'s
    /// search for it stops. Its config file's schema paths and its own `$schema` stay in it.
    pub(crate) fn root(&self, path: &Path) -> PathBuf {
        let path = lexical(&self.cwd.join(path));
        let start = path.parent().unwrap_or(&path);
        project(start, self.last(start))
    }

    /// Where the search from the folder `start` stops if it meets no `.git` first.
    fn last<'s>(&'s self, start: &'s Path) -> Option<&'s Path> {
        if self
            .repo
            .as_ref()
            .is_some_and(|repo| start.starts_with(repo))
        {
            None
        } else if start.starts_with(&self.cwd) {
            Some(self.cwd.as_path())
        } else if start.ancestors().any(|dir| dir.join(".git").exists()) {
            None
        } else {
            Some(start)
        }
    }

    /// The settings for the file at `path`, which need not exist: those of the first
    /// `jsonvet.toml`, or `pyproject.toml` with a `[tool.jsonvet]` table, in its folder or a
    /// folder above. The search stops at the first folder with a `.git` entry, so a file above
    /// the repository is never used. With no `.git` above the file, it stops at the working
    /// directory, or for a file outside it, at the file's own folder: a file planted above the
    /// job's folder on a shared machine never applies. With no project config file, the user's
    /// own applies, if any. `-`, standard input, is searched from the working directory.
    pub(crate) fn for_file(&mut self, path: &Path) -> Result<Arc<Settings>, String> {
        if let Some(fixed) = &self.fixed {
            return Ok(Arc::clone(fixed));
        }
        let folder = path.parent().unwrap_or(path);
        if let Some((last, settings)) = &self.last
            && last.as_os_str() == folder.as_os_str()
        {
            return Ok(Arc::clone(settings));
        }
        let settings = self.search(path)?;
        self.last = Some((folder.to_owned(), Arc::clone(&settings)));
        Ok(settings)
    }

    fn search(&mut self, path: &Path) -> Result<Arc<Settings>, String> {
        let path = lexical(&self.cwd.join(path));
        let start = path.parent().unwrap_or(&path);
        let last = self.last(start);
        let mut searched = Vec::new();
        let mut settings = None;
        for dir in start.ancestors() {
            if let Some(known) = self.found.get(dir) {
                settings = Some(Arc::clone(known));
                break;
            }
            searched.push(dir);
            if let Some(config) = config_in(dir) {
                // The project goes on from here to where the search would have stopped.
                let own = load(&config, Some(&project(dir, last)))?
                    .overridden_by(Settings::clone(&self.cli));
                settings = Some(Arc::new(own));
                break;
            }
            if ends_at(dir, last) {
                break;
            }
        }
        let settings = match settings {
            Some(settings) => settings,
            None => self.user()?,
        };
        for dir in searched {
            self.found.insert(dir.to_owned(), Arc::clone(&settings));
        }
        Ok(settings)
    }

    /// The folders a search for the file at `path` visits, nearest first, ending where
    /// [`Resolver::for_file`]'s search stops.
    pub(crate) fn search_dirs(&self, path: &Path) -> Vec<PathBuf> {
        let path = lexical(&self.cwd.join(path));
        let start = path.parent().unwrap_or(&path);
        let last = self.last(start);
        let mut dirs = Vec::new();
        for dir in start.ancestors() {
            dirs.push(dir.to_owned());
            if ends_at(dir, last) {
                break;
            }
        }
        dirs
    }

    /// The settings of the user's own `jsonvet.toml`, as ruff has, with the command line's on
    /// top; the command line's alone without one.
    fn user(&mut self) -> Result<Arc<Settings>, String> {
        if let Some(user) = &self.user {
            return Ok(Arc::clone(user));
        }
        let user = match user_config() {
            Some(path) => {
                let mut own = load(&path, None)?;
                own.user = true;
                // Its globs are relative to the working directory, as in ruff: it sits in no
                // project. Normalized, as `load` does for a file's own folder.
                let cwd = glob::normalize(&self.cwd.to_string_lossy());
                for pattern in &mut own.dialects {
                    pattern.base = Some(cwd.clone());
                }
                for pattern in &mut own.rules {
                    pattern.base = Some(cwd.clone());
                }
                for pattern in &mut own.per_file_format {
                    pattern.base = Some(cwd.clone());
                }
                for (_, base) in &mut own.exclude {
                    base.clone_from(&cwd);
                }
                // Its schema paths stay relative to its own folder, where they sit.
                for entry in &mut own.schemas {
                    entry.base.clone_from(&cwd);
                }
                Arc::new(own.overridden_by(Settings::clone(&self.cli)))
            }
            None => Arc::clone(&self.cli),
        };
        self.user = Some(Arc::clone(&user));
        Ok(user)
    }
}

/// Whether a search for config files that stops at `last`, if it meets no `.git` first, stops
/// at `dir`.
fn ends_at(dir: &Path, last: Option<&Path>) -> bool {
    Some(dir) == last || dir.join(".git").exists()
}

/// The project a search from the folder `from` ends at, as [`ends_at`] says, made canonical.
fn project(from: &Path, last: Option<&Path>) -> PathBuf {
    let root = from
        .ancestors()
        .find(|dir| ends_at(dir, last))
        .unwrap_or(from);
    fs::canonicalize(root).unwrap_or_else(|_| root.to_owned())
}

/// The user's own config file, if there is one: `jsonvet/jsonvet.toml` in `%APPDATA%` on
/// Windows, and elsewhere in `$XDG_CONFIG_HOME` or `~/.config`, as ruff looks for its own on
/// Linux and macOS. A relative `XDG_CONFIG_HOME` is ignored, as the XDG spec says.
fn user_config() -> Option<PathBuf> {
    let path = user_config_path()?;
    path.is_file().then_some(path)
}

/// Where the user's own config file goes, whether or not it is there.
pub(crate) fn user_config_path() -> Option<PathBuf> {
    let absolute = |name| {
        std::env::var_os(name)
            .map(PathBuf::from)
            .filter(|dir| dir.is_absolute())
    };
    let dir = if cfg!(windows) {
        absolute("APPDATA")
    } else {
        absolute("XDG_CONFIG_HOME").or_else(|| absolute("HOME").map(|home| home.join(".config")))
    };
    Some(dir?.join("jsonvet").join("jsonvet.toml"))
}

/// `path` with `..` folded away by name, as the globs fold it, so the search climbs the folders
/// as written: from `a/../b` it goes to the parent of `b`, not to `a`. A relative path keeps the
/// `..` that lead above where it starts. `components` already drops each `.` after the first part.
pub(crate) fn lexical(path: &Path) -> PathBuf {
    let mut folded = PathBuf::new();
    for part in path.components() {
        if part != Component::ParentDir {
            folded.push(part);
            continue;
        }
        match folded.components().next_back() {
            Some(Component::Normal(_)) => {
                folded.pop();
            }
            Some(Component::RootDir | Component::Prefix(_)) => {}
            _ => folded.push(part),
        }
    }
    folded
}

/// Whether the schema at `path`, relative to the folder `base`, as a file's `$schema` or a
/// project config names it, exists: an error if it is outside `root`, the canonical project
/// root (ADR 0012). A pull request picks these paths, and an error in a schema would show what
/// the file holds.
pub(crate) fn confined(path: &str, base: &Path, root: &Path) -> Result<bool, String> {
    let outside = || messages::fill("schema.outside", &[("path", &path)]);
    let given = Path::new(path);
    // Before the path is touched: on Windows, opening `\\host\share\s.json` connects to the host.
    // A drive or UNC path is refused on every OS, so a file gets the same verdict everywhere.
    let drive = matches!(path.as_bytes(), [letter, b':', ..] if letter.is_ascii_alphabetic());
    if drive || given.has_root() || matches!(given.components().next(), Some(Component::Prefix(_)))
    {
        return Err(outside());
    }
    // `\` separates folders only on Windows. Read as `/` too, a path that leads out there,
    // such as `sub\..\..\x.json`, is refused on every OS, and `\\host\share` is absolute
    // before anything is opened.
    if path.contains('\\') && confined(&path.replace('\\', "/"), base, root).is_err() {
        return Err(outside());
    }
    let base = if base.as_os_str().is_empty() {
        Path::new(".")
    } else {
        base
    };
    let joined = base.join(given);
    // A missing file is judged by where it would be, so a path outside is refused the same
    // whether or not anything is there, and nothing outside can be probed.
    let (exists, real) = match fs::canonicalize(&joined) {
        Ok(real) => (true, Some(real)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (false, leads_to(joined)),
        Err(e) => {
            return Err(messages::fill(
                "schema.unreadable",
                &[("path", &path), ("error", &e)],
            ));
        }
    };
    match real {
        Some(real) if real.starts_with(root) => Ok(exists),
        _ => Err(outside()),
    }
}

/// Where the missing file `path` would be: its deepest part that exists, made canonical, with
/// the rest added by name. A dangling symlink on the way is followed by hand. `None` if that
/// cannot be told, such as for a loop of symlinks.
fn leads_to(mut path: PathBuf) -> Option<PathBuf> {
    // As many symlinks as Linux follows in one path.
    for _ in 0..40 {
        let (dir, rest) = path.ancestors().find_map(|dir| {
            fs::symlink_metadata(dir).ok()?;
            Some((dir, path.strip_prefix(dir).ok()?))
        })?;
        match fs::canonicalize(dir) {
            Ok(real) => return Some(lexical(&real.join(rest))),
            Err(_) => path = dir.parent()?.join(fs::read_link(dir).ok()?).join(rest),
        }
    }
    None
}

/// The config file in `dir`: its `jsonvet.toml`, or its `pyproject.toml` with a
/// `[tool.jsonvet]` table.
fn config_in(dir: &Path) -> Option<PathBuf> {
    let own = dir.join("jsonvet.toml");
    if own.is_file() {
        return Some(own);
    }
    let pyproject = dir.join("pyproject.toml");
    // One that is not a regular file is skipped, as a `jsonvet.toml` is; one that is too large
    // is left for `load` to report.
    match crate::read_small(&pyproject, crate::MAX_CONFIG_BYTES) {
        Ok(text) => has_jsonvet_table(&text).then_some(pyproject),
        Err(e) if e.kind() == std::io::ErrorKind::Other => pyproject.is_file().then_some(pyproject),
        Err(_) => None,
    }
}

/// Whether a `pyproject.toml` has a `[tool.jsonvet]` table, valid or not: `load` then reports
/// what is wrong with it, rather than the search skipping a table with a typo.
fn has_jsonvet_table(text: &str) -> bool {
    match text.parse::<Table>() {
        Ok(table) => table
            .get("tool")
            .and_then(|tool| tool.get("jsonvet"))
            .is_some(),
        Err(_) => text.contains("[tool.jsonvet"),
    }
}

/// Read a config file: a `jsonvet.toml`, or the `[tool.jsonvet]` table of a `pyproject.toml`.
/// It holds `rules`, a table of rule id to severity, and `dialects`, an array of tables with a
/// `files` glob, relative to the config file's directory, and a `dialect`; and `exclude`, an
/// array of globs, relative to the same directory, for paths a directory walk skips; and
/// `schemas`, an array of tables with a `files` glob and a `schema` path, both relative to that
/// directory; and `per-file-rules`, an array of tables with a `files` glob, relative to that
/// directory, and a severity for each rule id, which apply after `rules` wherever they are in the
/// file. Any other key is an error, so a typo is never ignored. With a `root`, the file is a
/// project's, and each schema must be inside `root` ([`confined`]).
pub(crate) fn load(path: &Path, root: Option<&Path>) -> Result<Settings, String> {
    // A key or value from the file shows escaped, so it cannot start a line of its own on stderr.
    let in_file = |e: &dyn std::fmt::Display| printable(&format!("{}: {e}", path.display()));
    let text = crate::read_small(path, crate::MAX_CONFIG_BYTES).map_err(|e| in_file(&e))?;
    // A symlink can lead to any file on the machine, such as a secret that a pull request links
    // to, so an error in one names the place only, never a key or value from it.
    let linked = fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink());
    load_str(path, &text, linked, root)
}

/// [`load`] on text already read from `path`, which `linked` says is a symlink.
pub(crate) fn load_str(
    path: &Path,
    text: &str,
    linked: bool,
    root: Option<&Path>,
) -> Result<Settings, String> {
    let in_file = |e: &dyn std::fmt::Display| printable(&format!("{}: {e}", path.display()));
    let hidden = messages::text("config.symlink");
    // The same, with the line and column of the byte offset `at` after the name.
    let at = |at: usize, e: &dyn std::fmt::Display| {
        let before = &text[..at];
        let line = before.matches('\n').count() + 1;
        let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
        let e: &dyn std::fmt::Display = if linked { &hidden } else { e };
        printable(&format!("{}:{line}:{column}: {e}", path.display()))
    };
    let table = DeTable::parse(text)
        .map_err(|e| at(e.span().map_or(0, |span| span.start), &e.message()))?;
    let table = table.get_ref();
    let file = if path.file_name().is_some_and(|n| n == "pyproject.toml") {
        match table
            .get("tool")
            .and_then(|tool| tool.get_ref().get("jsonvet"))
        {
            Some(file) => match file.get_ref() {
                DeValue::Table(table) => table,
                _ => {
                    return Err(at(
                        file.span().start,
                        &messages::text("config.tool-not-table"),
                    ));
                }
            },
            None => return Err(in_file(&messages::text("config.no-tool-table"))),
        }
    } else {
        table
    };
    let absolute = std::path::absolute(path).map_err(|e| in_file(&e))?;
    let folder = absolute.parent();
    let base = folder.map(|dir| glob::normalize(&dir.to_string_lossy()));
    let mut settings = Settings::default();
    let mut per_file = Vec::new();
    for (key, value) in file {
        let here = value.span().start;
        match (key.get_ref().as_ref(), value.get_ref()) {
            ("rules", DeValue::Table(rules)) => {
                let rules = severities("rules", rules.iter(), &at)?;
                settings.rules.push(RulePattern::every_file(rules));
            }
            ("per-file-rules", DeValue::Array(entries)) => {
                for entry in entries {
                    per_file.push(rule_entry(entry, base.clone(), &at)?);
                }
            }
            ("per-file-format", DeValue::Array(entries)) => {
                for entry in entries {
                    let pattern = format_entry(entry, base.clone(), &at)?;
                    settings.per_file_format.push(pattern);
                }
            }
            ("dialects", DeValue::Array(entries)) => {
                for entry in entries {
                    let mut pattern = dialect_entry(entry).map_err(|(offset, e)| at(offset, &e))?;
                    pattern.base.clone_from(&base);
                    settings.dialects.push(pattern);
                }
            }
            ("exclude", DeValue::Array(patterns)) => {
                for pattern in patterns {
                    let text = pattern.get_ref().as_str().ok_or_else(|| {
                        at(pattern.span().start, &messages::text("config.exclude-type"))
                    })?;
                    // Without a base there is nothing for the pattern to be relative to.
                    if let Some(base) = &base {
                        settings.exclude.push((Glob::new(text), base.clone()));
                    }
                }
            }
            ("schemas", DeValue::Array(entries)) => {
                for entry in entries {
                    if let Some(mut pattern) =
                        schema_entry(entry, folder, root).map_err(|(offset, e)| at(offset, &e))?
                        && let Some(base) = &base
                    {
                        pattern.base.clone_from(base);
                        settings.schemas.push(pattern);
                    }
                }
            }
            ("format", DeValue::Table(table)) => settings.format = format_table(table.iter(), &at)?,
            (
                key @ ("exclude" | "schemas" | "rules" | "per-file-rules" | "per-file-format"
                | "dialects" | "format"),
                _,
            ) => return Err(at(here, &messages::text(&format!("config.{key}-type")))),
            (key_text, _) => {
                let hint = messages::did_you_mean(key_text, KEYS);
                return Err(at(
                    key.span().start,
                    &messages::fill("config.unknown-key", &[("key", &key_text), ("hint", &hint)]),
                ));
            }
        }
    }
    settings.rules.extend(per_file);
    Ok(settings)
}

/// The keys a config file may hold.
pub(crate) const KEYS: [&str; 7] = [
    "rules",
    "per-file-rules",
    "per-file-format",
    "dialects",
    "exclude",
    "schemas",
    "format",
];

/// A severity for each rule id, from the `rules` table or a `per-file-rules` entry, which
/// `table` names in errors.
fn severities<'t>(
    table: &str,
    rules: impl Iterator<Item = (&'t Spanned<Cow<'t, str>>, &'t Spanned<DeValue<'t>>)>,
    at: &dyn Fn(usize, &dyn std::fmt::Display) -> String,
) -> Result<Vec<(Rule, Severity)>, String> {
    let mut found = Vec::new();
    for (id, severity) in rules {
        let rule = parse_rule(id.get_ref()).map_err(|e| at(id.span().start, &e))?;
        let severity_at = severity.span().start;
        let severity = severity.get_ref().as_str().ok_or_else(|| {
            at(
                severity_at,
                &messages::fill(
                    "config.rule-not-string",
                    &[("table", &table), ("id", id.get_ref())],
                ),
            )
        })?;
        let severity = parse_severity(severity).map_err(|e| at(severity_at, &e))?;
        found.push((rule, severity));
    }
    Ok(found)
}

/// One `per-file-rules` entry: a table with a `files` string, relative to the folder `base`, and
/// a severity for each rule id.
fn rule_entry(
    entry: &Spanned<DeValue<'_>>,
    base: Option<String>,
    at: &dyn Fn(usize, &dyn std::fmt::Display) -> String,
) -> Result<RulePattern, String> {
    let array = "per-file-rules";
    let DeValue::Table(table) = entry.get_ref() else {
        let e = messages::fill("config.entry-type", &[("array", &array)]);
        return Err(at(entry.span().start, &e));
    };
    // A key that is no rule id but close to `files` is a typo for it, not an unknown rule.
    if let Some(key) = table
        .keys()
        .find(|key| key.get_ref().parse::<Rule>().is_err() && key.get_ref() != "files")
        && let hint = messages::did_you_mean(key.get_ref(), ["files"])
        && !hint.is_empty()
    {
        let e = messages::fill(
            "config.rule-entry-unknown-key",
            &[("key", key.get_ref()), ("hint", &hint)],
        );
        return Err(at(key.span().start, &e));
    }
    let files = table.get("files");
    let Some(files) = files.and_then(|files| files.get_ref().as_str()) else {
        let offset = files.map_or(entry.span().start, |files| files.span().start);
        let e = messages::fill(
            "config.entry-needs",
            &[("array", &array), ("key", &"files")],
        );
        return Err(at(offset, &e));
    };
    let rules = table.iter().filter(|(key, _)| key.get_ref() != "files");
    Ok(RulePattern {
        files: Some(Glob::new(files)),
        rules: severities(array, rules, at)?,
        base,
    })
}

/// One `per-file-format` entry with a required `files` glob and optional formatting keys.
fn format_entry(
    entry: &Spanned<DeValue<'_>>,
    base: Option<String>,
    at: &dyn Fn(usize, &dyn std::fmt::Display) -> String,
) -> Result<FormatPattern, String> {
    let array = "per-file-format";
    let DeValue::Table(table) = entry.get_ref() else {
        return Err(at(
            entry.span().start,
            &messages::fill("config.entry-type", &[("array", &array)]),
        ));
    };
    let files = table.get("files");
    let Some(pattern) = files.and_then(|value| value.get_ref().as_str()) else {
        return Err(at(
            files.map_or(entry.span().start, |value| value.span().start),
            &messages::fill(
                "config.entry-needs",
                &[("array", &array), ("key", &"files")],
            ),
        ));
    };
    Ok(FormatPattern {
        files: Glob::new(pattern),
        base,
        format: format_table(table.iter().filter(|(key, _)| key.get_ref() != "files"), at)?,
    })
}

/// Formatting keys shared by `[format]` and `per-file-format` entries.
fn format_table<'t>(
    table: impl Iterator<Item = (&'t Spanned<Cow<'t, str>>, &'t Spanned<DeValue<'t>>)>,
    at: &dyn Fn(usize, &dyn std::fmt::Display) -> String,
) -> Result<FormatSettings, String> {
    let mut format = FormatSettings::default();
    for (key, value) in table {
        let here = value.span().start;
        let wrong = |id: &str| at(here, &messages::text(id));
        match (key.get_ref().as_ref(), value.get_ref()) {
            ("indent", DeValue::String(s)) if s == "tab" => format.indent = Some(Indent::Tab),
            ("indent", DeValue::Integer(n)) => {
                let spaces = n.as_str().parse::<usize>().ok().filter(|n| *n <= 16);
                format.indent = Some(Indent::Spaces(
                    spaces.ok_or_else(|| wrong("config.format-indent"))?,
                ));
            }
            ("width", DeValue::Integer(n)) => {
                let width = n.as_str().parse::<usize>().ok().filter(|n| *n >= 1);
                format.width = Some(width.ok_or_else(|| wrong("config.format-width"))?);
            }
            ("normalize-json5", DeValue::Boolean(on)) => format.normalize_json5 = Some(*on),
            ("bracket-spacing", DeValue::Boolean(on)) => format.bracket_spacing = Some(*on),
            ("bracket-spacing", _) => return Err(wrong("config.format-bracket-spacing")),
            ("fill-numbers", DeValue::Boolean(on)) => format.fill_numbers = Some(*on),
            ("fill-numbers", _) => return Err(wrong("config.format-fill-numbers")),
            ("indent", _) => return Err(wrong("config.format-indent")),
            ("width", _) => return Err(wrong("config.format-width")),
            ("normalize-json5", _) => return Err(wrong("config.format-normalize")),
            (name, _) => {
                let hint = messages::did_you_mean(
                    name,
                    [
                        "indent",
                        "width",
                        "normalize-json5",
                        "bracket-spacing",
                        "fill-numbers",
                    ],
                );
                return Err(at(
                    key.span().start,
                    &messages::fill(
                        "config.format-unknown-key",
                        &[("key", &name), ("hint", &hint)],
                    ),
                ));
            }
        }
    }
    Ok(format)
}

/// One `dialects` entry: a table with exactly a `files` string and a `dialect` string. An error
/// comes with the offset it is about.
fn dialect_entry(entry: &Spanned<DeValue<'_>>) -> Result<DialectPattern, (usize, String)> {
    let [(_, files), (dialect_at, dialect)] =
        entry_strings(entry, "dialects", ["files", "dialect"])?;
    Ok(DialectPattern {
        files: Some(Glob::new(files)),
        dialect: parse_dialect(dialect).map_err(|e| (dialect_at, e))?,
        base: None,
    })
}

/// One entry of `schemas`, with no base yet, for a config file in `folder`: `None` without a
/// folder, which nothing is relative to. With a `root`, the schema must be inside it.
fn schema_entry(
    entry: &Spanned<DeValue<'_>>,
    folder: Option<&Path>,
    root: Option<&Path>,
) -> Result<Option<SchemaPattern>, (usize, String)> {
    let [(_, files), (schema_at, schema)] = entry_strings(entry, "schemas", ["files", "schema"])?;
    let Some(folder) = folder else {
        return Ok(None);
    };
    // A missing schema is reported when it is read, which `--schema` skips.
    if let Some(root) = root {
        confined(schema, folder, root).map_err(|e| (schema_at, e))?;
    }
    let folder = cwd()
        .and_then(|cwd| folder.strip_prefix(cwd).ok())
        .unwrap_or(folder);
    Ok(Some(SchemaPattern {
        files: Glob::new(files),
        schema: folder.join(schema),
        base: String::new(),
        confined: root.is_some(),
    }))
}

/// The two strings of an entry in the array `array`, a table with exactly the keys `keys`, each
/// with its offset. An error comes with the offset it is about.
fn entry_strings<'e>(
    entry: &'e Spanned<DeValue<'_>>,
    array: &str,
    keys: [&str; 2],
) -> Result<[(usize, &'e str); 2], (usize, String)> {
    let start = entry.span().start;
    let DeValue::Table(table) = entry.get_ref() else {
        return Err((
            start,
            messages::fill("config.entry-type", &[("array", &array)]),
        ));
    };
    if let Some(key) = table.keys().find(|k| !keys.contains(&k.get_ref().as_ref())) {
        let name = key.get_ref();
        let hint = messages::did_you_mean(name, keys);
        return Err((
            key.span().start,
            messages::fill(
                "config.entry-unknown-key",
                &[
                    ("key", name),
                    ("hint", &hint),
                    ("array", &array),
                    ("first", &keys[0]),
                    ("second", &keys[1]),
                ],
            ),
        ));
    }
    let string = |key: &str| {
        let value = table.get(key);
        value
            .and_then(|v| v.get_ref().as_str().map(|s| (v.span().start, s)))
            .ok_or_else(|| {
                let offset = value.map_or(start, |v| v.span().start);
                (
                    offset,
                    messages::fill("config.entry-needs", &[("array", &array), ("key", &key)]),
                )
            })
    };
    Ok([string(keys[0])?, string(keys[1])?])
}

#[cfg(test)]
mod tests {
    use super::{Glob, Resolver, Settings, absolute, confined, lexical};
    use crate::args::ConfigSource;

    #[test]
    fn lexical_folds_dot_dot_by_name_and_keeps_it_above_a_relative_start() {
        let sep = std::path::MAIN_SEPARATOR;
        for (path, folded) in [
            ("a/../s.json", "s.json".to_owned()),
            ("a/b/../../c/s.json", format!("c{sep}s.json")),
            ("../a/../s.json", format!("..{sep}s.json")),
            ("./a/../../s.json", format!(".{sep}..{sep}s.json")),
        ] {
            assert_eq!(lexical(path.as_ref()).to_string_lossy(), folded, "{path}");
        }
        #[cfg(unix)]
        assert_eq!(
            lexical("/../a/../s.json".as_ref()).to_string_lossy(),
            "/s.json"
        );
    }

    #[test]
    fn a_schema_path_with_a_root_drive_or_prefix_is_refused_before_it_is_opened() {
        let base = std::path::Path::new(".");
        let root = std::fs::canonicalize(base).expect("the working directory");
        let root = root.as_path();
        // Opening a path through a file fails with an error of its own, not "not found", so this
        // one shows whether the path was opened.
        let through_a_file = root.join("Cargo.toml").join("s.json");
        let through_a_file = through_a_file.to_str().expect("a UTF-8 path");
        let mut paths = vec![
            "/etc/passwd",
            through_a_file,
            "//host/share/s.json",
            "C:\\s.json",
            "C:/s.json",
            "c:s.json",
            "\\\\host\\share\\s.json",
        ];
        if cfg!(windows) {
            paths.push("\\s.json");
        }
        for path in paths {
            let refused = confined(path, base, root).expect_err(path);
            assert!(refused.contains("outside the project"), "{path}: {refused}");
        }
        assert_eq!(confined("missing-schema.json", base, root), Ok(false));
    }

    #[test]
    fn each_pattern_matches_relative_to_its_own_base() {
        // Bases from the working directory, so they are absolute on Windows too.
        let (r1, r2) = (
            absolute("r1").expect("a base"),
            absolute("r2").expect("a base"),
        );
        let settings = Settings {
            exclude: vec![
                (Glob::new("a.json"), r1.clone()),
                (Glob::new("b.json"), r2.clone()),
            ],
            ..Settings::default()
        };
        let path = |base: &str, name: &str| std::path::PathBuf::from(format!("{base}/{name}"));
        assert!(settings.excluded(&path(&r1, "a.json")));
        assert!(settings.excluded(&path(&r2, "b.json")));
        assert!(!settings.excluded(&path(&r1, "b.json")));
    }

    #[test]
    fn paths_are_made_absolute_from_the_working_directory() {
        let cwd = std::env::current_dir().expect("a working directory");
        let cwd = cwd.to_string_lossy().replace('\\', "/");
        assert_eq!(absolute("a/./b.json"), Some(format!("{cwd}/a/b.json")));
        assert_eq!(absolute(""), None);
        #[cfg(unix)]
        assert_eq!(absolute("/x/../y.json").as_deref(), Some("/y.json"));
    }

    #[test]
    fn root_is_where_the_search_for_a_config_file_ends() {
        // A repository whose config file, a folder down, names a schema at the top.
        let repo = std::env::temp_dir().join(format!("jsonvet-root-{}", std::process::id()));
        std::fs::create_dir_all(repo.join(".git")).expect("a repository");
        std::fs::create_dir_all(repo.join("a/b")).expect("folders");
        let config = "schemas = [{ files = \"*.json\", schema = \"../s.json\" }]\n";
        std::fs::write(repo.join("a/jsonvet.toml"), config).expect("write");
        let file = repo.join("a/b/f.json");
        let mut resolver =
            Resolver::new(&ConfigSource::Search, Settings::default()).expect("a resolver");
        let settings = resolver
            .for_file(&file)
            .expect("the schema is inside the project");
        assert_eq!(settings.schemas.len(), 1);
        let root = std::fs::canonicalize(&repo).expect("the repository");
        assert_eq!(resolver.root(&file), root);
        let _ = std::fs::remove_dir_all(&repo);
    }
}