jsonvet-cli 3.5.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
//! SARIF 2.1.0 output, for GitHub code scanning and other tools that read static analysis
//! results. The JSON is written by hand.

use std::ffi::OsStr;
use std::fmt::Write as _;
use std::path::Path;

use jsonvet::{Location, Severity};

use crate::output::{level, string};
use crate::rules;

/// A file that could not be read gets its own rule, so it shows as an alert. GitHub code scanning
/// lists tool notifications only on its tool status page, where a failing file is easy to miss.
pub(crate) const UNREADABLE: &str = "unreadable";

/// A value the file's schema rejects. A CLI rule: the library knows no schemas.
pub(crate) const SCHEMA: &str = "schema";

/// GitHub code scanning keeps only the top 5,000 results of a run with more than 25,000, and
/// rejects a run past 1,000,000. The rest are counted in a tool notification instead.
pub(crate) const MAX_RESULTS: usize = 25_000;

/// What the tool notification and stderr say about results past [`MAX_RESULTS`].
pub(crate) fn dropped_message(dropped: usize) -> String {
    format!("{dropped} more results not listed: SARIF output keeps the first {MAX_RESULTS}")
}

/// One result, as a JSON object. `end` is where the problem's text ends, for problems that know
/// it. `related` is a second position with its message, such as a duplicate key's first copy.
pub(crate) fn result(
    file: &OsStr,
    rule: &str,
    severity: Severity,
    message: &str,
    at: Location,
    end: Option<Location>,
    related: Option<(Location, &str)>,
) -> String {
    let mut json = format!(
        r#"{{"ruleId":{},"level":"{}","message":{{"text":{}}},"locations":[{{{}}}]"#,
        string(rule),
        level(severity),
        string(message),
        physical(file, at, end),
    );
    if let Some((first, text)) = related {
        let _ = write!(
            json,
            r#","relatedLocations":[{{{},"message":{{"text":{}}}}}]"#,
            physical(file, first, None),
            string(text)
        );
    }
    json.push('}');
    json
}

/// What comes before the first result: the document, its one run and the rules.
pub(crate) fn start() -> String {
    // GitHub code scanning shows `help` and links `helpUri` on each alert.
    let rules: Vec<String> = rules::ids()
        .map(|id| {
            format!(
                r#"{{"id":{},"shortDescription":{{"text":{}}},"fullDescription":{{"text":{}}},"help":{{"text":{}}},"helpUri":{}}}"#,
                string(id),
                string(rules::description(id)),
                string(&format!("{}.", rules::description(id))),
                string(rules::explanation(id)),
                string(&rules::help_uri(id))
            )
        })
        .collect();
    format!(
        concat!(
            r#"{{"$schema":"https://json.schemastore.org/sarif-2.1.0.json","version":"2.1.0","#,
            r#""runs":[{{"tool":{{"driver":{{"name":"jsonvet","version":"{}","#,
            r#""informationUri":"https://simonvanlierde.com/jsonvet/","rules":[{}]}}}},"#,
            // Relative URIs name `%SRCROOT%`, which SARIF wants declared. It has no `uri`: the
            // working directory's absolute path would make the output differ by machine, and
            // GitHub code scanning resolves it against the checkout.
            r#""originalUriBaseIds":{{"%SRCROOT%":{{"description":{{"text":"#,
            r#""the working directory jsonvet ran in"}}}}}},"#,
            // jsonvet counts columns in code points; SARIF's default is UTF-16 code units.
            r#""columnKind":"unicodeCodePoints","results":["#
        ),
        env!("CARGO_PKG_VERSION"),
        rules.join(","),
    )
}

/// What comes after the last result: a notification counting the `dropped` ones past
/// [`MAX_RESULTS`], and the closing brackets.
pub(crate) fn end(dropped: usize, notes: &[String]) -> String {
    if dropped == 0 && notes.is_empty() {
        return "]}]}".to_owned();
    }
    let dropped = (dropped > 0).then(|| dropped_message(dropped));
    let notes = notes
        .iter()
        .chain(dropped.iter())
        .map(|note| {
            format!(
                r#"{{"level":"warning","message":{{"text":{}}}}}"#,
                string(note)
            )
        })
        .collect::<Vec<_>>()
        .join(",");
    format!(
        r#"],"invocations":[{{"executionSuccessful":true,"toolExecutionNotifications":[{notes}]}}]}}]}}"#
    )
}

/// The `physicalLocation` member of a location object. SARIF's end column is the column just
/// past the region, so an empty region has the start column as its end.
fn physical(file: &OsStr, at: Location, end: Option<Location>) -> String {
    let (uri, base) = uri(file);
    let base = if base {
        r#","uriBaseId":"%SRCROOT%""#
    } else {
        ""
    };
    let end = match end {
        Some(end) if end.line == at.line => format!(r#","endColumn":{}"#, end.column),
        Some(end) => format!(r#","endLine":{},"endColumn":{}"#, end.line, end.column),
        None => String::new(),
    };
    format!(
        r#""physicalLocation":{{"artifactLocation":{{"uri":{}{base}}},"region":{{"startLine":{},"startColumn":{}{end}}}}}"#,
        string(&uri),
        at.line,
        at.column
    )
}

/// The file name as a URI reference, and whether it is relative to the source root. Bytes
/// outside a URI's unreserved set are percent-encoded, so a space or `#` in a name stays part
/// of the path.
fn uri(file: &OsStr) -> (String, bool) {
    let absolute = Path::new(file).is_absolute();
    // The name's own bytes, so a name that is not UTF-8 still points at its file.
    let path = file.as_encoded_bytes();
    let mut uri = String::new();
    if absolute {
        // A Windows path starts with its drive letter, which needs a `/` before it.
        uri.push_str(if path.first() == Some(&b'/') {
            "file://"
        } else {
            "file:///"
        });
    }
    for &byte in path {
        let byte = if cfg!(windows) && byte == b'\\' {
            b'/'
        } else {
            byte
        };
        // `:` stays literal only in an absolute path's drive letter: in the first segment of a
        // relative one it would read as a URI scheme.
        if byte.is_ascii_alphanumeric() || b"-._~/".contains(&byte) || (absolute && byte == b':') {
            uri.push(char::from(byte));
        } else {
            let _ = write!(uri, "%{byte:02X}");
        }
    }
    (uri, !absolute)
}

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

    use super::uri;

    #[test]
    fn relative_paths_stay_relative_and_odd_bytes_are_encoded() {
        assert_eq!(
            uri(OsStr::new("a/b c#1.json")),
            ("a/b%20c%231.json".to_owned(), true)
        );
        assert_eq!(uri(OsStr::new("c:x.json")), ("c%3Ax.json".to_owned(), true));
        #[cfg(unix)]
        assert_eq!(
            uri(OsStr::new("a\\b.json")),
            ("a%5Cb.json".to_owned(), true)
        );
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            assert_eq!(
                uri(OsStr::from_bytes(b"\xe9.json")),
                ("%E9.json".to_owned(), true)
            );
        }
        #[cfg(unix)]
        assert_eq!(
            uri(OsStr::new("/abs/a b:c.json")),
            ("file:///abs/a%20b:c.json".to_owned(), false)
        );
        #[cfg(windows)]
        assert_eq!(
            uri(OsStr::new(r"C:\x\y.json")),
            ("file:///C:/x/y.json".to_owned(), false)
        );
    }
}