Skip to main content

jsonvet_cli/
lib.rs

1//! The jsonvet command line, shared by the `jsonvet` and `check-json5` binaries.
2
3use std::ffi::{OsStr, OsString};
4use std::io::{self, BufWriter, IsTerminal, Read, Write};
5use std::path::{Path, PathBuf};
6use std::process::ExitCode;
7
8use std::sync::atomic::{AtomicUsize, Ordering};
9use std::sync::{Arc, Mutex};
10
11use jsonvet::{Dialect, Problem, Report, Severity};
12
13mod args;
14mod editorconfig;
15mod format;
16mod frame;
17mod glob;
18mod json;
19mod messages;
20mod output;
21mod rules;
22mod sarif;
23mod schema;
24mod settings;
25mod write;
26
27use args::{Command, STDIN};
28use output::{Format, Look, Printer};
29use schema::Schema;
30use schema::select::{Job, Schemas, check_own_schema, jobs, with_schema};
31use settings::{Resolver, Settings};
32use write::write_atomically;
33
34/// The stack every run uses, for `--schema`: jsonschema validates recursively, and building,
35/// validating and dropping a value [`schema::SCHEMA_MAX_DEPTH`] levels deep against a recursive schema
36/// took up to 2.2 MB in a debug build, more than Windows' 1 MB main thread. Only the pages used
37/// are committed, so a plain check costs no more memory.
38const STACK: usize = 64 << 20;
39
40/// How much memory the files read at once may take before they are checked and printed.
41const CHUNK_BYTES: usize = 64 << 20;
42
43/// How many bytes of memory a byte of file text takes with a schema, which holds the file's value
44/// one document at a time. Kept above the most that docs/usage.md ("JSON Schema limits") gives,
45/// so a chunk never overcommits.
46const SCHEMA_BYTES: usize = 20;
47
48/// From this size, a JSON Lines file is split at newlines and its parts checked on the cores
49/// its chunk leaves free.
50const SPLIT_BYTES: usize = 1 << 20;
51
52/// Run the command with the process's arguments and environment, and return its exit code.
53pub fn run() -> ExitCode {
54    // The release profile aborts on a panic, which ends the process with a signal and no way to
55    // report it. A hook runs first, so a bug exits 101 with a pointer to the issue tracker.
56    std::panic::set_hook(Box::new(|info| {
57        eprintln!(
58            "jsonvet: internal error: {info}\n\nThis is a bug in jsonvet. Please report it at \
59             https://github.com/simonvanlierde/jsonvet/issues with the command you ran and, if \
60             you can share it, the file that caused it."
61        );
62        std::process::exit(101);
63    }));
64    on_big_stack(run_here)
65}
66
67/// Run `f` on a thread with a [`STACK`]-byte stack, or here if no thread can start. A panic in
68/// `f` carries on here.
69fn on_big_stack<T: Send + 'static>(f: fn() -> T) -> T {
70    let thread = std::thread::Builder::new().name("jsonvet".into());
71    match thread.stack_size(STACK).spawn(f) {
72        Ok(thread) => thread
73            .join()
74            .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
75        Err(_) => f(),
76    }
77}
78
79fn run_here() -> ExitCode {
80    // NOTE: a hidden trigger for tests/cli.rs, so the panic hook runs without a real bug. Debug
81    // builds only, so release binaries cannot be made to panic on purpose.
82    #[cfg(debug_assertions)]
83    assert!(
84        std::env::var_os("JSONVET_TEST_PANIC").is_none(),
85        "test panic"
86    );
87    let annotate = std::env::var_os("GITHUB_ACTIONS").is_some_and(|v| v == "true");
88    let stdout = io::stdout().lock();
89    let set = |name| std::env::var_os(name).is_some_and(|v| !v.is_empty());
90    // NO_COLOR wins over FORCE_COLOR: asking for no color is the safer wish to honour.
91    // FORCE_COLOR=0 and =false ask for no color, as Node and chalk read them.
92    let color = if set("NO_COLOR") {
93        Some(false)
94    } else if set("FORCE_COLOR") {
95        Some(std::env::var_os("FORCE_COLOR").is_none_or(|v| v != "0" && v != "false"))
96    } else {
97        None
98    };
99    let terminal = Terminal {
100        tty: stdout.is_terminal(),
101        color,
102    };
103    match run_with(
104        std::env::args_os().skip(1),
105        annotate,
106        terminal,
107        BufWriter::new(stdout),
108    ) {
109        Ok(code) => ExitCode::from(code),
110        Err(message) => {
111            eprintln!("jsonvet: {message}");
112            ExitCode::from(2)
113        }
114    }
115}
116
117/// The end of a run: the `line` of counts as text on a terminal (`text`), and as an annotation
118/// when `found` problems, then whatever the format closes with.
119fn print_summary(
120    printer: &mut Printer<impl Write>,
121    line: Option<&str>,
122    text: bool,
123    found: bool,
124) -> io::Result<()> {
125    if let Some(line) = line {
126        if text {
127            printer.text_line(line)?;
128        }
129        if found {
130            printer.summary_annotation(line)?;
131        }
132    }
133    printer.finish()
134}
135
136/// Where output goes, as far as text output's look depends on it. Public only for
137/// `benches/codspeed.rs`; not part of the crate's API.
138#[doc(hidden)]
139#[derive(Clone, Copy, Debug, Default)]
140pub struct Terminal {
141    /// Standard output is a terminal. A summary and code frames are for people: hooks and CI
142    /// read standard output from a pipe and see one line per problem.
143    pub tty: bool,
144    /// What the environment asks for when `--color` is `auto`: `Some(false)` for `NO_COLOR`,
145    /// `Some(true)` for `FORCE_COLOR`.
146    pub color: Option<bool>,
147}
148
149/// The command, with its inputs passed in: 0 when no file has an error, 1 when one does.
150/// On a terminal, text output ends with a count of the problems. A usage error comes back as
151/// `Err`, which `run` turns into exit status 2. Public only for `benches/codspeed.rs`, which
152/// measures `--schema` in-process; not part of the crate's API.
153#[doc(hidden)]
154pub fn run_with(
155    args: impl IntoIterator<Item = OsString>,
156    annotate: bool,
157    terminal: Terminal,
158    out: impl Write,
159) -> Result<u8, String> {
160    // Usage errors quote arguments and the schema file, which can hold a newline or an escape.
161    let args = match args::parse(args)
162        .map_err(|e| messages::fill("error.usage", &[("error", &output::printable(&e))]))?
163    {
164        Command::Help => return print(out, messages::text("help")),
165        Command::Version => return print(out, concat!("jsonvet ", env!("CARGO_PKG_VERSION"))),
166        Command::ListRules => return print(out, &rules::list()),
167        Command::Explain(text) => return print(out, &text),
168        Command::Check(args) => *args,
169    };
170    messages::english_only(args.format != Format::Text);
171    let resolver = Arc::new(Mutex::new(Resolver::new(&args.config, args.settings)?));
172    let settings_for = |path: &Path| lock(&resolver).for_file(path);
173    let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
174    let files = expand(args.files, &resolver, threads)?;
175    if let Some(check_only) = args.fmt {
176        return format::run(&files, check_only, args.stdin_filename, &resolver, out);
177    }
178    let schemas = Schemas::default();
179    let load = |path: &Path, quiet| {
180        schemas.get(path, quiet, |admit| {
181            Schema::load(path, &*settings_for(path)?, quiet, admit)
182        })
183    };
184    let root = |path: &Path| lock(&resolver).root(path);
185
186    // Standard input goes by its `--stdin-filename`, for settings and in the output.
187    let stdin_name = args.stdin_filename.unwrap_or_else(|| STDIN.into());
188    let shown = |file: &OsStr| -> OsString {
189        if file == STDIN {
190            stdin_name.clone()
191        } else {
192            file.to_owned()
193        }
194    };
195    // Every config file, and every schema one names, is read before any file is checked, so a
196    // bad one stops the run at once.
197    let files = jobs(files, &shown, &settings_for, args.schema.as_deref(), &load)?;
198    let look = look(args.format, args.color, terminal);
199    // Standard input fixed to standard output leaves only standard error for the problems.
200    let stdin_fix = args.fix && files.iter().any(|(_, file)| file == STDIN);
201    let mut out = out;
202    let sink = Diagnostics::new(stdin_fix, &mut out);
203    let mut printer = Printer::new(sink, args.format, annotate, look);
204    let mut fixed = FixRun::default();
205    let mut counts = Counts::default();
206    // Files are read and checked on every core, a chunk at a time, then printed here in the
207    // order given. A chunk ends once its files hold CHUNK_BYTES, so memory stays near that. With
208    // a schema a file takes SCHEMA_BYTES times its size, so the chunk is cut from the sizes
209    // before any file is read: otherwise every core would start on a file at once. Without
210    // a schema the files are not sized first, which made a walk of 10,000 files 7 ms slower.
211    // A file whose own `$schema` may name a schema is known only once read: it counts the same,
212    // and the texts read past the end of the chunk are kept, in `ahead`, for the next one.
213    // NOTE: each chunk waits for its slowest file before the next starts; hand files out
214    // one at a time across chunks if one big file among many small ones holds a run up.
215    let mut rest = &files[..];
216    let shares = schema_shares(&files, threads);
217    let mut ahead = Vec::new();
218    let written = loop {
219        if rest.is_empty() {
220            let line = (!files.is_empty()).then(|| counts.summary(files.len()));
221            let found = counts.errors + counts.warnings > 0;
222            break print_summary(&mut printer, line.as_deref(), terminal.tty, found);
223        }
224        let shares = shares.get(files.len() - rest.len()..);
225        let with_schema = |job: &Job, text: &str| with_schema(job, &shown(&job.1), text);
226        let mut texts = take_chunk(&mut ahead, rest, shares, threads, &with_schema);
227        let chunk;
228        (chunk, rest) = rest.split_at(texts.len());
229        let known = if args.fix {
230            fix_chunk(
231                chunk,
232                &mut texts,
233                &shown,
234                args.unsafe_fixes,
235                threads,
236                &mut fixed,
237            )
238        } else {
239            vec![None; texts.len()]
240        };
241        let jobs: Vec<_> = chunk.iter().zip(&texts).zip(&known).collect();
242        let parts = (threads / jobs.len()).max(1);
243        let checked = parallel(
244            &jobs,
245            threads,
246            || false,
247            |((((settings, schema), file), (text, with)), known)| {
248                let name = shown(file);
249                let name = name.to_string_lossy();
250                text.as_deref().map(|text| match schema {
251                    Some(schema) => check(&name, text, settings, Some(schema), parts, None),
252                    None if *with => {
253                        check_own_schema(&name, text, settings, &schemas, &root, &load, parts)
254                    }
255                    None => check(&name, text, settings, None, parts, known.as_deref()),
256                })
257            },
258        );
259        schemas.over().map_err(|e| output::printable(&e))?;
260        let outcome = print_checked(chunk, checked, &shown, &mut printer, &mut counts);
261        if outcome.is_err() {
262            break outcome;
263        }
264    };
265    let written = written.and_then(|()| fixed.finish(&mut out));
266    conclude(written, &schemas, &counts, args.max_warnings)
267}
268
269/// A file's report and its schema errors.
270type Checked<'t> = (Report<'t>, Vec<(usize, String, bool)>);
271
272/// Print what checking the files of `chunk` found, in order: the problems of each, or why it
273/// could not be read.
274fn print_checked(
275    chunk: &[Job],
276    checked: Vec<Result<Checked<'_>, &String>>,
277    shown: &impl Fn(&OsStr) -> OsString,
278    printer: &mut Printer<impl Write>,
279    counts: &mut Counts,
280) -> io::Result<()> {
281    chunk
282        .iter()
283        .zip(checked)
284        .try_for_each(|((_, file), checked)| match checked {
285            Ok((report, schema_errors)) => {
286                print_file(&shown(file), &report, &schema_errors, printer, counts)
287            }
288            Err(message) => {
289                counts.errors += 1;
290                counts.files += 1;
291                printer.unreadable(&shown(file), message)
292            }
293        })
294}
295
296/// The exit code once the output is written: 1 for an error, or for more warnings than
297/// `max_warnings` allows.
298fn conclude(
299    written: io::Result<()>,
300    schemas: &Schemas,
301    counts: &Counts,
302    max_warnings: Option<usize>,
303) -> Result<u8, String> {
304    // A reader that has gone, as with `| head`, wants no more output: the verdict so far stands.
305    match written {
306        Err(e) if e.kind() != io::ErrorKind::BrokenPipe => {
307            return Err(messages::fill("error.write", &[("error", &e)]));
308        }
309        _ => {}
310    }
311    schemas.note_missing();
312    let too_many_warnings = max_warnings.is_some_and(|max| counts.warnings > max);
313    Ok(u8::from(counts.errors > 0 || too_many_warnings))
314}
315
316/// The texts of the first of `files`, read on up to `threads` threads until their [`weight`]s
317/// reach [`CHUNK_BYTES`], and always the first, each with whether `with_schema` says it is
318/// checked against a schema.
319fn read_chunk<S: Sync>(
320    files: &[(S, OsString)],
321    threads: usize,
322    with_schema: &(impl Fn(&(S, OsString), &str) -> bool + Sync),
323) -> Vec<(Result<String, String>, bool)> {
324    let bytes = AtomicUsize::new(0);
325    let full = || bytes.load(Ordering::Relaxed) >= CHUNK_BYTES;
326    parallel(files, threads, full, |file| {
327        let text = if file.1 == STDIN {
328            read_stdin()
329        } else {
330            read(Path::new(&file.1))
331        };
332        let with = text.as_ref().is_ok_and(|text| with_schema(file, text));
333        bytes.fetch_add(weight(&text, with), Ordering::Relaxed);
334        (text, with)
335    })
336}
337
338/// The texts of the next chunk of `rest`, the files left, each with whether it is checked
339/// against a schema: up to and including the one whose [`weight`] fills [`CHUNK_BYTES`], from
340/// `ahead`, the texts of the first of them read already, or if none are, from those read now.
341/// `shares` are the files' [`schema_share`]s, if any.
342fn take_chunk(
343    ahead: &mut Vec<(Result<String, String>, bool)>,
344    rest: &[Job],
345    shares: Option<&[usize]>,
346    threads: usize,
347    with_schema: &(impl Fn(&Job, &str) -> bool + Sync),
348) -> Vec<(Result<String, String>, bool)> {
349    if ahead.is_empty() {
350        let offered = match shares {
351            Some(shares) if !shares.is_empty() => &rest[..chunk_len(shares)],
352            _ => rest,
353        };
354        *ahead = read_chunk(offered, threads, with_schema);
355    }
356    let weights: Vec<usize> = ahead
357        .iter()
358        .map(|(text, with)| weight(text, *with))
359        .collect();
360    ahead.drain(..chunk_len(&weights)).collect()
361}
362
363/// The memory a text read takes while it is checked, as far as a chunk counts it: its size, or
364/// with a schema, [`SCHEMA_BYTES`] times that, capped at [`CHUNK_BYTES`].
365fn weight(text: &Result<String, String>, with_schema: bool) -> usize {
366    let size = text.as_ref().map_or(0, String::len);
367    if with_schema {
368        size.saturating_mul(SCHEMA_BYTES).min(CHUNK_BYTES)
369    } else {
370        size
371    }
372}
373
374/// The memory a file takes while a schema checks it, as far as a chunk counts it:
375/// [`SCHEMA_BYTES`] times its size, capped at [`CHUNK_BYTES`]. Standard input's size is known
376/// only once it is read, so it takes a chunk's worth. A file that cannot be read takes nothing:
377/// `read` reports why.
378fn schema_share(file: &OsStr) -> usize {
379    if file == STDIN {
380        return CHUNK_BYTES;
381    }
382    let size = std::fs::metadata(file).map_or(0, |meta| meta.len());
383    usize::try_from(size)
384        .unwrap_or(usize::MAX)
385        .saturating_mul(SCHEMA_BYTES)
386        .min(CHUNK_BYTES)
387}
388
389/// Each file's [`schema_share`], or 0 for a file with no schema; nothing if no file has one.
390fn schema_shares(files: &[Job], threads: usize) -> Vec<usize> {
391    if files.iter().all(|((_, schema), _)| schema.is_none()) {
392        return Vec::new();
393    }
394    parallel(
395        files,
396        threads,
397        || false,
398        |((_, schema), file)| schema.as_ref().map_or(0, |_| schema_share(file)),
399    )
400}
401
402/// How many of the files with these shares the next chunk takes: up to and including the one
403/// that fills [`CHUNK_BYTES`], so always at least one.
404fn chunk_len(shares: &[usize]) -> usize {
405    let mut total = 0;
406    shares
407        .iter()
408        .position(|share| {
409            total += share;
410            total >= CHUNK_BYTES
411        })
412        .map_or(shares.len(), |last| last + 1)
413}
414
415/// The files to check: each argument as given, except that a directory stands for the files under
416/// it that jsonvet checks by default, in sorted order. The walk skips hidden files and what
417/// `.gitignore`, `.ignore` and the `exclude` setting of each folder's settings name, as ripgrep
418/// would.
419fn expand(
420    args: Vec<OsString>,
421    resolver: &Arc<Mutex<Resolver>>,
422    threads: usize,
423) -> Result<Vec<OsString>, String> {
424    let mut files = Vec::with_capacity(args.len());
425    // Each argument costs a call to the system, so thousands of them are asked about in parallel.
426    let dirs = parallel(
427        &args,
428        threads,
429        || false,
430        |arg| arg != STDIN && Path::new(arg).is_dir(),
431    );
432    // Folders that share no file need no check for repeats: the walk follows no symlinks.
433    let mut roots = Vec::new();
434    let mut distinct = true;
435    for (arg, dir) in args.into_iter().zip(dirs) {
436        if !dir {
437            distinct = false;
438            files.push(arg);
439            continue;
440        }
441        let start = files.len();
442        // The walk reads the ignore files of the folder, and of every folder above it when it
443        // can find them, before the filter sees anything.
444        let above = std::fs::canonicalize(&arg).ok();
445        match &above {
446            Some(root) => roots.push(root.clone()),
447            None => distinct = false,
448        }
449        if let Some(problem) = std::iter::once(Path::new(&arg))
450            .chain(above.iter().flat_map(|dir| dir.ancestors()))
451            .find_map(unsafe_ignore_file)
452        {
453            return Err(problem);
454        }
455        let skipped = Arc::new(Mutex::new(None));
456        let skip = Arc::clone(&skipped);
457        // The filter must own what it reads.
458        let resolver = Arc::clone(resolver);
459        // A config file that cannot be read excludes nothing here: the run reports it when it
460        // looks up the settings of the files under it.
461        let walk = ignore::WalkBuilder::new(&arg)
462            .filter_entry(move |entry| {
463                // The walk reads a folder's ignore files once the filter lets the folder in.
464                if entry.file_type().is_some_and(|t| t.is_dir())
465                    && let Some(problem) = unsafe_ignore_file(entry.path())
466                {
467                    // A poisoned lock still holds the message.
468                    skip.lock()
469                        .unwrap_or_else(std::sync::PoisonError::into_inner)
470                        .get_or_insert(problem);
471                    return false;
472                }
473                let settings = lock(&resolver).for_file(entry.path());
474                !settings.is_ok_and(|settings| settings.excluded(entry.path()))
475            })
476            .build();
477        for entry in walk {
478            let entry = entry
479                .map_err(|e| output::printable(&messages::fill("error.walk", &[("error", &e)])))?;
480            if entry.file_type().is_some_and(|t| t.is_file())
481                && Dialect::for_path(entry.path()).is_some()
482            {
483                files.push(entry.into_path().into_os_string());
484            }
485        }
486        if let Some(problem) = skipped
487            .lock()
488            .unwrap_or_else(std::sync::PoisonError::into_inner)
489            .take()
490        {
491            return Err(problem);
492        }
493        files[start..].sort_unstable();
494    }
495    // Checking costs a call to the system for each file, 12% of a run over 10,000 small files.
496    let overlap = |i: usize, root: &PathBuf| {
497        roots[..i]
498            .iter()
499            .any(|r| r.starts_with(root) || root.starts_with(r))
500    };
501    if distinct && !roots.iter().enumerate().any(|(i, root)| overlap(i, root)) {
502        return Ok(files);
503    }
504    Ok(unique(files, threads))
505}
506
507/// What names a file apart from its spelling.
508#[derive(PartialEq, Eq, Hash)]
509enum Identity {
510    #[cfg(unix)]
511    Inode(u64, u64),
512    Path(PathBuf),
513}
514
515fn identity(file: &OsStr) -> Identity {
516    #[cfg(unix)]
517    if let Ok(meta) = std::fs::metadata(file) {
518        use std::os::unix::fs::MetadataExt;
519        return Identity::Inode(meta.dev(), meta.ino());
520    }
521    // A file that cannot be found stays as spelled, so it is reported once per spelling.
522    Identity::Path(std::fs::canonicalize(file).unwrap_or_else(|_| file.into()))
523}
524
525/// `files` without any that is the same file as an earlier one, so that each is checked once,
526/// under its first spelling. Standard input can be given only once, as the arguments check.
527fn unique(files: Vec<OsString>, threads: usize) -> Vec<OsString> {
528    let ids = parallel(&files, threads, || false, |file| identity(file));
529    let mut seen = std::collections::HashSet::with_capacity(files.len());
530    files
531        .into_iter()
532        .zip(ids)
533        .filter_map(|(file, id)| seen.insert(id).then_some(file))
534        .collect()
535}
536
537/// The resolver, even if a panic elsewhere left its lock poisoned: it holds only a cache.
538fn lock(resolver: &Mutex<Resolver>) -> std::sync::MutexGuard<'_, Resolver> {
539    resolver
540        .lock()
541        .unwrap_or_else(std::sync::PoisonError::into_inner)
542}
543
544/// Where the problems go: standard output, or standard error when standard output carries a
545/// fixed text.
546enum Diagnostics<'w, W: Write> {
547    Out(&'w mut W),
548    Stderr(io::Stderr),
549}
550
551impl<'w, W: Write> Diagnostics<'w, W> {
552    fn new(to_stderr: bool, out: &'w mut W) -> Self {
553        if to_stderr {
554            Diagnostics::Stderr(io::stderr())
555        } else {
556            Diagnostics::Out(out)
557        }
558    }
559}
560
561impl<W: Write> Write for Diagnostics<'_, W> {
562    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
563        match self {
564            Diagnostics::Out(out) => out.write(buf),
565            Diagnostics::Stderr(err) => err.write(buf),
566        }
567    }
568
569    fn flush(&mut self) -> io::Result<()> {
570        match self {
571            Diagnostics::Out(out) => out.flush(),
572            Diagnostics::Stderr(err) => err.flush(),
573        }
574    }
575}
576
577/// What `--fix` did over the whole run.
578#[derive(Default)]
579struct FixRun {
580    problems: usize,
581    files: usize,
582    /// Standard input as it is after the fixes, for standard output.
583    stdin: Option<String>,
584}
585
586impl FixRun {
587    /// Print the count to standard error, then standard input's fixed text to `out`.
588    fn finish(&self, out: &mut impl Write) -> io::Result<()> {
589        if let Some(summary) = self.summary() {
590            eprintln!("{summary}");
591        }
592        match &self.stdin {
593            Some(text) => out.write_all(text.as_bytes()).and_then(|()| out.flush()),
594            None => Ok(()),
595        }
596    }
597
598    /// Such as `fixed 3 problems in 2 files`, or `None` when nothing was fixed.
599    fn summary(&self) -> Option<String> {
600        (self.problems > 0).then(|| {
601            messages::fill(
602                "summary.fixed",
603                &[
604                    (
605                        "problems",
606                        &messages::count("summary.problems", self.problems),
607                    ),
608                    ("files", &messages::count("summary.files", self.files)),
609                ],
610            )
611        })
612    }
613}
614
615/// Fix the `texts` of `chunk` in place, and write each changed file, so the check that follows
616/// reports what is left. A file that cannot be written gets the reason in place of its text.
617fn fix_chunk(
618    chunk: &[Job],
619    texts: &mut [(Result<String, String>, bool)],
620    shown: &(impl Fn(&OsStr) -> OsString + Sync),
621    unsafe_fixes: bool,
622    threads: usize,
623    run: &mut FixRun,
624) -> Vec<Option<Vec<Problem>>> {
625    let jobs: Vec<_> = chunk.iter().zip(texts.iter()).collect();
626    let done = parallel(
627        &jobs,
628        threads,
629        || false,
630        |(((settings, _), file), (text, _))| {
631            let text = text.as_ref().ok()?;
632            let name = shown(file);
633            let config = settings.config_for(&name.to_string_lossy());
634            let fixed = match jsonvet::try_fix(text, &config, unsafe_fixes) {
635                Ok(fixed) => fixed,
636                Err(problems) => return Some(Err(problems)),
637            };
638            let saved = if file == STDIN {
639                Ok(())
640            } else {
641                write_atomically(Path::new(file), &fixed.text)
642            };
643            Some(Ok((fixed, saved)))
644        },
645    );
646    drop(jobs);
647    let mut known = Vec::with_capacity(done.len());
648    for (((_, file), entry), done) in chunk.iter().zip(texts.iter_mut()).zip(done) {
649        // The scan's problems stand for the check only while the text is unchanged.
650        known.push(match &done {
651            Some(Err(problems)) => problems.clone(),
652            _ => None,
653        });
654        let done = done.and_then(Result::ok);
655        match done {
656            Some((fixed, Ok(()))) => {
657                run.problems += fixed.fixes.len();
658                run.files += 1;
659                entry.0 = Ok(fixed.text);
660            }
661            Some((_, Err(error))) => {
662                entry.0 = Err(error);
663            }
664            None => {}
665        }
666        if file == STDIN
667            && let Ok(text) = &entry.0
668        {
669            run.stdin = Some(text.clone());
670        }
671    }
672    known
673}
674
675#[derive(Default)]
676struct Counts {
677    errors: usize,
678    warnings: usize,
679    /// Files with at least one problem, or that could not be read.
680    files: usize,
681}
682
683impl Counts {
684    /// Such as `3 errors and 1 warning in 2 of 5 files`.
685    fn summary(&self, checked: usize) -> String {
686        let files = messages::count("summary.files", checked);
687        if self.errors + self.warnings == 0 {
688            return messages::fill("summary.none", &[("files", &files)]);
689        }
690        let errors = || messages::count("summary.errors", self.errors);
691        let warnings = || messages::count("summary.warnings", self.warnings);
692        let problems = match (self.errors, self.warnings) {
693            (_, 0) => errors(),
694            (0, _) => warnings(),
695            _ => messages::fill(
696                "summary.both",
697                &[("errors", &errors()), ("warnings", &warnings())],
698            ),
699        };
700        messages::fill(
701            "summary.some",
702            &[
703                ("problems", &problems),
704                ("failed", &self.files),
705                ("files", &files),
706            ],
707        )
708    }
709}
710
711/// `f` on the items, on up to `threads` threads counting this one, each with a [`STACK`]-byte
712/// stack, until `stop` says so before an item is taken: the results for the items done, in
713/// order, always at least the first. A panic in `f` carries on here.
714fn parallel<T: Sync, U: Send>(
715    items: &[T],
716    threads: usize,
717    stop: impl Fn() -> bool + Sync,
718    f: impl Fn(&T) -> U + Sync,
719) -> Vec<U> {
720    let next = AtomicUsize::new(0);
721    // Each thread takes the next item in turn, so the items taken are always the first ones,
722    // and the results are tagged to put them back in order.
723    let work = || {
724        let mut done = Vec::new();
725        loop {
726            if stop() && next.load(Ordering::Relaxed) > 0 {
727                break done;
728            }
729            let i = next.fetch_add(1, Ordering::Relaxed);
730            let Some(item) = items.get(i) else { break done };
731            done.push((i, f(item)));
732        }
733    };
734    let mut done = std::thread::scope(|scope| {
735        // A thread that cannot start leaves its share to the others.
736        let helpers: Vec<_> = (1..threads.min(items.len()))
737            .filter_map(|_| {
738                std::thread::Builder::new()
739                    .stack_size(STACK)
740                    .spawn_scoped(scope, work)
741                    .ok()
742            })
743            .collect();
744        let mut done = work();
745        for helper in helpers {
746            done.extend(
747                helper
748                    .join()
749                    .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
750            );
751        }
752        done
753    });
754    done.sort_unstable_by_key(|&(i, _)| i);
755    done.into_iter().map(|(_, result)| result).collect()
756}
757
758/// The parts to check a text in `dialect` in, on up to `parts` threads: more than one only for
759/// JSON Lines of [`SPLIT_BYTES`] or more.
760fn split(text: &str, dialect: Dialect, parts: usize) -> Vec<std::ops::Range<usize>> {
761    let split = dialect == Dialect::JsonLines && parts > 1 && text.len() >= SPLIT_BYTES;
762    jsonvet::line_parts(text, if split { parts } else { 1 })
763}
764
765/// Check a file's text, named by its lossy UTF-8 form for glob matching, and against `schema`
766/// if there is one, on up to `parts` threads: the report and the schema errors.
767fn check<'t>(
768    name: &str,
769    text: &'t str,
770    settings: &Settings,
771    schema: Option<&Schema>,
772    parts: usize,
773    known: Option<&[Problem]>,
774) -> (Report<'t>, Vec<(usize, String, bool)>) {
775    let config = settings.config_for(name);
776    let ranges = split(text, config.dialect(), parts);
777    if ranges.len() > 1 {
778        // Each line is a document of its own, and the error cap counts per document, so each
779        // part's schema errors are the ones a single pass finds in its lines.
780        let (lines, errors): (Vec<_>, Vec<_>) = parallel(
781            &ranges,
782            parts,
783            || false,
784            |lines| match schema {
785                Some(schema) => schema.check_lines(text, lines.clone(), &config),
786                None => (
787                    jsonvet::parse_lines(text, lines.clone(), &config, None),
788                    Vec::new(),
789                ),
790            },
791        )
792        .into_iter()
793        .unzip();
794        let (report, syntax_error) = jsonvet::join_lines(text, lines);
795        // A file with a syntax error in any part gets no schema errors.
796        let errors = if syntax_error {
797            Vec::new()
798        } else {
799            errors.into_iter().flatten().collect()
800        };
801        return (report, errors);
802    }
803    match schema {
804        // A file with a syntax error gets no schema errors.
805        Some(schema) => schema.check(text, &config),
806        // The problems `--fix` found on its way, when it changed nothing.
807        None => match known {
808            Some(problems) => (
809                jsonvet::report(text, problems.to_vec(), &config),
810                Vec::new(),
811            ),
812            None => (jsonvet::check(text, &config), Vec::new()),
813        },
814    }
815}
816
817/// How text output looks: code frames on a terminal and lines otherwise, so tools reading a pipe
818/// always get `file:line:col`, and in color as `--color` and the environment ask.
819fn look(format: Format, color: Option<bool>, terminal: Terminal) -> Look {
820    let text = format == Format::Text;
821    Look {
822        frames: text && terminal.tty,
823        color: text && color.or(terminal.color).unwrap_or(terminal.tty),
824    }
825}
826
827/// Print one file's problems and schema errors, and add them to `counts`, each before it is
828/// printed, so a failed write still leaves the verdict. The file count is added last: only the
829/// summary reads it, and a failed write ends the run before the summary.
830fn print_file(
831    file: &OsStr,
832    report: &Report<'_>,
833    schema_errors: &[(usize, String, bool)],
834    printer: &mut Printer<impl Write>,
835    counts: &mut Counts,
836) -> io::Result<()> {
837    let before = counts.errors + counts.warnings;
838    for problem in report.problems() {
839        match problem.severity() {
840            Severity::Error => counts.errors += 1,
841            Severity::Warning => counts.warnings += 1,
842            _ => {}
843        }
844        printer.problem(file, report, problem)?;
845    }
846    for (offset, message, summary) in schema_errors {
847        counts.errors += usize::from(!summary);
848        printer.schema_error(file, report, *offset, message, *summary)?;
849    }
850    counts.files += usize::from(counts.errors + counts.warnings > before);
851    Ok(())
852}
853
854/// A file's text, or why it has none. Only regular files are read, so a FIFO cannot hang the
855/// run and a device such as `/dev/zero` cannot fill memory. A symlink to a regular file is
856/// followed, as `cat` would.
857fn read(path: &Path) -> Result<String, String> {
858    let read = std::fs::metadata(path).and_then(|meta| {
859        if meta.is_file() {
860            std::fs::read(path).map(Some)
861        } else {
862            Ok(None)
863        }
864    });
865    match read {
866        Ok(Some(bytes)) => decode(bytes),
867        Ok(None) => Err(messages::text("read.not-regular").to_owned()),
868        Err(e) if e.kind() == io::ErrorKind::NotFound => {
869            Err(messages::text("read.missing").to_owned())
870        }
871        Err(e) => Err(messages::fill("read.error", &[("error", &e)])),
872    }
873}
874
875/// Standard input's text, or why it has none. Empty input is an empty file.
876fn read_stdin() -> Result<String, String> {
877    let mut bytes = Vec::new();
878    match io::stdin().lock().read_to_end(&mut bytes) {
879        Ok(_) => decode(bytes),
880        Err(e) => Err(messages::fill("read.error", &[("error", &e)])),
881    }
882}
883
884/// A file's bytes as UTF-8 text. A UTF-16 or UTF-32 file says so, rather than that its first
885/// byte is not UTF-8: by its byte order mark, or without one by where the zero bytes of its first
886/// two characters fall, as RFC 4627 section 3 tells the encodings apart.
887fn decode(bytes: Vec<u8>) -> Result<String, String> {
888    // Without a mark, a text these patterns match would fail the check anyway: a zero byte is
889    // U+0000, and outside a string no dialect allows it. JSON5 does allow it raw inside one, so
890    // a first byte that opens a string is left alone.
891    let opens_string = |b: u8| b == b'"' || b == b'\'';
892    // UTF-32 LE first: its mark starts with UTF-16 LE's.
893    let encoding = match *bytes.as_slice() {
894        [0xFF, 0xFE, 0, 0, ..] => Some("UTF-32 (LE)"),
895        [0, 0, 0xFE, 0xFF, ..] => Some("UTF-32 (BE)"),
896        [0xFF, 0xFE, ..] => Some("UTF-16 (LE)"),
897        [0xFE, 0xFF, ..] => Some("UTF-16 (BE)"),
898        [0, 0, 0, a, ..] if a != 0 => Some("UTF-32 (BE)"),
899        [0, a, 0, b, ..] if a != 0 && b != 0 => Some("UTF-16 (BE)"),
900        [a, 0, 0, 0, ..] if a != 0 && !opens_string(a) => Some("UTF-32 (LE)"),
901        [a, 0, b, 0, ..] if a != 0 && b != 0 && !opens_string(a) => Some("UTF-16 (LE)"),
902        _ => None,
903    };
904    if let Some(encoding) = encoding {
905        return Err(messages::fill("read.encoding", &[("encoding", &encoding)]));
906    }
907    String::from_utf8(bytes).map_err(|e| {
908        let byte = e.utf8_error().valid_up_to();
909        messages::fill("read.not-utf8", &[("byte", &byte)])
910    })
911}
912
913/// The most a config file or an ignore file may hold: real ones take a few kilobytes.
914pub(crate) const MAX_CONFIG_BYTES: u64 = 16 << 20;
915
916/// The most a `--schema` file may hold: 40 times the largest schema on schemastore.org
917/// (1.6 MB), and room for the 5,000,000 objects and arrays a schema may hold at 2 to 3 bytes each.
918pub(crate) const MAX_SCHEMA_BYTES: u64 = 64 << 20;
919
920/// The text of a config or schema file of at most `max` bytes. As in [`read`], only a regular
921/// file, or a symlink to one, is opened, so a FIFO cannot hang the run and `/dev/zero` cannot
922/// fill memory.
923pub(crate) fn read_small(path: &Path, max: u64) -> io::Result<String> {
924    if !std::fs::metadata(path)?.is_file() {
925        return Err(io::Error::other(messages::text("read.not-regular")));
926    }
927    let mut text = String::new();
928    // The cap holds even for a file that grows after the check.
929    std::fs::File::open(path)?
930        .take(max + 1)
931        .read_to_string(&mut text)?;
932    if text.len() as u64 > max {
933        let mb = max >> 20;
934        return Err(io::Error::other(messages::fill(
935            "read.too-large",
936            &[("mb", &mb)],
937        )));
938    }
939    Ok(text)
940}
941
942/// Why a folder walk must not read the `.gitignore` or `.ignore` in `dir`, if it must not. The
943/// `ignore` crate reads them to the end with no check of what they are, so a link to
944/// `/dev/zero` takes memory until the run is killed and a FIFO hangs it. A file that cannot be
945/// looked at is no problem: the crate skips it too.
946fn unsafe_ignore_file(dir: &Path) -> Option<String> {
947    [".gitignore", ".ignore"].into_iter().find_map(|name| {
948        let path = dir.join(name);
949        let meta = std::fs::metadata(&path).ok()?;
950        let problem = if !meta.is_file() {
951            messages::text("read.not-regular").to_owned()
952        } else if meta.len() > MAX_CONFIG_BYTES {
953            messages::fill("read.too-large", &[("mb", &(MAX_CONFIG_BYTES >> 20))])
954        } else {
955            return None;
956        };
957        let error = format!("{}: {problem}", path.display());
958        Some(output::printable(&messages::fill(
959            "error.walk",
960            &[("error", &error)],
961        )))
962    })
963}
964
965fn print(mut out: impl Write, text: &str) -> Result<u8, String> {
966    match writeln!(out, "{text}").and_then(|()| out.flush()) {
967        Err(e) if e.kind() != io::ErrorKind::BrokenPipe => {
968            Err(messages::fill("error.write", &[("error", &e)]))
969        }
970        _ => Ok(0),
971    }
972}
973
974#[cfg(test)]
975mod tests {
976    use std::fmt::Write as _;
977    use std::sync::atomic::{AtomicUsize, Ordering};
978
979    use jsonvet::Dialect;
980
981    use super::{
982        CHUNK_BYTES, MAX_CONFIG_BYTES, SCHEMA_BYTES, SPLIT_BYTES, STDIN, Schema, Settings, check,
983        chunk_len, parallel, read_small, schema_share, schema_shares, split, take_chunk,
984        unsafe_ignore_file,
985    };
986    use crate::schema::select::Job;
987    use std::sync::Arc;
988
989    /// A schema that takes any value, in a fresh folder named for `test`, which also holds an
990    /// empty folder `x`.
991    fn any_schema(test: &str) -> (std::path::PathBuf, Schema) {
992        let dir = std::env::temp_dir().join(format!("jsonvet-{test}-{}", std::process::id()));
993        std::fs::create_dir_all(dir.join("x")).expect("a temporary directory");
994        std::fs::write(dir.join("s.json"), "{}").expect("written");
995        let schema = Schema::load(&dir.join("s.json"), &Settings::default(), false, |_| Ok(()));
996        (dir, schema.expect("a schema"))
997    }
998
999    #[test]
1000    fn only_files_with_a_schema_take_a_share() {
1001        let (dir, schema) = any_schema("shares");
1002        let _ = std::fs::remove_dir_all(&dir);
1003        let schema = Arc::new(schema);
1004        let settings = Arc::new(Settings::default());
1005        let job =
1006            |schema: Option<&Arc<Schema>>| ((Arc::clone(&settings), schema.cloned()), STDIN.into());
1007        assert_eq!(
1008            schema_shares(&[job(None), job(None)], 2),
1009            Vec::<usize>::new()
1010        );
1011        assert_eq!(
1012            schema_shares(&[job(None), job(Some(&schema)), job(None)], 2),
1013            [0, CHUNK_BYTES, 0]
1014        );
1015    }
1016
1017    #[test]
1018    fn small_files_are_read_up_to_their_limit_and_no_further() {
1019        let dir = std::env::temp_dir().join(format!("jsonvet-small-{}", std::process::id()));
1020        std::fs::create_dir_all(&dir).expect("a temporary directory");
1021        let path = dir.join("f");
1022        std::fs::write(&path, "0123456789").expect("written");
1023        assert_eq!(read_small(&path, 10).expect("ten bytes"), "0123456789");
1024        assert!(read_small(&path, 9).is_err());
1025        // An ignore file is judged by its size alone; sparse files, so nothing is written.
1026        let sized = |len: u64| {
1027            std::fs::File::create(dir.join(".gitignore"))
1028                .and_then(|file| file.set_len(len))
1029                .expect("a large file");
1030        };
1031        sized(MAX_CONFIG_BYTES);
1032        assert_eq!(unsafe_ignore_file(&dir), None);
1033        sized(MAX_CONFIG_BYTES + 1);
1034        assert!(unsafe_ignore_file(&dir).is_some_and(|e| e.ends_with("larger than 16 MB")));
1035        let _ = std::fs::remove_dir_all(&dir);
1036    }
1037
1038    #[test]
1039    fn only_json_lines_of_the_split_size_is_split_one_part_per_thread() {
1040        let line = "[1]\n".repeat(SPLIT_BYTES / 4);
1041        assert_eq!(split(&line, Dialect::JsonLines, 8).len(), 8);
1042        assert_eq!(split(&line, Dialect::JsonLines, 1).len(), 1);
1043        assert_eq!(split(&line, Dialect::Json, 8).len(), 1);
1044        assert_eq!(split(&line[4..], Dialect::JsonLines, 8).len(), 1);
1045    }
1046
1047    #[test]
1048    fn a_large_json_lines_file_checked_in_parts_reports_what_one_pass_does() {
1049        // Problems in every part: duplicate keys, and strings the schema wants as integers. Every
1050        // thousandth line has more schema errors than a document reports, and two in each
1051        // thousand have values the schema cannot check.
1052        let pad = "x".repeat(500);
1053        let wide: Vec<String> = (0..150).map(|k| format!("\"k{k}\": \"s\"")).collect();
1054        let wide = format!("{{{}}}", wide.join(", "));
1055        let mut text = String::from("\u{FEFF}");
1056        for i in 0..4_000 {
1057            let _ = match i % 7 {
1058                _ if i % 1_000 == 999 => writeln!(text, "{wide}"),
1059                _ if i % 1_000 == 500 => writeln!(text, "{{\"a\": 1e400}}"),
1060                _ if i % 1_000 == 501 => writeln!(text, r#"{{"\ud800": 1, "\ud801": 2}}"#),
1061                0 => writeln!(text, "{{\"a\": {i}, \"a\": 1}}"),
1062                1 => write!(text, "{{\"a\": \"{i}\", \"p\": \"{pad}\"}}\r\n"),
1063                _ => writeln!(text, "{{\"a\": {i}, \"p\": \"{pad}\"}}"),
1064            };
1065        }
1066        assert!(text.len() > SPLIT_BYTES);
1067        let deep = format!("{}{}\n", "[".repeat(600), "]".repeat(600));
1068        let texts = [
1069            text.clone(),
1070            format!("{text}{{\"a\": 1\n{text}"),
1071            format!("{text}{deep}{text}"),
1072        ];
1073        let dir = std::env::temp_dir().join(format!("jsonvet-split-{}", std::process::id()));
1074        std::fs::create_dir_all(&dir).expect("a temporary directory");
1075        let path = dir.join("schema.json");
1076        let schema = concat!(
1077            r#"{"properties": {"a": {"type": "integer"}}, "#,
1078            r#""patternProperties": {"^k": {"type": "integer"}}}"#,
1079        );
1080        std::fs::write(&path, schema).expect("written");
1081        let settings = Settings::default();
1082        let schema = Schema::load(&path, &settings, false, |_| Ok(())).expect("a schema");
1083        let _ = std::fs::remove_dir_all(&dir);
1084        for text in &texts {
1085            for schema in [None, Some(&schema)] {
1086                let (whole, whole_errors) = check("x.jsonl", text, &settings, schema, 1, None);
1087                let (split, split_errors) = check("x.jsonl", text, &settings, schema, 8, None);
1088                assert_ne!(whole.problems(), &[]);
1089                assert_eq!(split.problems(), whole.problems());
1090                assert_eq!(split_errors, whole_errors);
1091            }
1092        }
1093        let (_, errors) = check("x.jsonl", &texts[0], &settings, Some(&schema), 8, None);
1094        // 570 strings, 100 and a summary for each wide line, and one for each line not checked.
1095        assert_eq!(errors.len(), 570 + 4 * 101 + 8);
1096        let unchecked = errors.iter().filter(|(_, m, _)| m.contains("not checked"));
1097        assert_eq!(unchecked.count(), 8);
1098    }
1099
1100    #[test]
1101    fn parallel_keeps_the_order_and_stops_after_a_prefix() {
1102        let items: Vec<usize> = (0..1000).collect();
1103        for threads in [1, 3, 16] {
1104            let squares = parallel(&items, threads, || false, |i| i * i);
1105            assert_eq!(squares, items.iter().map(|i| i * i).collect::<Vec<_>>());
1106            // Stopped from the start, it still does the first item, and a thread that looks
1107            // before another has taken it may take one more.
1108            let stopped = parallel(&items, threads, || true, |&i| i);
1109            assert!((1..=threads).contains(&stopped.len()), "{stopped:?}");
1110            assert_eq!(stopped, (0..stopped.len()).collect::<Vec<_>>());
1111            let done = AtomicUsize::new(0);
1112            let some = parallel(
1113                &items,
1114                threads,
1115                || done.load(Ordering::Relaxed) >= 100,
1116                |&i| {
1117                    done.fetch_add(1, Ordering::Relaxed);
1118                    i
1119                },
1120            );
1121            // At least 100, plus at most one per thread already under way.
1122            assert!((100..100 + threads).contains(&some.len()), "{}", some.len());
1123            assert_eq!(some, (0..some.len()).collect::<Vec<_>>());
1124        }
1125        assert_eq!(
1126            parallel(&[] as &[u8], 4, || false, |&b| b),
1127            Vec::<u8>::new()
1128        );
1129    }
1130
1131    #[test]
1132    fn a_chunk_ends_with_the_file_that_fills_it() {
1133        assert_eq!(chunk_len(&[]), 0);
1134        assert_eq!(chunk_len(&[1, 2, 3]), 3);
1135        assert_eq!(chunk_len(&[CHUNK_BYTES, 1]), 1);
1136        assert_eq!(chunk_len(&[CHUNK_BYTES - 1, 1, 1]), 2);
1137        assert_eq!(chunk_len(&[CHUNK_BYTES - 2, 1, 1]), 3);
1138        assert_eq!(chunk_len(&[0, CHUNK_BYTES - 1, 0, 2, 5]), 4);
1139    }
1140
1141    #[test]
1142    fn take_chunk_respects_shares() {
1143        let dir = std::env::temp_dir().join(format!("jsonvet-chunk-{}", std::process::id()));
1144        std::fs::create_dir_all(&dir).expect("dir");
1145        let f1 = dir.join("1.json");
1146        let f2 = dir.join("2.json");
1147        std::fs::write(&f1, "{}").expect("write");
1148        std::fs::write(&f2, "{}").expect("write");
1149        let settings = Arc::new(Settings::default());
1150        let job1: Job = ((settings.clone(), None), f1.into_os_string());
1151        let job2: Job = ((settings.clone(), None), f2.into_os_string());
1152        let rest = [job1, job2];
1153        let mut ahead = Vec::new();
1154        let shares = [CHUNK_BYTES, CHUNK_BYTES];
1155        let taken = take_chunk(&mut ahead, &rest, Some(&shares), 1, &|_, _| false);
1156        assert_eq!(taken.len(), 1);
1157        assert_eq!(ahead, []);
1158        let _ = std::fs::remove_dir_all(&dir);
1159    }
1160
1161    #[test]
1162    fn a_file_counts_its_size_twenty_times_with_a_schema() {
1163        let dir = std::env::temp_dir().join(format!("jsonvet-share-{}", std::process::id()));
1164        std::fs::create_dir_all(&dir).expect("a temp dir");
1165        let path = dir.join("a.json");
1166        std::fs::write(&path, " ".repeat(1000)).expect("write");
1167        let path = path.as_os_str();
1168        assert_eq!(schema_share(path), 1000 * SCHEMA_BYTES);
1169        std::fs::write(path, " ".repeat(CHUNK_BYTES / SCHEMA_BYTES + 1)).expect("write");
1170        assert_eq!(schema_share(path), CHUNK_BYTES, "capped");
1171        assert_eq!(schema_share(dir.join("gone.json").as_os_str()), 0);
1172        assert_eq!(schema_share(std::ffi::OsStr::new("-")), CHUNK_BYTES);
1173        let _ = std::fs::remove_dir_all(&dir);
1174    }
1175
1176    #[test]
1177    fn frames_show_on_a_terminal_and_color_follows_the_option_then_the_environment() {
1178        use super::{Format, Look, Terminal, look};
1179        let terminal = |tty, color| Terminal { tty, color };
1180        // Off a terminal, `color_forced_off_a_terminal_keeps_one_line_per_problem` in
1181        // tests/cli.rs covers each case end to end.
1182        let frames = |color| Look {
1183            frames: true,
1184            color,
1185        };
1186        let lines = Look {
1187            frames: false,
1188            color: false,
1189        };
1190        let cases = [
1191            (Format::Text, None, terminal(true, None), frames(true)),
1192            (
1193                Format::Text,
1194                None,
1195                terminal(true, Some(false)),
1196                frames(false),
1197            ),
1198            (
1199                Format::Text,
1200                Some(false),
1201                terminal(true, Some(true)),
1202                frames(false),
1203            ),
1204            (Format::Sarif, Some(true), terminal(true, None), lines),
1205            (Format::Json, Some(true), terminal(true, None), lines),
1206        ];
1207        for (format, color, terminal, want) in cases {
1208            assert_eq!(
1209                look(format, color, terminal),
1210                want,
1211                "{format:?} {color:?} {terminal:?}"
1212            );
1213        }
1214    }
1215
1216    #[test]
1217    fn the_summary_counts_problems_and_files() {
1218        let dir = std::env::temp_dir().join(format!("jsonvet-summary-{}", std::process::id()));
1219        std::fs::create_dir_all(&dir).expect("a temp dir");
1220        let dup = dir.join("dup.json");
1221        let ok = dir.join("ok.json");
1222        std::fs::write(&dup, "{\"a\": 1, \"a\": 2}").expect("write");
1223        std::fs::write(&ok, "{}").expect("write");
1224        let run = |summary: bool, files: &[&std::path::Path]| {
1225            let mut out = Vec::new();
1226            let args = ["--no-config".into()]
1227                .into_iter()
1228                .chain(files.iter().map(|f| f.as_os_str().to_owned()));
1229            let terminal = super::Terminal {
1230                tty: summary,
1231                color: Some(false),
1232            };
1233            let code = super::run_with(args, false, terminal, &mut out).expect("a check");
1234            (code, String::from_utf8(out).expect("UTF-8"))
1235        };
1236        let (code, out) = run(true, &[&dup, &ok]);
1237        assert_eq!(code, 1);
1238        assert!(out.ends_with("\n1 error in 1 of 2 files\n"), "{out}");
1239        // A file that cannot be read counts as a file with an error.
1240        let gone = dir.join("gone.json");
1241        // The clean file last, so counting it instead of a file with problems shows.
1242        let dup2 = dir.join("dup2.json");
1243        std::fs::write(&dup2, "{\"a\": 1, \"a\": 2}").expect("write");
1244        let (_, out) = run(true, &[&dup, &gone, &dup2, &ok]);
1245        assert!(out.ends_with("\n3 errors in 3 of 4 files\n"), "{out}");
1246        assert_eq!(run(true, &[&ok]).1, "no problems in 1 file\n");
1247        // No summary off a terminal, nor for no files.
1248        assert!(!run(false, &[&dup]).1.contains(" in 1 of 1 file"));
1249        assert_eq!(run(true, &[]).1, "");
1250        // SARIF and JSON stay one document on a terminal too.
1251        for format in ["sarif", "json"] {
1252            let args = ["--no-config", "--format", format]
1253                .map(std::ffi::OsString::from)
1254                .into_iter()
1255                .chain([dup.clone().into_os_string()]);
1256            let mut out = Vec::new();
1257            let terminal = super::Terminal {
1258                tty: true,
1259                color: None,
1260            };
1261            super::run_with(args, false, terminal, &mut out).expect("a check");
1262            let out = String::from_utf8(out).expect("UTF-8");
1263            assert!(
1264                serde_json::from_str::<serde_json::Value>(&out).is_ok(),
1265                "{out}"
1266            );
1267        }
1268        let _ = std::fs::remove_dir_all(&dir);
1269    }
1270
1271    /// Text output takes a translation; SARIF and JSON stay English with one in place.
1272    #[test]
1273    fn a_translation_reaches_text_output_only() {
1274        let dir = std::env::temp_dir().join(format!("jsonvet-locale-{}", std::process::id()));
1275        std::fs::create_dir_all(&dir).expect("a temp dir");
1276        let dup = dir.join("dup.json");
1277        std::fs::write(&dup, "{\"a\": 1, \"a\": 2}").expect("write");
1278        crate::messages::use_translation(
1279            "\"duplicate-key\" = \"XX {path}\"\n\"related.first-at\" = \"XX {line}:{column}\"\n",
1280        );
1281        let run = |format: &str| {
1282            let args = ["--no-config", "--format", format]
1283                .map(std::ffi::OsString::from)
1284                .into_iter()
1285                .chain([dup.clone().into_os_string()]);
1286            let mut out = Vec::new();
1287            super::run_with(args, false, super::Terminal::default(), &mut out).expect("a check");
1288            String::from_utf8(out).expect("UTF-8")
1289        };
1290        let text = run("text");
1291        assert!(text.contains("XX $.a (XX 1:2)"), "{text}");
1292        for format in ["json", "sarif"] {
1293            let out = run(format);
1294            assert!(out.contains("duplicate key $.a (first at 1:2)"), "{out}");
1295            assert!(!out.contains("XX"), "{out}");
1296        }
1297        let _ = std::fs::remove_dir_all(&dir);
1298    }
1299
1300    /// A JSON Lines file and a `--schema` error get the same code frames on a terminal as any
1301    /// other problem, at the line they are on.
1302    #[test]
1303    fn json_lines_and_schema_errors_get_code_frames_on_a_terminal() {
1304        let dir = std::env::temp_dir().join(format!("jsonvet-frames-{}", std::process::id()));
1305        std::fs::create_dir_all(&dir).expect("a temp dir");
1306        let lines = dir.join("l.jsonl");
1307        let schema = dir.join("s.json");
1308        let data = dir.join("d.json");
1309        std::fs::write(&lines, "{\"a\": 1}\n{\"a\": True}\n").expect("write");
1310        std::fs::write(&schema, r#"{"properties": {"a": {"type": "string"}}}"#).expect("write");
1311        std::fs::write(&data, "{\n  \"a\": 1\n}\n").expect("write");
1312        let run = |args: &[&std::ffi::OsStr]| {
1313            let args = ["--no-config".into()]
1314                .into_iter()
1315                .chain(args.iter().map(|a| (*a).to_owned()));
1316            let terminal = super::Terminal {
1317                tty: true,
1318                color: Some(false),
1319            };
1320            let mut out = Vec::new();
1321            let code = super::run_with(args, false, terminal, &mut out).expect("a check");
1322            let out = String::from_utf8(out).expect("UTF-8");
1323            (
1324                code,
1325                out.replace(
1326                    &format!("{}{}", dir.display(), std::path::MAIN_SEPARATOR),
1327                    "",
1328                ),
1329            )
1330        };
1331        assert_eq!(
1332            run(&[lines.as_os_str()]),
1333            (
1334                1,
1335                "error[syntax]: expected a value, found `True`; did you mean `true`?\n \
1336                 --> l.jsonl:2:7\n  |\n2 | {\"a\": True}\n  |       ^^^^\n  |\n  = help: https://github.com/simonvanlierde/jsonvet/blob/main/docs/usage.md#syntax\n\n\
1337                 1 error in 1 of 1 file\n"
1338                    .to_owned()
1339            )
1340        );
1341        assert_eq!(
1342            run(&["--schema".as_ref(), schema.as_os_str(), data.as_os_str()]),
1343            (
1344                1,
1345                "error[schema]: 1 is not of type \"string\" (at $.a)\n \
1346                 --> d.json:2:8\n  |\n2 |   \"a\": 1\n  |        ^\n  |\n  = help: https://github.com/simonvanlierde/jsonvet/blob/main/docs/usage.md#schema\n\n\
1347                 1 error in 1 of 1 file\n"
1348                    .to_owned()
1349            )
1350        );
1351        let _ = std::fs::remove_dir_all(&dir);
1352    }
1353
1354    #[test]
1355    fn the_summary_names_errors_and_warnings_together() {
1356        let counts = |errors, warnings| super::Counts {
1357            errors,
1358            warnings,
1359            files: 1,
1360        };
1361        assert_eq!(
1362            counts(1, 1).summary(2),
1363            "1 error and 1 warning in 1 of 2 files"
1364        );
1365        assert_eq!(counts(0, 2).summary(1), "2 warnings in 1 of 1 file");
1366    }
1367
1368    #[test]
1369    fn a_line_separator_ends_a_frame_line_only_in_a_json5_file() {
1370        let dir = std::env::temp_dir().join(format!("jsonvet-u2028-{}", std::process::id()));
1371        std::fs::create_dir_all(&dir).expect("a temp dir");
1372        let frame = |name: &str| {
1373            let file = dir.join(name);
1374            std::fs::write(&file, "{\"a\": \"x\u{2028}y\", \"a\": 2}\n").expect("write");
1375            let mut out = Vec::new();
1376            let args = ["--no-config".into(), file.into_os_string()];
1377            let terminal = super::Terminal {
1378                tty: true,
1379                color: Some(false),
1380            };
1381            super::run_with(args, false, terminal, &mut out).expect("a check");
1382            String::from_utf8(out).expect("UTF-8")
1383        };
1384        let five = frame("a.json5");
1385        // Both the duplicate and the first copy, whose line ends at the separator.
1386        assert!(five.contains("\n2 | y\", \"a\": 2}\n"), "{five}");
1387        assert!(five.contains("\n1 | {\"a\": \"x\n"), "{five}");
1388        let other = frame("a.jsonc");
1389        // The frame shows U+2028 as a replacement character, on the one line.
1390        assert!(
1391            other
1392                .lines()
1393                .any(|l| l.starts_with("1 | {\"a\": \"x\u{FFFD}y\", \"a\": 2}")),
1394            "{other}"
1395        );
1396        let _ = std::fs::remove_dir_all(&dir);
1397    }
1398
1399    #[test]
1400    fn a_panic_on_the_big_stack_carries_on_in_the_caller() {
1401        static RUNS: AtomicUsize = AtomicUsize::new(0);
1402        let panic = std::panic::catch_unwind(|| {
1403            super::on_big_stack(|| -> u8 {
1404                RUNS.fetch_add(1, Ordering::Relaxed);
1405                panic!("on the big stack")
1406            })
1407        })
1408        .expect_err("the panic carries on");
1409        assert_eq!(panic.downcast_ref::<&str>(), Some(&"on the big stack"));
1410        assert_eq!(RUNS.load(Ordering::Relaxed), 1);
1411    }
1412}