opengrep 1.1.0

Advanced AST-aware code search tool with tree-sitter parsing and AI integration capabilities
Documentation
//! JSON output formatter.

use super::OutputFormatter;
use crate::config::OutputConfig;
use crate::search::SearchResult;
use anyhow::Result;
use serde_json;
use std::io::Write;

/// Formats search results as JSON.
pub struct JsonFormatter {
    pretty: bool,
}

impl JsonFormatter {
    /// Creates a new `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(())
    }
}