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
//! Which schema each file is checked against, and whether its errors may quote it: the one
//! `--schema` gives, else the one a config file names, else the one a file's own `$schema`
//! names (ADR 0012).

use std::cell::Cell;
use std::collections::{BTreeSet, HashMap};
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use jsonvet::{Dialect, Event, EventKind, Report, Rule};

use memchr::memmem;

use super::Schema;
use super::limits::{PATTERN_BYTES, RUN_PATTERNS};
use crate::settings::{self, Settings};
use crate::{check, messages, output};

/// Whether the file of `job`, shown as `name`, with `text`, is checked against a schema: the one
/// given, or one its own `$schema` may name.
pub(crate) fn with_schema(((settings, schema), _): &Job, name: &OsStr, text: &str) -> bool {
    schema.is_some()
        || may_name_a_path(text)
            && settings.config_for(&name.to_string_lossy()).dialect() != Dialect::JsonLines
}

/// A file to check, with its settings and the schema it is checked against, if any.
pub(crate) type Job = ((Arc<Settings>, Option<Arc<Schema>>), OsString);

/// Each file, shown by the name `shown` gives it, with its settings and schema: the one at
/// `given`, from `--schema`, or else the one its config file names, through `load`.
pub(crate) fn jobs(
    files: Vec<OsString>,
    shown: &impl Fn(&OsStr) -> OsString,
    settings_for: &impl Fn(&Path) -> Result<Arc<Settings>, String>,
    given: Option<&Path>,
    load: &impl Fn(&Path, bool) -> Loaded,
) -> Result<Vec<Job>, String> {
    // `--schema` is the user's own choice, so it may be anywhere and its errors quote it.
    let given = given
        .map(|path| load(path, false))
        .transpose()
        .map_err(|e| output::printable(&e))?;
    // Settings are shared between files of a folder, so each set is walked once.
    let mut walked = std::collections::HashSet::new();
    files
        .into_iter()
        .map(|file| {
            let name = shown(&file);
            let settings = settings_for(Path::new(&name))?;
            // A schema the config names is read even if no file matches its glob, so a missing
            // one is never passed over. `--schema` replaces them all.
            if given.is_none() && walked.insert(Arc::as_ptr(&settings)) {
                for entry in &settings.schemas {
                    load(&entry.schema, entry.confined).map_err(|e| output::printable(&e))?;
                }
            }
            let schema = match &given {
                Some(schema) => Some(Arc::clone(schema)),
                None => settings
                    .schema_for(&name.to_string_lossy())
                    .map(|entry| load(&entry.schema, entry.confined))
                    .transpose()
                    .map_err(|e| output::printable(&e))?,
            };
            Ok(((settings, schema), file))
        })
        .collect()
}

/// A schema, or why it cannot be used.
pub(crate) type Loaded = Result<Arc<Schema>, String>;

/// The schemas `--schema`, config files and `$schema` keys name, each read once, by canonical
/// path and whether its errors are quiet.
#[derive(Default)]
pub(crate) struct Schemas {
    loaded: Mutex<HashMap<(SchemaKey, bool), Loaded>>,
    /// The regexes of the schemas read, as [`RUN_PATTERNS`] counts them, also of those that
    /// failed after they were counted. Changed only while `loaded` is held.
    patterns: AtomicUsize,
    /// Why the run stops: a schema took it past [`RUN_PATTERNS`].
    over: OnceLock<String>,
    /// What each `$schema` path, from each folder of the files that hold one, leads to.
    own: Mutex<HashMap<(PathBuf, String), Own>>,
    /// The `$schema` paths that lead to no file, each joined to the folder of a file naming it
    /// and folded by name, so `a/../s.json` and `b/../s.json` are one.
    missing: Mutex<BTreeSet<PathBuf>>,
}

/// The schema a file's own `$schema` names: none if it is not there, or why it cannot be used.
type Own = Result<Option<Arc<Schema>>, String>;

#[derive(Eq, Hash, PartialEq)]
enum SchemaKey {
    Local(PathBuf),
    Catalog(String),
}

impl Schemas {
    /// The schema at `path`, from `load` the first time it is asked for with `quiet`. Every
    /// spelling of a path, such as `x/../s.json` for `s.json`, reads it once: else a file
    /// could name one large schema many ways and have it read for each. `load` hands the number
    /// of regexes in the schema to its argument before it compiles any: one that takes the run
    /// past [`RUN_PATTERNS`] is an error, and so is every schema after it.
    pub(crate) fn get(
        &self,
        path: &Path,
        quiet: bool,
        load: impl FnOnce(&dyn Fn(usize) -> Result<(), String>) -> Result<Schema, String>,
    ) -> Loaded {
        self.get_named(path, quiet, false, load)
    }

    /// Catalog URLs occupy a separate namespace from paths that spell the same text.
    pub(crate) fn get_catalog(
        &self,
        url: &str,
        load: impl FnOnce(&dyn Fn(usize) -> Result<(), String>) -> Result<Schema, String>,
    ) -> Loaded {
        self.get_named(Path::new(url), false, true, load)
    }

    fn get_named(
        &self,
        path: &Path,
        quiet: bool,
        catalog: bool,
        load: impl FnOnce(&dyn Fn(usize) -> Result<(), String>) -> Result<Schema, String>,
    ) -> Loaded {
        let key = if catalog {
            SchemaKey::Catalog(path.to_string_lossy().into_owned())
        } else {
            SchemaKey::Local(
                std::fs::canonicalize(path)
                    .or_else(|_| std::path::absolute(path))
                    .unwrap_or_else(|_| path.to_owned()),
            )
        };
        // A poisoned lock still holds every schema read.
        let mut loaded = self
            .loaded
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        loaded
            .entry((key, quiet))
            .or_insert_with(|| {
                // A catalog load can parse a cached, a fetched and a stale body in turn: each
                // count replaces the last, so only the body it keeps stays counted.
                let counted = Cell::new(0);
                let admit = |count: usize| {
                    self.over()?;
                    let patterns = self.patterns.load(Ordering::Relaxed) - counted.get() + count;
                    if patterns > RUN_PATTERNS {
                        let error = messages::fill(
                            "schema.run-patterns",
                            &[
                                ("path", &path.display()),
                                ("limit", &RUN_PATTERNS),
                                ("mb", &(PATTERN_BYTES >> 20)),
                            ],
                        );
                        return Err(self.over.get_or_init(|| error).clone());
                    }
                    self.patterns.store(patterns, Ordering::Relaxed);
                    counted.set(count);
                    Ok(())
                };
                load(&admit).map(Arc::new)
            })
            .clone()
    }

    /// Why the run must stop, once a schema read took it past [`RUN_PATTERNS`]: a usage error,
    /// whichever file named the schema, so the verdict does not depend on which thread read it
    /// first.
    pub(crate) fn over(&self) -> Result<(), String> {
        self.over.get().map_or(Ok(()), |error| Err(error.clone()))
    }

    /// What the `$schema` `path` in a file in `folder` leads to, from `find` the first time it
    /// is asked for from that folder. Where a path leads, and whether it stays in the project,
    /// depend on the folder and the path alone, so the answer holds for every file there, and
    /// thousands of files that name one schema look it up once.
    fn own(&self, folder: &Path, path: &str, find: impl FnOnce() -> Own) -> Own {
        let key = (folder.to_owned(), path.to_owned());
        // A poisoned lock still holds every answer, and none is held while `find` runs: it
        // looks at the file system. Two threads may then both run it, with the same answer.
        let known = self
            .own
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(own) = known.get(&key) {
            return own.clone();
        }
        drop(known);
        let own = find();
        self.own
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(key, own.clone());
        own
    }

    /// Observe local schema dependencies that passed confinement but do not exist yet.
    pub(crate) fn observe_missing(&self, observe: &impl Fn(&Path)) {
        let missing = self
            .missing
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        for path in missing.iter() {
            observe(path);
        }
    }

    /// One runtime note for each missing `$schema` path, sorted by path. These do not fail a run.
    pub(crate) fn missing_notes(&self) -> Vec<String> {
        let missing = self
            .missing
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        missing
            .iter()
            .map(|path| messages::fill("schema.missing", &[("path", &path.to_string_lossy())]))
            .collect()
    }
}

/// The local schema path a file's `$schema` names, and the offset of its value, found as the
/// file's events come in: a string member of the top-level object that is no URL. Document URLs
/// are never followed. It keeps no event, so the file's memory stays its text.
#[derive(Default)]
struct OwnSchema {
    /// How many levels under the top-level object the events are, once it opens.
    depth: Option<usize>,
    /// Whether the next event is the value of the top-level `$schema`.
    value: bool,
    /// Whether the first top-level `$schema`, or the end of the object, has been seen.
    done: bool,
    /// What that `$schema` names.
    found: Option<(usize, String)>,
}

/// Whether a document declares a local schema, which takes precedence over the catalog.
pub(crate) fn names_local_schema(name: &str, text: &str, settings: &Settings) -> bool {
    let config = settings.config_for(name);
    if config.dialect() == Dialect::JsonLines || !may_name_a_path(text) {
        return false;
    }
    let mut own = OwnSchema::default();
    jsonvet::parse_with(text, &config, &mut |event| own.event(&event));
    own.found.is_some()
}

impl OwnSchema {
    fn event(&mut self, event: &Event<'_>) {
        if self.done {
            return;
        }
        if self.value {
            self.done = true;
            if let EventKind::String(path) = &event.kind {
                // A fragment points into the schema, as in `s.json#`; the file is the same.
                let path = path.split_once('#').map_or(&**path, |(path, _)| path);
                self.found =
                    (!path.is_empty() && !is_url(path)).then(|| (event.offset, path.to_owned()));
            }
            return;
        }
        let Some(depth) = &mut self.depth else {
            self.depth = Some(0);
            self.done = event.kind != EventKind::ObjectStart;
            return;
        };
        match &event.kind {
            EventKind::ObjectStart | EventKind::ArrayStart => *depth += 1,
            EventKind::End if *depth == 0 => self.done = true,
            EventKind::End => *depth -= 1,
            EventKind::Key(key) if *depth == 0 && **key == *b"$schema" => self.value = true,
            _ => {}
        }
    }
}

/// Whether some `$schema` in `text` may hold a path rather than a URL, so the text is worth
/// parsing into events: they take 10 times its memory and 2.5 times as long as a plain check,
/// and most `$schema` values are URLs. Anything but `$schema`, a quote, `:` and a URL is a maybe,
/// and so is any escape that can spell the key: `\u`, JSON5's `\x`, and a backslash that
/// continues a JSON5 string over a line break.
fn may_name_a_path(text: &str) -> bool {
    let bytes = text.as_bytes();
    memmem::find_iter(bytes, b"$schema").any(|at| {
        let rest = text[at + "$schema".len()..].trim_start_matches(['"', '\'']);
        rest.trim_start()
            .strip_prefix(':')
            .is_none_or(|value| !is_url(value.trim_start().trim_start_matches(['"', '\''])))
    }) || memchr::memchr_iter(b'\\', bytes).any(|at| {
        let next = &bytes[at + 1..];
        next.starts_with(b"u")
            || next.starts_with(b"x")
            || next.starts_with(b"\n")
            || next.starts_with(b"\r")
            || next.starts_with("\u{2028}".as_bytes())
            || next.starts_with("\u{2029}".as_bytes())
    })
}

/// Whether `text` starts with a URI scheme: a letter, then letters, digits, `+`, `-` or `.`,
/// then `:`. One letter is a Windows drive, as in `C:\schemas\a.json`, so a scheme takes two.
fn is_url(text: &str) -> bool {
    text.split_once(':').is_some_and(|(scheme, _)| {
        scheme.len() > 1
            && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
            && scheme
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    })
}

/// Check a file's text with no schema given for it, which [`with_schema`] says may name one in its
/// own `$schema`, against that schema if any, relative to the file's folder, through `load`. The schema must be inside the file's own
/// project, as `root` gives it, and its errors quote nothing from it (ADR 0012). One that does not
/// exist is skipped, and noted by [`Schemas::missing_notes`]; one outside the project or that
/// cannot be used is an error at the `$schema` value. JSON Lines holds many documents, so no one
/// `$schema` applies.
pub(crate) fn check_own_schema<'t>(
    name: &str,
    text: &'t str,
    settings: &Settings,
    schemas: &Schemas,
    root: &impl Fn(&Path) -> PathBuf,
    load: &impl Fn(&Path, bool) -> Loaded,
    parts: usize,
) -> (Report<'t>, Vec<(usize, String, bool)>) {
    let config = settings.config_for(name);
    // With the file's own depth limit, so a file with no usable `$schema` gets the report a
    // plain check gives, without a second parse.
    let mut own = OwnSchema::default();
    let report = jsonvet::parse_with(text, &config, &mut |event| own.event(&event));
    let syntax_error = report.problems().iter().any(|p| p.rule() == Rule::Syntax);
    let Some((offset, path)) = own.found.filter(|_| !syntax_error) else {
        return (report, Vec::new());
    };
    let folder = Path::new(name).parent().unwrap_or(Path::new(""));
    let own = schemas.own(folder, &path, || {
        // A schema that is not there is skipped like a URL: tools name one under
        // `node_modules` that a CI run may not have installed.
        if !settings::confined(&path, folder, &root(Path::new(name)))? {
            schemas
                .missing
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .insert(settings::lexical(&folder.join(&path)));
            return Ok(None);
        }
        load(&folder.join(&path), true).map(Some)
    });
    match own {
        Ok(None) => (report, Vec::new()),
        // As with `--schema`.
        Ok(Some(schema)) => check(name, text, settings, Some(&schema), parts, None),
        Err(error) => (report, vec![(offset, output::printable(&error), false)]),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::{Schema, Schemas, Settings};

    #[test]
    fn every_spelling_of_a_schema_path_reads_it_once() {
        let dir = std::env::temp_dir().join(format!("jsonvet-spellings-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("x")).expect("a temporary directory");
        std::fs::write(dir.join("s.json"), "{}").expect("written");
        let schemas = Schemas::default();
        let reads = AtomicUsize::new(0);
        let read = |admit: &dyn Fn(usize) -> Result<(), String>| {
            reads.fetch_add(1, Ordering::Relaxed);
            Schema::load(&dir.join("s.json"), &Settings::default(), false, admit)
        };
        for path in ["s.json", "x/../s.json", "x/../x/../s.json", "./s.json"] {
            assert!(schemas.get(&dir.join(path), true, read).is_ok(), "{path}");
        }
        assert_eq!(reads.load(Ordering::Relaxed), 1);
        // Quiet and not are two reads, since their errors differ.
        assert!(schemas.get(&dir.join("s.json"), false, read).is_ok());
        assert_eq!(reads.load(Ordering::Relaxed), 2);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn only_the_last_attempt_of_one_load_counts_its_patterns() {
        // A catalog load may parse a cached, a fetched and a stale body; only the one it keeps
        // stays counted.
        let schemas = Schemas::default();
        let loaded = schemas.get_catalog("https://json.schemastore.org/x.json", |admit| {
            admit(600)?;
            admit(600)?;
            Schema::load_text(
                std::path::Path::new("x.json"),
                "{}",
                &Settings::default(),
                false,
                admit,
            )
        });
        assert_eq!(loaded.err(), None);
        assert!(schemas.over().is_ok());
        assert!(
            schemas
                .get_catalog("https://json.schemastore.org/y.json", |admit| {
                    admit(super::RUN_PATTERNS)?;
                    Schema::load_text(
                        std::path::Path::new("y.json"),
                        "{}",
                        &Settings::default(),
                        false,
                        admit,
                    )
                })
                .is_ok()
        );
    }

    #[test]
    fn only_a_dollar_schema_that_may_hold_a_path_is_worth_parsing() {
        for (text, path) in [
            ("{}", false),
            (r#"{"$schema": "https://x/s.json", "a": 1}"#, false),
            ("{$schema: 'https://x/s.json'}", false),
            (
                r#"{"a": {"$schema":"http://x"}, "$schema" : "urn:x"}"#,
                false,
            ),
            (r#"{"$schema": "s.json"}"#, true),
            (r#"{"$schema": "C:\\s.json"}"#, true),
            (r#"{"$schema": /* https://x */ "s.json"}"#, true),
            (r#"{"$schema" /* c */: "https://x"}"#, true),
            (r#"{"$schema": 1}"#, true),
            (r#"{"a": "https://x", "$schema": "s.json"}"#, true),
            ("{\"$schema", true),
            (r#"{"\u0024schema": "https://x"}"#, true),
            (r#"{"\x24schema": "https://x"}"#, true),
            ("{\"$sch\\\nema\": \"https://x\"}", true),
            ("{\"$sch\\\u{2028}ema\": \"https://x\"}", true),
            (r#"{"a\tb": "c:\\d", "$schema": "https://x"}"#, false),
        ] {
            assert_eq!(super::may_name_a_path(text), path, "{text}");
        }
    }

    #[test]
    fn is_url_tells_a_scheme_from_a_windows_drive() {
        for (text, url) in [
            ("https://x", true),
            ("ab:x", true),
            ("C:\\a.json", false),
            ("./a.json", false),
            ("a.json", false),
            // A scheme starts with a letter.
            ("1a:x", false),
        ] {
            assert_eq!(super::is_url(text), url, "{text}");
        }
    }

    #[test]
    fn check_own_schema_runs_on_duplicate_key_without_syntax_error() {
        let dir = std::env::temp_dir().join(format!("jsonvet-own-schema-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("a temporary directory");
        std::fs::write(
            dir.join("s.json"),
            r#"{"properties": {"b": {"type": "integer"}}, "required": ["b"]}"#,
        )
        .expect("write schema");
        let settings = Settings::default();
        let schemas = Schemas::default();
        let root = |_path: &std::path::Path| dir.clone();
        let load = |path: &std::path::Path, quiet: bool| {
            Schema::load(path, &settings, quiet, |_| Ok(())).map(std::sync::Arc::new)
        };
        let file = dir.join("test.json");
        let text = r#"{"$schema": "s.json", "k": 1, "k": 2, "b": "bad"}"#;
        let (report, errors) = super::check_own_schema(
            &file.to_string_lossy(),
            text,
            &settings,
            &schemas,
            &root,
            &load,
            1,
        );
        assert_eq!(report.problems().len(), 1);
        assert_eq!(report.problems()[0].rule(), jsonvet::Rule::DuplicateKey);
        assert!(!errors.is_empty(), "own schema should be validated");
        let _ = std::fs::remove_dir_all(&dir);
    }
}