use crate::lint::{LINTS, Level, Lint};
use crate::render::Skipped;
#[cfg(test)]
use crate::render::Violation;
use crate::render::escape::{inner, string};
use crate::render::line::{Line, Spelled};
use crate::render::name::Codepoint;
use crate::render::order;
use crate::render::value::{Fields, array, field, list, number, object};
use crate::scan::{Position, Unreadable};
use std::borrow::Cow;
use std::fmt::Write;
const SCHEMA: &str = "https://json.schemastore.org/sarif-2.1.0.json";
const VERSION: &str = "2.1.0";
const NAME: &str = "ctrm";
#[cfg(test)]
pub(super) fn check(
items: &[Violation<'_>],
skipped: &[Skipped<'_>],
) -> String {
check_lines(order::lines(items), skipped)
}
pub(super) fn check_lines<'a>(
lines: impl IntoIterator<Item = Line<'a>>,
skipped: &[Skipped<'_>],
) -> String {
let mut out = String::new();
let mut log = Fields::open(&mut out);
log.text("$schema", SCHEMA);
log.text("version", VERSION);
let runs = log.key("runs");
runs.push('[');
run(runs, lines, skipped);
runs.push(']');
log.close();
out
}
fn run<'a>(
out: &mut String,
lines: impl IntoIterator<Item = Line<'a>>,
skipped: &[Skipped<'_>],
) {
let mut fields = Fields::open(out);
fields.raw("tool", &object(&[field("driver", &driver())]));
fields.text("columnKind", "unicodeCodePoints");
results(fields.key("results"), lines);
fields.raw("invocations", &array(&[invocation(skipped)]));
fields.close();
}
const RESULT_BYTES: usize = 240;
fn results<'a>(out: &mut String, lines: impl IntoIterator<Item = Line<'a>>) {
let lines = lines.into_iter();
out.reserve(lines.size_hint().0.saturating_mul(RESULT_BYTES));
let mut path = Spelled::new(uri_literal);
list(out, lines, |out, item| {
result(out, path.of(item.path), item)
});
}
fn uri_literal(path: &str) -> Cow<'_, str> {
Cow::Owned(string(&uri(path)))
}
fn driver() -> String {
let mut fields = vec![
field("name", &string(NAME)),
field("version", &string(env!("CARGO_PKG_VERSION"))),
];
if let Some(uri) = information_uri(env!("CARGO_PKG_REPOSITORY")) {
fields.push(field("informationUri", &string(uri)));
}
let rules: Vec<String> = LINTS.iter().copied().map(rule).collect();
fields.push(field("rules", &array(&rules)));
object(&fields)
}
fn information_uri(repository: &str) -> Option<&str> {
(!repository.is_empty()).then_some(repository)
}
fn rule(lint: Lint) -> String {
let level = field("level", &string(level_word(lint.default_level())));
let tags = field("tags", &array(&[string(lint.group.name())]));
object(&[
field("id", &string(lint.name)),
field("defaultConfiguration", &object(&[level])),
field("properties", &object(&[tags])),
])
}
const fn level_word(level: Level) -> &'static str {
match level {
Level::Allow => "none",
Level::Warn => "warning",
Level::Deny | Level::Forbid => "error",
}
}
fn result(out: &mut String, uri: &str, item: Line<'_>) {
let mut fields = Fields::open(out);
fields.text("ruleId", item.finding.lint.name);
fields.text("level", level_word(item.finding.level));
message(fields.key("message"), item);
locations(fields.key("locations"), uri, item.finding.hit.position);
fields.close();
}
fn locations(out: &mut String, uri: &str, at: Position) {
out.push_str(r#"[{"physicalLocation":{"artifactLocation":{"uri":"#);
out.push_str(uri);
out.push_str(r#"},"region":"#);
region(out, at);
out.push_str("}}]");
}
fn message(out: &mut String, item: Line<'_>) {
let found = Codepoint(item.finding.hit.character);
let _infallible = write!(out, "{{\"text\":\"{found} (set in force: ");
inner(out, item.set);
out.push_str(")\"}");
}
fn text(words: &str) -> String {
object(&[field("text", &string(words))])
}
fn region(out: &mut String, at: Position) {
let mut fields = Fields::open(out);
fields.number("startLine", at.line);
fields.number("startColumn", at.column);
fields.number("endColumn", at.column.saturating_add(1));
fields.close();
}
fn location(path: &str, region: Option<String>) -> String {
let artifact = object(&[field("uri", &string(&uri(path)))]);
let mut fields = vec![field("artifactLocation", &artifact)];
if let Some(at) = region {
fields.push(field("region", &at));
}
object(&[field("physicalLocation", &object(&fields))])
}
fn uri(path: &str) -> String {
let encoded: String = path.bytes().map(uri_byte).collect();
if path.starts_with('/') {
return format!("file://{encoded}");
}
encoded
}
fn uri_byte(byte: u8) -> String {
if byte.is_ascii_alphanumeric() || b"-._~/".contains(&byte) {
return String::from(char::from(byte));
}
format!("%{byte:02X}")
}
fn invocation(skipped: &[Skipped<'_>]) -> String {
let notes: Vec<String> = order::skipped(skipped)
.into_iter()
.map(notification)
.collect();
object(&[
field("executionSuccessful", "true"),
field("toolExecutionNotifications", &array(¬es)),
])
}
fn notification(item: &Skipped<'_>) -> String {
let (level, words, at) = match item.reason {
Unreadable::NotUtf8 { byte, line, column } => (
"warning",
format!("not read: invalid UTF-8 at {line}:{column}"),
Some(undecoded(line, column, byte)),
),
Unreadable::Binary => ("note", String::from("not read: binary"), None),
};
object(&[
field("level", &string(level)),
field("message", &text(&words)),
field("locations", &array(&[location(item.path, at)])),
])
}
fn undecoded(line: usize, column: usize, byte: usize) -> String {
object(&[
field("startLine", &number(line)),
field("startColumn", &number(column)),
field("byteOffset", &number(byte)),
])
}
#[cfg(test)]
mod tests {
use super::{check, information_uri, level_word, uri};
use crate::lint::{Finding, Group, LINTS, Level, Lint};
use crate::render::{Skipped, Violation};
use crate::scan::{Hit, Position, Unreadable};
const fn outside_set() -> Lint {
crate::lint::OUTSIDE_SET
}
fn hit() -> Hit {
let position = Position {
line: 2,
column: 5,
byte: 7,
};
Hit {
position,
character: '\u{2014}',
}
}
fn em_dash(path: &str, level: Level) -> Violation<'_> {
let (hit, lint) = (hit(), outside_set());
let finding = Finding { hit, lint, level };
Violation {
path,
finding,
set: "ascii",
}
}
fn skip(path: &str, reason: Unreadable) -> Skipped<'_> {
Skipped { path, reason }
}
fn head() -> String {
let rules: Vec<String> = LINTS.iter().map(|l| rule_row(*l)).collect();
format!(
concat!(
r#"{{"$schema":"https://json.schemastore.org/"#,
r#"sarif-2.1.0.json","version":"2.1.0","runs":[{{"tool":"#,
r#"{{"driver":{{"name":"ctrm","version":"{}","#,
r#""informationUri":"{}","rules":[{}]}}}},"#,
r#""columnKind":"unicodeCodePoints","#,
),
env!("CARGO_PKG_VERSION"),
env!("CARGO_PKG_REPOSITORY"),
rules.join(",")
)
}
fn rule_row(lint: Lint) -> String {
let (level, tag) = match lint.group {
Group::Hazard => ("error", "hazard"),
Group::Charset => ("error", "charset"),
Group::Pedantic => ("none", "pedantic"),
};
format!(
concat!(
r#"{{"id":"{}","defaultConfiguration":{{"level":"{}"}},"#,
r#""properties":{{"tags":["{}"]}}}}"#,
),
lint.name, level, tag
)
}
#[test]
fn the_ordinary_violation_is_a_rule() {
let row = concat!(
r#"{"id":"outside-set","#,
r#""defaultConfiguration":{"level":"error"},"#,
r#""properties":{"tags":["charset"]}}"#
);
assert!(head().contains(row), "{}", head());
assert!(check(&[], &[]).starts_with(&head()));
}
#[test]
fn the_log_is_the_contract() {
let expected = concat!(
r#""results":[{"ruleId":"outside-set","level":"error","#,
r#""message":{"text":"U+2014 (set in force: ascii)"},"#,
r#""locations":[{"physicalLocation":{"artifactLocation":{"#,
r#""uri":"src/a.rs"},"region":{"startLine":2,"startColumn":5,"#,
r#""endColumn":6}}}]}],"invocations":[{"#,
r#""executionSuccessful":true,"#,
r#""toolExecutionNotifications":[]}]}]}"#
);
let log = check(&[em_dash("src/a.rs", Level::Deny)], &[]);
assert_eq!(log, format!("{}{expected}", head()));
}
const NOT_UTF8: Unreadable = Unreadable::NotUtf8 {
byte: 17,
line: 1,
column: 18,
};
#[test]
fn unread_files_are_notifications_in_path_order() {
let items =
[skip("b.bin", Unreadable::Binary), skip("a.txt", NOT_UTF8)];
let expected = concat!(
r#""results":[],"invocations":[{"executionSuccessful":true,"#,
r#""toolExecutionNotifications":[{"level":"warning","#,
r#""message":{"text":"not read: invalid UTF-8 at 1:18"},"#,
r#""locations":[{"physicalLocation":{"artifactLocation":{"#,
r#""uri":"a.txt"},"region":{"startLine":1,"startColumn":18,"byteOffset":17}}}]},"#,
r#"{"level":"note","message":{"text":"not read: binary"},"#,
r#""locations":[{"physicalLocation":{"artifactLocation":{"#,
r#""uri":"b.bin"}}}]}]}]}]}"#
);
assert_eq!(check(&[], &items), format!("{}{expected}", head()));
}
#[test]
fn a_warned_finding_is_a_warning_and_results_keep_report_order() {
let items =
[em_dash("b.md", Level::Warn), em_dash("a.md", Level::Forbid)];
let log = check(&items, &[]);
let first = log.find(r#""uri":"a.md""#).unwrap_or(usize::MAX);
let second = log.find(r#""uri":"b.md""#).unwrap_or(0);
assert!(first < second, "{log}");
assert!(log.contains(r#""level":"warning","message""#), "{log}");
}
#[test]
fn levels_map_onto_the_sarif_words() {
assert_eq!(level_word(Level::Forbid), "error");
assert_eq!(level_word(Level::Deny), "error");
assert_eq!(level_word(Level::Warn), "warning");
assert_eq!(level_word(Level::Allow), "none");
}
#[test]
fn a_path_is_percent_encoded_into_a_uri_reference() {
assert_eq!(uri("src/a_b-c.d~e.rs"), "src/a_b-c.d~e.rs");
assert_eq!(uri("my notes/100%.md"), "my%20notes/100%25.md");
assert_eq!(uri("c:d.md"), "c%3Ad.md");
assert_eq!(uri("caf\u{e9}.md"), "caf%C3%A9.md");
}
#[test]
fn an_absolute_path_becomes_a_file_uri() {
assert_eq!(uri("/elsewhere/a.rs"), "file:///elsewhere/a.rs");
}
#[test]
fn an_absent_repository_is_omitted_rather_than_empty() {
assert_eq!(information_uri(""), None);
assert_eq!(
information_uri("https://x.test/r"),
Some("https://x.test/r")
);
}
}