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, Write};
5use std::path::Path;
6use std::process::ExitCode;
7
8use jsonvet::Severity;
9
10mod args;
11mod glob;
12mod output;
13mod settings;
14
15use args::{Command, ConfigSource};
16use output::Printer;
17use settings::Settings;
18
19/// Run the command with the process's arguments and environment, and return its exit code.
20pub fn run() -> ExitCode {
21    let annotate = std::env::var_os("GITHUB_ACTIONS").is_some_and(|v| v == "true");
22    let stdout = io::stdout().lock();
23    match run_with(
24        std::env::args_os().skip(1),
25        annotate,
26        BufWriter::new(stdout),
27    ) {
28        Ok(code) => ExitCode::from(code),
29        Err(message) => {
30            eprintln!("jsonvet: {message}");
31            ExitCode::from(2)
32        }
33    }
34}
35
36/// The command, with its inputs passed in: 0 when no file has an error, 1 when one does.
37/// A usage error comes back as `Err`, which `run` turns into exit status 2.
38fn run_with(
39    args: impl IntoIterator<Item = OsString>,
40    annotate: bool,
41    out: impl Write,
42) -> Result<u8, String> {
43    let args =
44        match args::parse(args).map_err(|e| format!("{e}\n\nRun `jsonvet --help` for usage."))? {
45            Command::Help => return print(out, args::HELP),
46            Command::Version => return print(out, concat!("jsonvet ", env!("CARGO_PKG_VERSION"))),
47            Command::Check(args) => args,
48        };
49    let from_file = match &args.config {
50        ConfigSource::None => Settings::default(),
51        ConfigSource::File(path) => settings::load(path)?,
52        ConfigSource::Search => {
53            let cwd = std::env::current_dir()
54                .map_err(|e| format!("cannot read the working directory: {e}"))?;
55            match settings::discover(&cwd) {
56                Some(path) => settings::load(&path)?,
57                None => Settings::default(),
58            }
59        }
60    };
61    let settings = from_file.overridden_by(args.settings);
62
63    let mut printer = Printer { out, annotate };
64    let (mut failed, mut warnings) = (false, 0usize);
65    for file in &args.files {
66        let result = check_file(file, &settings, &mut printer)
67            .map_err(|e| format!("cannot write output: {e}"))?;
68        failed |= result.errors > 0;
69        warnings += result.warnings;
70    }
71    printer
72        .out
73        .flush()
74        .map_err(|e| format!("cannot write output: {e}"))?;
75    let too_many_warnings = args.max_warnings.is_some_and(|max| warnings > max);
76    Ok(u8::from(failed || too_many_warnings))
77}
78
79#[derive(Default)]
80struct Counts {
81    errors: usize,
82    warnings: usize,
83}
84
85/// Check one file. The name is opened as given; its lossy UTF-8 form is only for output and
86/// glob matching.
87fn check_file(
88    file: &OsStr,
89    settings: &Settings,
90    printer: &mut Printer<impl Write>,
91) -> io::Result<Counts> {
92    let text = match std::fs::read(Path::new(file)) {
93        Ok(bytes) => String::from_utf8(bytes)
94            .map_err(|e| format!("not valid UTF-8 (byte {})", e.utf8_error().valid_up_to())),
95        Err(e) if e.kind() == io::ErrorKind::NotFound => Err("no such file".to_owned()),
96        Err(e) => Err(format!("cannot read: {e}")),
97    };
98    let name = file.to_string_lossy();
99    let file = name.as_ref();
100    let text = match text {
101        Ok(text) => text,
102        Err(message) => {
103            printer.unreadable(file, &message)?;
104            return Ok(Counts {
105                errors: 1,
106                warnings: 0,
107            });
108        }
109    };
110    let report = jsonvet::check(&text, &settings.config_for(file));
111    let mut counts = Counts::default();
112    for problem in report.problems() {
113        printer.problem(file, &report, problem)?;
114        match problem.severity() {
115            Severity::Error => counts.errors += 1,
116            Severity::Warning => counts.warnings += 1,
117            Severity::Off => {}
118        }
119    }
120    Ok(counts)
121}
122
123fn print(mut out: impl Write, text: &str) -> Result<u8, String> {
124    writeln!(out, "{text}").map_err(|e| format!("cannot write output: {e}"))?;
125    Ok(0)
126}