use std::collections::BTreeSet;
use serde_json::json;
use crate::offence::Offence;
use crate::offence_threshold::OffenceThreshold;
pub struct JsonPrinter {
files_scanned: usize,
threshold: OffenceThreshold,
}
impl JsonPrinter {
pub fn new(files_scanned: usize) -> Self {
Self {
files_scanned,
threshold: OffenceThreshold::default(),
}
}
pub fn with_threshold(self, threshold: OffenceThreshold) -> Self {
Self { threshold, ..self }
}
pub fn render(&self, offences: &[Offence]) -> String {
let broken: BTreeSet<&str> = offences.iter().map(|offence| offence.rule).collect();
let shown = self.threshold.kept(offences);
let document = json!({
"files_scanned": self.files_scanned,
"offences_found": offences.len(),
"offences_reported": shown.len(),
"offences_omitted": self.threshold.omitted(offences),
"offence_threshold": self.threshold.limit(),
"rules_broken": broken.len(),
"offences": shown,
});
serde_json::to_string_pretty(&document).unwrap_or_default()
}
pub fn print(&self, offences: &[Offence]) {
println!("{}", self.render(offences));
}
}