use super::OutputFormatter;
use crate::config::OutputConfig;
use crate::search::SearchResult;
use anyhow::Result;
use serde_json;
use std::io::Write;
pub struct JsonFormatter {
pretty: bool,
}
impl JsonFormatter {
pub fn new(pretty: bool) -> Self {
Self { pretty }
}
}
impl OutputFormatter for JsonFormatter {
fn format<W: Write>(
&self,
results: &[SearchResult],
writer: &mut W,
_config: &OutputConfig,
) -> Result<()> {
let results_with_matches: Vec<_> = results
.iter()
.filter(|r| !r.matches.is_empty())
.collect();
if self.pretty {
serde_json::to_writer_pretty(writer, &results_with_matches)?;
} else {
serde_json::to_writer(writer, &results_with_matches)?;
}
Ok(())
}
}