//! Unified diff encoder. //! //! Mirror image of [`crate::decode`]: takes a [`DiffDocument`] tree and emits //! Git-style unified-diff text. Round-tripping `decode` → `encode` is //! byte-for-byte for any document the decoder accepted, including the //! preamble and the raw header lines preserved on each [`crate::FileHeader`]. use std::io::{self, Write}; use crate::document::{DiffDocument, DiffLine, DiffLineKind, FileDiff, FileKind, Hunk, HunkHeader}; /// Encodes a value as unified-diff text. pub trait Encode { /// Writes the unified-diff representation to `out`. fn encode(&self, out: &mut impl Write) -> io::Result<()>; /// Returns the unified-diff representation as a `String`. fn to_unified_string(&self) -> io::Result { let mut out = Vec::new(); self.encode(&mut out)?; String::from_utf8(out).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) } } impl Encode for DiffDocument { fn encode(&self, out: &mut impl Write) -> io::Result<()> { if let Some(commit) = &self.commit { write!(out, "{commit}")?; } for file in &self.files { file.encode(out)?; } Ok(()) } } impl Encode for FileDiff { fn encode(&self, out: &mut impl Write) -> io::Result<()> { for line in &self.header.raw { writeln!(out, "{line}")?; } if !self.header.is_binary() && self.header.kind != FileKind::ModeChanged { for hunk in &self.hunks { hunk.encode(out)?; } } Ok(()) } } impl Encode for Hunk { fn encode(&self, out: &mut impl Write) -> io::Result<()> { self.header.encode(out)?; for line in &self.lines { line.encode(out)?; } Ok(()) } } impl Encode for HunkHeader { fn encode(&self, out: &mut impl Write) -> io::Result<()> { let old = if self.old_size == 1 { self.old_line_no.to_string() } else { format!("{},{}", self.old_line_no, self.old_size) }; let new = if self.new_size == 1 { self.new_line_no.to_string() } else { format!("{},{}", self.new_line_no, self.new_size) }; if self.text.is_empty() { writeln!(out, "@@ -{old} +{new} @@") } else { writeln!(out, "@@ -{old} +{new} @@ {}", self.text) } } } impl Encode for DiffLine { fn encode(&self, out: &mut impl Write) -> io::Result<()> { match self.kind { DiffLineKind::Context => writeln!(out, " {}", self.text), DiffLineKind::Addition => writeln!(out, "+{}", self.text), DiffLineKind::Deletion => writeln!(out, "-{}", self.text), DiffLineKind::NoNewline => writeln!(out, "\\ No newline at end of file"), } } } #[cfg(test)] #[allow(clippy::expect_used)] mod tests { use super::*; use crate::{Decode, DiffDocument, HunkHeader}; const PATCH: &str = "\ diff --git a/a.txt b/a.txt index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644 --- a/a.txt +++ b/a.txt @@ -1,3 +1,4 @@ one +two three -four +five diff --git a/b.txt b/b.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29e69de29e69de29e69de29e69de29e69de --- /dev/null +++ b/b.txt @@ -0,0 +1 @@ +new "; #[test] fn round_trips_a_full_patch() { let doc = DiffDocument::decode_str(PATCH).expect("parses"); assert_eq!(doc.to_unified_string().expect("encodes"), PATCH); } #[test] fn round_trips_a_binary_patch_without_encoding_its_synthetic_hunk() { let patch = "\ diff --git a/image.png b/image.png index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 Binary files a/image.png and b/image.png differ "; let doc = DiffDocument::decode_str(patch).expect("parses"); assert_eq!(doc.to_unified_string().expect("encodes"), patch); } #[test] fn round_trips_with_preamble() { let with_preamble = format!( "commit 1234567890abcdef1234567890abcdef12345678\nGood signature\nAuthor: A\n\n{PATCH}" ); let doc = DiffDocument::decode_str(&with_preamble).expect("parses"); assert_eq!(doc.to_unified_string().expect("encodes"), with_preamble); } #[test] fn hunk_header_omits_size_when_one() { let header = HunkHeader::decode_str("@@ -7 +8 @@ fn f").expect("parses"); assert_eq!( header.to_unified_string().expect("encodes"), "@@ -7 +8 @@ fn f\n" ); } #[test] fn encodes_a_single_hunk_for_git_apply() { let doc = DiffDocument::decode_str(PATCH).expect("parses"); let only_first = doc.files[0].selected([0]); assert!( only_first .to_unified_string() .expect("encodes") .starts_with("diff --git") ); } }