diffo 0.2.0

Semantic diffing for Rust structs via serde
Documentation
//! Output formatters for diffs.
//!
//! This module provides various formatters to display diffs in different formats:
//! - Pretty: Human-readable colored terminal output
//! - JSON: JSON representation
//! - JSON Patch: RFC 6902 JSON Patch format
//! - Markdown: Markdown table format

mod json;
mod markdown;
mod patch;
mod pretty;

pub use json::JsonFormatter;
pub use markdown::MarkdownFormatter;
pub use patch::JsonPatchFormatter;
pub use pretty::PrettyFormatter;

use crate::{Diff, FormatError};

/// Trait for formatting diffs into various representations.
pub trait Formatter {
    /// Format the diff into a string.
    fn format(&self, diff: &Diff) -> Result<String, FormatError>;
}

// Convenience methods on Diff
impl Diff {
    /// Format as pretty colored output.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::diff;
    ///
    /// let old = vec![1, 2, 3];
    /// let new = vec![1, 2, 4];
    ///
    /// let d = diff(&old, &new).unwrap();
    /// println!("{}", d.to_pretty());
    /// ```
    pub fn to_pretty(&self) -> String {
        PrettyFormatter::new()
            .format(self)
            .unwrap_or_else(|_| String::from("Error formatting diff"))
    }

    /// Format as JSON.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::diff;
    ///
    /// let old = vec![1, 2, 3];
    /// let new = vec![1, 2, 4];
    ///
    /// let d = diff(&old, &new).unwrap();
    /// let json = d.to_json().unwrap();
    /// ```
    pub fn to_json(&self) -> Result<String, FormatError> {
        JsonFormatter::new().pretty().format(self)
    }

    /// Format as JSON Patch (RFC 6902).
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::diff;
    ///
    /// let old = vec![1, 2, 3];
    /// let new = vec![1, 2, 4];
    ///
    /// let d = diff(&old, &new).unwrap();
    /// let patch = d.to_json_patch().unwrap();
    /// ```
    pub fn to_json_patch(&self) -> Result<String, FormatError> {
        JsonPatchFormatter::new().format(self)
    }

    /// Format as Markdown table.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::diff;
    ///
    /// let old = vec![1, 2, 3];
    /// let new = vec![1, 2, 4];
    ///
    /// let d = diff(&old, &new).unwrap();
    /// let markdown = d.to_markdown().unwrap();
    /// ```
    pub fn to_markdown(&self) -> Result<String, FormatError> {
        MarkdownFormatter::new().format(self)
    }
}