jsonvet-cli 3.3.0

The jsonvet command: checks JSON, I-JSON, JSONC, JWCC (HuJSON), JSON5 and JSON Lines files, with JSON Schema checks, SARIF output, fixes and a formatter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! How problems are printed: `file:line:col: severity[rule] message`, plus a GitHub Actions
//! annotation for each when running there, or one SARIF or JSON document for the whole run.

use std::ffi::OsStr;
use std::fmt::Write as _;
use std::io::{self, Write};

use annotate_snippets::Renderer;
use annotate_snippets::renderer::Style;
use jsonvet::{Location, Problem, RelatedKind, Report, Severity, is_hidden};

use crate::frame::{self, Mark, STYLED};
use crate::{json, messages, sarif};

/// The output format, from `--format`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Format {
    Text,
    Sarif,
    Json,
}

/// A file name or message with control characters made visible: a newline would start a line
/// of its own, which GitHub Actions reads as a workflow command when it starts with `::`, and
/// an escape character would reach the terminal. Bidi controls, which reorder how the rest of
/// the line displays, and zero-width characters, which hide part of it, are made visible too.
/// CR and LF show as `\r` and `\n`, the others as `\uXXXX` escapes such as `\u001b`, as
/// JSONPaths in messages show them. The runner also reads its older `##[command]` form anywhere
/// in a line, so the `[` of `##[` shows as `\u005b`.
pub(crate) fn printable(value: &str) -> String {
    let mut shown = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '\r' => shown.push_str("\\r"),
            '\n' => shown.push_str("\\n"),
            c if c.is_control() || is_hidden(c) => escape_utf16(&mut shown, c),
            '[' if shown.ends_with("##") => shown.push_str("\\u005b"),
            c => shown.push(c),
        }
    }
    shown
}

/// Write `c` as `\uXXXX`, or as two of them, a UTF-16 surrogate pair, past U+FFFF, as JSON
/// writes it.
pub(crate) fn escape_utf16(out: &mut String, c: char) {
    for unit in c.encode_utf16(&mut [0; 2]) {
        let _ = write!(out, "\\u{unit:04x}");
    }
}

/// A file name as it starts an output line. A name starting with `::`, after any leading
/// white space as the runner trims it, gets `./` in front, so the line is not a workflow
/// command.
fn line_start(file: &str) -> String {
    let shown = printable(file);
    if shown.trim_start().starts_with("::") {
        format!("./{shown}")
    } else {
        shown
    }
}

/// Escape a [`printable`] value for a GitHub workflow command: `%` always, `:` and `,` in
/// properties such as `file=`. CR and LF never reach it.
fn escape(value: &str, property: bool) -> String {
    let value = value.replace('%', "%25");
    if property {
        value.replace(':', "%3A").replace(',', "%2C")
    } else {
        value
    }
}

/// How text output looks: a code frame for each problem or one line, and whether in color.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Look {
    pub(crate) frames: bool,
    pub(crate) color: bool,
}

/// Where a problem is in its file: the file's report, what a code frame marks, and where the problem ends, for SARIF and annotations, when it ends
/// past its start.
#[derive(Clone, Copy)]
struct Place<'t> {
    report: &'t Report<'t>,
    mark: Mark<'t>,
    end: Option<Location>,
}

pub(crate) struct Printer<W: Write> {
    out: W,
    sink: Sink,
    /// The words for each related place, looked up once rather than for every problem: how the
    /// message names it, with its `{line}` and `{column}`, and the frame's label for it.
    related: [(&'static str, &'static str); 3],
}

/// How many code frames one run draws before the rest of its problems show as lines. A frame
/// costs about 24 µs, against about 1 µs for a line, so 1,000 take about 25 ms and some 10,000
/// lines of terminal, more than anyone reads; past that, frames only slow the run (320,000
/// problems took 7.6 s framed).
pub(crate) const MAX_FRAMES: usize = 1_000;

/// What each format keeps while the run goes on.
enum Sink {
    /// With `annotate`, each problem is also a GitHub Actions annotation. With a renderer, each
    /// problem is a code frame instead of a line, up to [`MAX_FRAMES`], counted in `framed`.
    /// With `color`, a line shows its severity and rule in color.
    Text {
        annotate: bool,
        frames: Option<Renderer>,
        framed: usize,
        color: bool,
    },
    /// How many results were written as they came, and how many past [`sarif::MAX_RESULTS`]
    /// were counted but not written.
    Sarif { written: usize, dropped: usize },
    /// Whether the document has started.
    Json { started: bool },
}

impl<W: Write> Printer<W> {
    pub(crate) fn new(out: W, format: Format, annotate: bool, look: Look) -> Self {
        let sink = match format {
            Format::Text => Sink::Text {
                annotate,
                frames: look.frames.then(|| {
                    if look.color {
                        STYLED
                    } else {
                        Renderer::plain()
                    }
                }),
                framed: 0,
                color: look.color,
            },
            Format::Sarif => Sink::Sarif {
                written: 0,
                dropped: 0,
            },
            Format::Json => Sink::Json { started: false },
        };
        let words = |what, label| (messages::text(what), messages::text(label));
        let related = [
            words("related.first-at", "related.first-copy"),
            words("related.opened-at", "related.opened-here"),
            words("related.started-at", "related.starts-here"),
        ];
        Printer { out, sink, related }
    }

    /// A problem in a file's contents.
    pub(crate) fn problem(
        &mut self,
        file: &OsStr,
        report: &Report<'_>,
        problem: &Problem,
    ) -> io::Result<()> {
        let (offset, end) = (problem.offset(), problem.end());
        let mut message = messages::problem(problem);
        let title = message.len();
        // The related place, named in the message and marked in a frame, SARIF and JSON.
        let related = problem.related().map(|related| {
            let (what, label) = match related.kind {
                RelatedKind::FirstOccurrence => self.related[0],
                RelatedKind::Opened => self.related[1],
                // NOTE: `RelatedKind` is non-exhaustive; `Start` is the only other kind so far.
                _ => self.related[2],
            };
            let at = report.location(related.offset);
            message.push_str(" (");
            let _ = jsonvet::fill(
                &mut message,
                what,
                &[("line", &at.line), ("column", &at.column)],
            );
            message.push(')');
            Mark {
                at,
                span: frame::one_char(report, related.offset),
                label: Some(label),
            }
        });
        let place = Place {
            report,
            mark: Mark {
                at: report.location(offset),
                span: (offset, end),
                label: None,
            },
            end: (end > offset).then(|| report.location(end)),
        };
        self.line(
            file,
            problem.rule().id(),
            problem.severity(),
            (&message, &message[..title]),
            Some(place),
            related,
        )
    }

    /// A value the `--schema` schema rejects, at `offset`. A `summary` of the errors not listed
    /// is left out of SARIF and JSON, where each result is one finding.
    pub(crate) fn schema_error(
        &mut self,
        file: &OsStr,
        report: &Report<'_>,
        offset: usize,
        message: &str,
        summary: bool,
    ) -> io::Result<()> {
        if summary && !matches!(self.sink, Sink::Text { .. }) {
            return Ok(());
        }
        let place = Place {
            report,
            mark: Mark {
                at: report.location(offset),
                span: frame::one_char(report, offset),
                label: None,
            },
            end: None,
        };
        self.line(
            file,
            sarif::SCHEMA,
            Severity::Error,
            (message, message),
            Some(place),
            None,
        )
    }

    /// A file that could not be checked at all.
    pub(crate) fn unreadable(&mut self, file: &OsStr, message: &str) -> io::Result<()> {
        self.line(
            file,
            sarif::UNREADABLE,
            Severity::Error,
            (message, message),
            None,
            None,
        )
    }

    /// One problem, in whichever format: a text line or code frame and maybe an annotation, a
    /// SARIF result or a JSON diagnostic. A code frame's title is the message without the part
    /// naming the related place, which the frame marks instead. `related` always has a label.
    /// With no `place`, for a file that could not be read, the text shows neither a position
    /// nor the rule.
    fn line(
        &mut self,
        file: &OsStr,
        rule: &str,
        severity: Severity,
        (message, frame_title): (&str, &str),
        place: Option<Place<'_>>,
        related: Option<Mark<'_>>,
    ) -> io::Result<()> {
        let at = place.map(|p| p.mark.at);
        let (annotate, frames, color) = match &mut self.sink {
            Sink::Json { started } => {
                if *started {
                    self.out.write_all(b",\n")?;
                } else {
                    self.out.write_all(json::start().as_bytes())?;
                }
                *started = true;
                let diagnostic = json::diagnostic(
                    file,
                    rule,
                    severity,
                    message,
                    place.map(|p| (p.mark.at, p.mark.span.0)),
                    related.and_then(|r| Some((r.at, r.span.0, r.label?))),
                );
                return self.out.write_all(diagnostic.as_bytes());
            }
            Sink::Sarif { written, dropped } => {
                if *written < sarif::MAX_RESULTS {
                    if *written == 0 {
                        self.out.write_all(sarif::start().as_bytes())?;
                    } else {
                        self.out.write_all(b",")?;
                    }
                    *written += 1;
                    // GitHub code scanning needs a line in every result.
                    let at = at.unwrap_or(Location::START);
                    // A point problem, such as a missing `,`, has no end: GitHub leaves `endColumn` out for
                    // it, and so does SARIF.
                    let end = place.and_then(|p| p.end);
                    let related = related.and_then(|r| Some((r.at, r.label?)));
                    let result = sarif::result(file, rule, severity, message, at, end, related);
                    self.out.write_all(result.as_bytes())?;
                } else {
                    *dropped += 1;
                }
                return Ok(());
            }
            Sink::Text {
                annotate,
                frames,
                framed,
                color,
            } => {
                if frames.is_some() && *framed == MAX_FRAMES {
                    *frames = None;
                    let stopped =
                        messages::fill("output.frames-stopped", &[("count", &MAX_FRAMES)]);
                    writeln!(self.out, "jsonvet: {stopped}\n")?;
                }
                *framed += 1;
                (*annotate, frames.as_ref(), *color)
            }
        };
        let file = &file.to_string_lossy();
        // Escaped once, for the line and the annotation alike.
        let message = &printable(message);
        if let Some(renderer) = frames {
            let frame = frame::render(
                renderer,
                file,
                severity,
                rule,
                frame_title,
                place.map(|p| (p.report, p.mark)),
                related,
            );
            // A blank line after each frame keeps one problem apart from the next.
            writeln!(self.out, "{frame}\n")?;
        } else {
            let position = Self::position(at, severity, rule, color);
            writeln!(self.out, "{}{position} {message}", line_start(file))?;
        }
        if !annotate {
            return Ok(());
        }
        let title = match place {
            Some(place) => {
                let at = place.mark.at;
                let mut title = format!(",line={},col={}", at.line, at.column);
                // GitHub's end column is the last column marked, and only on the start's line.
                if let Some(end) = place.end
                    && end.line == at.line
                {
                    let _ = write!(title, ",endColumn={}", end.column - 1);
                }
                let _ = write!(title, ",title=jsonvet ({rule})");
                title
            }
            None => ",title=jsonvet".to_owned(),
        };
        writeln!(
            self.out,
            "::{} file={}{title}::{}",
            sarif::level(severity),
            escape(&printable(file), true),
            escape(message, false)
        )
    }

    /// The part of a text line between the file name and the message, with the severity and
    /// rule in color when `color` is set.
    fn position(at: Option<Location>, severity: Severity, rule: &str, color: bool) -> String {
        let style = match (color, severity) {
            (false, _) => Style::new(),
            (true, Severity::Error) => frame::ERROR,
            (true, _) => frame::WARNING,
        };
        match at {
            Some(at) => format!(
                ":{}:{}: {style}{severity}[{rule}]{style:#}",
                at.line, at.column
            ),
            None => format!(": {style}{severity}{style:#}:"),
        }
    }

    /// A line of text output, such as the summary; nothing in SARIF or JSON.
    pub(crate) fn text_line(&mut self, line: &str) -> io::Result<()> {
        if matches!(self.sink, Sink::Text { .. }) {
            writeln!(self.out, "{line}")?;
        }
        Ok(())
    }

    /// The run's last annotation, a notice with the summary, when annotating. GitHub shows only
    /// the first 10 annotations of a type for each step, and the notice is a type of its own, so
    /// it shows however many problems there are.
    pub(crate) fn summary_annotation(&mut self, summary: &str) -> io::Result<()> {
        if matches!(self.sink, Sink::Text { annotate: true, .. }) {
            writeln!(
                self.out,
                "::notice title=jsonvet::{}",
                escape(&printable(summary), false)
            )?;
        }
        Ok(())
    }

    /// Write what can only come once every file was checked: the end of the SARIF or JSON
    /// document, with SARIF's count of results past the cap.
    pub(crate) fn finish(&mut self) -> io::Result<()> {
        match &self.sink {
            Sink::Text { .. } => {}
            Sink::Json { started: true } => writeln!(self.out, "\n]}}")?,
            Sink::Json { started: false } => writeln!(self.out, "{}]}}", json::start())?,
            Sink::Sarif { written, dropped } => {
                if *dropped > 0 {
                    eprintln!("jsonvet: {}", sarif::dropped_message(*dropped));
                }
                if *written == 0 {
                    self.out.write_all(sarif::start().as_bytes())?;
                }
                writeln!(self.out, "{}", sarif::end(*dropped))?;
            }
        }
        self.out.flush()
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::OsStr;

    use jsonvet::{Config, Dialect, check};

    use super::{Format, Look, MAX_FRAMES, Printer, escape, line_start, printable};

    /// On a terminal in color, each problem is a code frame, with the same color codes on every
    /// platform.
    #[test]
    fn code_frames_in_color() {
        let mut out = Vec::new();
        let mut printer = Printer::new(
            &mut out,
            Format::Text,
            false,
            Look {
                frames: true,
                color: true,
            },
        );
        for (file, text) in [
            ("dup.json", "{\n  \"a\": 1,\n  \"a\": 2\n}\n"),
            ("open.json", "{\"a\": [1, True"),
        ] {
            let report = check(text, &Config::new(Dialect::Json));
            for problem in report.problems() {
                printer
                    .problem(OsStr::new(file), &report, problem)
                    .expect("a write to memory");
            }
        }
        printer
            .unreadable(OsStr::new("gone.json"), "no such file")
            .expect("a write to memory");
        let out = String::from_utf8(out).expect("UTF-8");
        insta::assert_snapshot!(out.replace('\u{1b}', "␛"));
    }

    /// Past [`MAX_FRAMES`] code frames in a run, problems show one line each, after a line that
    /// says so.
    #[test]
    fn code_frames_stop_after_the_cap() {
        let mut out = Vec::new();
        let look = Look {
            frames: true,
            color: false,
        };
        let mut printer = Printer::new(&mut out, Format::Text, false, look);
        // MAX_FRAMES + 1 duplicate keys, over two files: the cap is per run, not per file.
        for text in [
            format!("{{{}}}", vec!["\"a\": 1"; MAX_FRAMES].join(",")),
            "{\"a\": 1, \"a\": 2, \"a\": 3}".to_owned(),
        ] {
            let report = check(&text, &Config::new(Dialect::Json));
            for problem in report.problems() {
                printer
                    .problem(OsStr::new("dup.json"), &report, problem)
                    .expect("a write to memory");
            }
        }
        let out = String::from_utf8(out).expect("UTF-8");
        let frames = out.matches("\nerror[duplicate-key]: ").count() + 1;
        assert_eq!(frames, MAX_FRAMES, "{out}");
        let (_, rest) = out
            .split_once(&format!(
                "jsonvet: {MAX_FRAMES} problems shown with their lines; the rest show one line each"
            ))
            .expect("the line saying frames stopped");
        let lines: Vec<&str> = rest.lines().skip(2).collect();
        assert_eq!(
            lines,
            ["dup.json:1:18: error[duplicate-key] duplicate key $.a (first at 1:2)"],
            "{rest}"
        );
    }

    #[test]
    fn messages_stay_on_one_line_and_annotation_fields_are_percent_encoded() {
        assert_eq!(printable("a\n::warning::x"), "a\\n::warning::x");
        assert_eq!(
            printable("a\u{1b}]8;;x\u{7}\u{9b}b"),
            "a\\u001b]8;;x\\u0007\\u009bb"
        );
        assert_eq!(
            printable("a\u{1b}[31m\u{7}\t\u{9b}"),
            "a\\u001b[31m\\u0007\\u0009\\u009b"
        );
        assert_eq!(escape(&printable("a\u{1b}]0;x"), false), "a\\u001b]0;x");
        assert_eq!(printable("a##[add-mask]b#[c"), "a##\\u005badd-mask]b#[c");
        assert_eq!(printable("C:\\x\te.json"), "C:\\x\\u0009e.json");
        assert_eq!(
            printable("a\u{202e}b\u{2066}c\u{200f}d\u{61c}e\u{200d}f"),
            "a\\u202eb\\u2066c\\u200fd\\u061ce\\u200df"
        );
        assert_eq!(escape("50% a", false), "50%25 a");
        assert_eq!(escape("a:b,c", true), "a%3Ab%2Cc");
        assert_eq!(escape("not strict: x, y", false), "not strict: x, y");
        assert_eq!(
            printable("x\u{202e}y\u{200b}\u{feff}\u{2028}"),
            "x\\u202ey\\u200b\\ufeff\\u2028"
        );
    }

    #[test]
    fn soft_hyphens_word_joiners_and_tag_characters_are_hidden() {
        assert_eq!(
            printable("a\u{ad}b\u{180e}c\u{2060}d\u{2064}e"),
            "a\\u00adb\\u180ec\\u2060d\\u2064e"
        );
        // Past U+FFFF, as a UTF-16 surrogate pair, the way JSON writes it.
        assert_eq!(
            printable("\u{e0000}x\u{e007f}"),
            "\\udb40\\udc00x\\udb40\\udc7f"
        );
        assert_eq!(printable("\u{e0080}\u{2065}é"), "\u{e0080}\u{2065}é");
    }

    #[test]
    fn a_name_never_starts_a_workflow_command() {
        assert_eq!(
            line_start("::stop-commands::t.json"),
            "./::stop-commands::t.json"
        );
        assert_eq!(
            line_start("\u{3000} ::add-mask::x"),
            "./\u{3000} ::add-mask::x"
        );
        assert_eq!(line_start("\n::error::x"), "\\n::error::x");
        assert_eq!(line_start("a::b.json"), "a::b.json");
    }
}