use std::ffi::OsStr;
use std::fmt::Write as _;
use std::path::Path;
use jsonvet::{Location, Severity, is_hidden};
use crate::output::escape_utf16;
use crate::rules;
pub(crate) const UNREADABLE: &str = "unreadable";
pub(crate) const SCHEMA: &str = "schema";
pub(crate) const MAX_RESULTS: usize = 25_000;
pub(crate) fn dropped_message(dropped: usize) -> String {
format!("{dropped} more results not listed: SARIF output keeps the first {MAX_RESULTS}")
}
pub(crate) fn result(
file: &OsStr,
rule: &str,
severity: Severity,
message: &str,
at: 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),
);
if let Some((first, text)) = related {
let _ = write!(
json,
r#","relatedLocations":[{{{},"message":{{"text":{}}}}}]"#,
physical(file, first),
string(text)
);
}
json.push('}');
json
}
pub(crate) fn level(severity: Severity) -> &'static str {
if severity == Severity::Error {
"error"
} else {
"warning"
}
}
pub(crate) fn document(results: &[String], dropped: usize) -> String {
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();
let invocations = if dropped == 0 {
String::new()
} else {
format!(
r#""invocations":[{{"executionSuccessful":true,"toolExecutionNotifications":[{{"level":"warning","message":{{"text":{}}}}}]}}],"#,
string(&dropped_message(dropped))
)
};
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://github.com/simonvanlierde/jsonvet","rules":[{}]}}}},"#,
r#""originalUriBaseIds":{{"%SRCROOT%":{{"description":{{"text":"#,
r#""the working directory jsonvet ran in"}}}}}},"#,
r#""columnKind":"unicodeCodePoints",{}"results":[{}]}}]}}"#
),
env!("CARGO_PKG_VERSION"),
rules.join(","),
invocations,
results.join(",")
)
}
fn physical(file: &OsStr, at: Location) -> String {
let (uri, base) = uri(file);
let base = if base {
r#","uriBaseId":"%SRCROOT%""#
} else {
""
};
format!(
r#""physicalLocation":{{"artifactLocation":{{"uri":{}{base}}},"region":{{"startLine":{},"startColumn":{}}}}}"#,
string(&uri),
at.line,
at.column
)
}
fn uri(file: &OsStr) -> (String, bool) {
let absolute = Path::new(file).is_absolute();
let path = file.as_encoded_bytes();
let mut uri = String::new();
if absolute {
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
};
if byte.is_ascii_alphanumeric() || b"-._~/".contains(&byte) || (absolute && byte == b':') {
uri.push(char::from(byte));
} else {
let _ = write!(uri, "%{byte:02X}");
}
}
(uri, !absolute)
}
pub(crate) fn string(value: &str) -> String {
let mut json = String::with_capacity(value.len() + 2);
json.push('"');
for c in value.chars() {
match c {
'"' => json.push_str("\\\""),
'\\' => json.push_str("\\\\"),
'[' if json.ends_with("##") => json.push_str("\\u005b"),
c if c.is_control() || is_hidden(c) => escape_utf16(&mut json, c),
c => json.push(c),
}
}
json.push('"');
json
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use super::{string, uri};
#[test]
fn strings_escape_quotes_backslashes_and_control_characters() {
assert_eq!(
string("a\"b\\c\n\u{1}\u{7f}\u{e9}"),
"\"a\\\"b\\\\c\\u000a\\u0001\\u007f\u{e9}\""
);
assert_eq!(
string("\u{85}\u{9f}\u{202e}\u{200b}\u{ad}\u{e0041}"),
"\"\\u0085\\u009f\\u202e\\u200b\\u00ad\\udb40\\udc41\""
);
assert_eq!(string("a b"), "\"a b\"");
assert_eq!(string("##[add-mask]"), "\"##\\u005badd-mask]\"");
}
#[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)
);
}
}