use crate::ui::theme::{ThemeEntry, ThemeStyle};
use owo_colors::OwoColorize;
use std::collections::HashMap;
use std::io::{self, Write};
use anyhow::Result;
use diffy::{create_patch, Line};
pub fn print_diff<W: Write>(
original_content: &str,
sanitized_content: &str,
writer: &mut W,
theme_map: &HashMap<ThemeEntry, ThemeStyle>,
enable_colors: bool, ) -> Result<()> {
let diff_header = get_styled_text("\n--- Diff View ---", ThemeEntry::DiffHeader, theme_map, true);
writeln!(io::stderr(), "{}", diff_header)?;
let patch = create_patch(original_content, sanitized_content);
for hunk in patch.hunks() {
for line_change in hunk.lines() {
let content_str = match line_change {
Line::Delete(s) => s,
Line::Insert(s) => s,
Line::Context(s) => s,
};
let s_with_actual_newlines = content_str.replace("\\n", "\n");
for segment in s_with_actual_newlines.lines() {
match line_change {
Line::Delete(_) => {
if enable_colors {
writeln!(writer, "{}{}", "-".red(), segment.red())?;
} else {
writeln!(writer, "-{}", segment)?;
}
}
Line::Insert(_) => {
if enable_colors {
writeln!(writer, "{}{}", "+".green(), segment.green())?;
} else {
writeln!(writer, "+{}", segment)?;
}
}
Line::Context(_) => {
writeln!(writer, " {}", segment)?;
}
}
}
}
}
writeln!(io::stderr(), "{}", get_styled_text("-----------------", ThemeEntry::DiffHeader, theme_map, true))?;
Ok(())
}
fn get_styled_text(
text: &str,
entry: ThemeEntry,
theme_map: &HashMap<ThemeEntry, ThemeStyle>,
enable_colors: bool,
) -> String {
if enable_colors {
if let Some(style) = theme_map.get(&entry) {
if let Some(color) = &style.fg {
return text.color(color.to_ansi_color()).to_string();
}
}
text.color(owo_colors::AnsiColors::White).to_string()
} else {
text.to_string()
}
}