jtool-grep 0.2.1

notebook-specific grep tool for jtool
Documentation
//! JSON Lines output formatter

use super::OutputFormatter;
use crate::types::GrepResult;
use anyhow::Result;
use serde_json::json;

/// JSON Lines output formatter (one JSON object per line)
pub struct JsonlFormatter;

impl JsonlFormatter {
    pub fn new() -> Self {
        Self
    }
}

impl Default for JsonlFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl OutputFormatter for JsonlFormatter {
    fn format_result(&self, result: &GrepResult) -> Result<String> {
        let mut output = String::new();

        for m in &result.matches {
            let obj = json!({
                "notebook": result.notebook,
                "cell_index": m.cell_index,
                "cell_number": m.cell_number,
                "execution_count": m.execution_count,
                "match_type": m.match_type,
                "line_index": m.line_index,
                "line_number": m.line_number,
                "matched_text": m.matched_text,
                "line_content": m.line_content,
            });

            output.push_str(&serde_json::to_string(&obj)?);
            output.push('\n');
        }

        Ok(output)
    }

    fn format_results(&self, results: &[GrepResult]) -> Result<String> {
        let mut output = String::new();

        for result in results {
            for m in &result.matches {
                let obj = json!({
                    "notebook": result.notebook,
                    "cell_index": m.cell_index,
                    "cell_number": m.cell_number,
                    "execution_count": m.execution_count,
                    "match_type": m.match_type,
                    "line_index": m.line_index,
                    "line_number": m.line_number,
                    "matched_text": m.matched_text,
                    "line_content": m.line_content,
                });

                output.push_str(&serde_json::to_string(&obj)?);
                output.push('\n');
            }
        }

        Ok(output)
    }
}