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;
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,
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
}
pub(crate) fn start() -> 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();
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":[{}]}}}},"#,
r#""originalUriBaseIds":{{"%SRCROOT%":{{"description":{{"text":"#,
r#""the working directory jsonvet ran in"}}}}}},"#,
r#""columnKind":"unicodeCodePoints","results":["#
),
env!("CARGO_PKG_VERSION"),
rules.join(","),
)
}
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}]}}]}}]}}"#
)
}
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
)
}
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)
}
#[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)
);
}
}