jsonvet-cli 3.1.1

The jsonvet command: checks JSON, I-JSON, JSONC, JWCC (HuJSON), JSON5 and JSON Lines files, with JSON Schema checks and SARIF output.
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
//! 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::collections::HashMap;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use jsonvet::{Config, Dialect, 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::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,
        })
    }
}

fn parse_dialect(name: &str) -> Result<Option<Dialect>, String> {
    if name == "auto" {
        return Ok(None);
    }
    name.parse()
        .map(Some)
        .map_err(|e: jsonvet::UnknownDialect| format!("{e}, or auto"))
}

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(format!(
            "unknown severity `{name}`{}; expected error, warning or ignore",
            jsonvet::did_you_mean(name, ["error", "warning", "warn", "ignore", "off"])
        )),
    }
}

/// A rule id from the command line or a settings file. `schema` is no [`Rule`]: its errors
/// cannot be turned down, so it gets its own message rather than "unknown rule".
pub(crate) fn parse_rule(id: &str) -> Result<Rule, String> {
    if id == crate::sarif::SCHEMA {
        return Err("the `schema` rule is always an error and cannot be set".to_owned());
    }
    id.parse().map_err(|e| format!("{e}"))
}

/// 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>,
    pub(crate) rules: Vec<(Rule, Severity)>,
    /// 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)>,
}

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
    }

    /// 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 given = std::cell::OnceCell::new();
        let mut located = Located::new(path);
        let dialect = self
            .dialects
            .iter()
            .rev()
            .find(|rule| match (&rule.files, &rule.base) {
                (None, _) => true,
                (Some(glob), None) => glob.matches(given.get_or_init(|| Target::new(path))),
                (Some(glob), Some(base)) => {
                    located.in_base(base).is_some_and(|path| glob.matches(path))
                }
            })
            .and_then(|rule| rule.dialect)
            .unwrap_or_else(auto);
        self.config(dialect)
    }

    /// The checking config for `dialect`, with the rule severities set.
    pub(crate) fn config(&self, dialect: Dialect) -> Config {
        self.rules
            .iter()
            .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 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,
            absolute: std::cell::OnceCell::new(),
            relative: None,
        }
    }

    /// 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> {
    static CWD: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
    let path = Path::new(path);
    let absolute = match CWD.get_or_init(|| std::env::current_dir().ok()) {
        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 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. Empty unless searching.
    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> {
        let (fixed, cwd) = match config {
            ConfigSource::Search => (
                None,
                std::env::current_dir()
                    .map_err(|e| format!("cannot read the working directory: {e}"))?,
            ),
            ConfigSource::None => (Some(Arc::new(cli.clone())), PathBuf::new()),
            ConfigSource::File(path) => (
                Some(Arc::new(load(path)?.overridden_by(cli.clone()))),
                PathBuf::new(),
            ),
        };
        let repo = cwd
            .ancestors()
            .find(|dir| dir.join(".git").exists())
            .map(Path::to_owned);
        Ok(Resolver {
            cli: Arc::new(cli),
            fixed,
            found: HashMap::new(),
            cwd,
            repo,
            user: None,
            last: None,
        })
    }

    /// 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);
        // Where the search stops if it meets no `.git` first.
        let last = 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)
        };
        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) {
                let own = load(&config)?.overridden_by(Settings::clone(&self.cli));
                settings = Some(Arc::new(own));
                break;
            }
            if Some(dir) == last || dir.join(".git").exists() {
                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 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)?;
                // 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 (_, base) in &mut own.exclude {
                    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)
    }
}

/// 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 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")))
    };
    let path = dir?.join("jsonvet").join("jsonvet.toml");
    path.is_file().then_some(path)
}

/// The absolute `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`. `components`
/// already drops each `.` after the first part.
fn lexical(path: &Path) -> PathBuf {
    let mut folded = PathBuf::new();
    for part in path.components() {
        if part == Component::ParentDir {
            folded.pop();
        } else {
            folded.push(part);
        }
    }
    folded
}

/// 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. Any other
/// key is an error, so a typo is never ignored.
pub(crate) fn load(path: &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());
    let hidden = "invalid setting, not shown because the file is a 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, &"`tool.jsonvet` must be a table")),
            },
            None => return Err(in_file(&"no [tool.jsonvet] table")),
        }
    } else {
        table
    };
    let base = std::path::absolute(path).map_err(|e| in_file(&e))?;
    let base = base
        .parent()
        .map(|dir| glob::normalize(&dir.to_string_lossy()));
    let mut settings = Settings::default();
    for (key, value) in file {
        let here = value.span().start;
        match (key.get_ref().as_ref(), value.get_ref()) {
            ("rules", DeValue::Table(rules)) => {
                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,
                            &format!("`rules.{}` must be a string", id.get_ref()),
                        )
                    })?;
                    let severity = parse_severity(severity).map_err(|e| at(severity_at, &e))?;
                    settings.rules.push((rule, severity));
                }
            }
            ("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,
                            &"`exclude` must be an array of strings",
                        )
                    })?;
                    // 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()));
                    }
                }
            }
            ("exclude", _) => return Err(at(here, &"`exclude` must be an array of strings")),
            ("rules", _) => return Err(at(here, &"`rules` must be a table")),
            ("dialects", _) => return Err(at(here, &"`dialects` must be an array of tables")),
            (key_text, _) => {
                let hint = jsonvet::did_you_mean(key_text, ["rules", "dialects", "exclude"]);
                return Err(at(
                    key.span().start,
                    &format!("unknown key `{key_text}`{hint}; expected rules, dialects or exclude"),
                ));
            }
        }
    }
    Ok(settings)
}

/// 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 start = entry.span().start;
    let DeValue::Table(table) = entry.get_ref() else {
        return Err((start, "each `dialects` entry must be a table".to_owned()));
    };
    if let Some(key) = table
        .keys()
        .find(|k| !matches!(k.get_ref().as_ref(), "files" | "dialect"))
    {
        let name = key.get_ref();
        let hint = jsonvet::did_you_mean(name, ["files", "dialect"]);
        return Err((
            key.span().start,
            format!("unknown key `{name}`{hint} in a `dialects` entry; expected files and dialect"),
        ));
    }
    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,
                    format!("each `dialects` entry needs a `{key}` string"),
                )
            })
    };
    let (_, files) = string("files")?;
    let (dialect_at, dialect) = string("dialect")?;
    Ok(DialectPattern {
        files: Some(Glob::new(files)),
        dialect: parse_dialect(dialect).map_err(|e| (dialect_at, e))?,
        base: None,
    })
}

#[cfg(test)]
mod tests {
    use super::{Glob, Settings, absolute};

    #[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"));
    }
}