1use std::io::{self, Write};
9
10use crate::document::{DiffDocument, DiffLine, DiffLineKind, FileDiff, Hunk, HunkHeader};
11
12pub trait Encode {
14 fn encode(&self, out: &mut impl Write) -> io::Result<()>;
16
17 fn to_unified_string(&self) -> io::Result<String> {
19 let mut out = Vec::new();
20 self.encode(&mut out)?;
21 String::from_utf8(out).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
22 }
23}
24
25impl Encode for DiffDocument {
26 fn encode(&self, out: &mut impl Write) -> io::Result<()> {
27 if let Some(commit) = &self.commit {
28 write!(out, "{commit}")?;
29 }
30 for file in &self.files {
31 file.encode(out)?;
32 }
33 Ok(())
34 }
35}
36
37impl Encode for FileDiff {
38 fn encode(&self, out: &mut impl Write) -> io::Result<()> {
39 for line in &self.header.raw {
40 writeln!(out, "{line}")?;
41 }
42 for hunk in &self.hunks {
43 hunk.encode(out)?;
44 }
45 Ok(())
46 }
47}
48
49impl Encode for Hunk {
50 fn encode(&self, out: &mut impl Write) -> io::Result<()> {
51 self.header.encode(out)?;
52 for line in &self.lines {
53 line.encode(out)?;
54 }
55 Ok(())
56 }
57}
58
59impl Encode for HunkHeader {
60 fn encode(&self, out: &mut impl Write) -> io::Result<()> {
61 let old = if self.old_size == 1 {
62 self.old_line_no.to_string()
63 } else {
64 format!("{},{}", self.old_line_no, self.old_size)
65 };
66 let new = if self.new_size == 1 {
67 self.new_line_no.to_string()
68 } else {
69 format!("{},{}", self.new_line_no, self.new_size)
70 };
71 if self.text.is_empty() {
72 writeln!(out, "@@ -{old} +{new} @@")
73 } else {
74 writeln!(out, "@@ -{old} +{new} @@ {}", self.text)
75 }
76 }
77}
78
79impl Encode for DiffLine {
80 fn encode(&self, out: &mut impl Write) -> io::Result<()> {
81 match self.kind {
82 DiffLineKind::Context => writeln!(out, " {}", self.text),
83 DiffLineKind::Addition => writeln!(out, "+{}", self.text),
84 DiffLineKind::Deletion => writeln!(out, "-{}", self.text),
85 DiffLineKind::NoNewline => writeln!(out, "\\ No newline at end of file"),
86 }
87 }
88}
89
90#[cfg(test)]
91#[allow(clippy::expect_used)]
92mod tests {
93 use super::*;
94 use crate::{Decode, DiffDocument, HunkHeader};
95
96 const PATCH: &str = "\
97diff --git a/a.txt b/a.txt
98index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644
99--- a/a.txt
100+++ b/a.txt
101@@ -1,3 +1,4 @@
102 one
103+two
104 three
105-four
106+five
107diff --git a/b.txt b/b.txt
108new file mode 100644
109index 0000000000000000000000000000000000000000..e69de29e69de29e69de29e69de29e69de29e69de
110--- /dev/null
111+++ b/b.txt
112@@ -0,0 +1 @@
113+new
114";
115
116 #[test]
117 fn round_trips_a_full_patch() {
118 let doc = DiffDocument::decode_str(PATCH).expect("parses");
119
120 assert_eq!(doc.to_unified_string().expect("encodes"), PATCH);
121 }
122
123 #[test]
124 fn round_trips_with_preamble() {
125 let with_preamble = format!(
126 "commit 1234567890abcdef1234567890abcdef12345678\nGood signature\nAuthor: A\n\n{PATCH}"
127 );
128 let doc = DiffDocument::decode_str(&with_preamble).expect("parses");
129
130 assert_eq!(doc.to_unified_string().expect("encodes"), with_preamble);
131 }
132
133 #[test]
134 fn hunk_header_omits_size_when_one() {
135 let header = HunkHeader::decode_str("@@ -7 +8 @@ fn f").expect("parses");
136
137 assert_eq!(
138 header.to_unified_string().expect("encodes"),
139 "@@ -7 +8 @@ fn f\n"
140 );
141 }
142
143 #[test]
144 fn encodes_a_single_hunk_for_git_apply() {
145 let doc = DiffDocument::decode_str(PATCH).expect("parses");
146 let only_first = doc.files[0].selected([0]);
147
148 assert!(
149 only_first
150 .to_unified_string()
151 .expect("encodes")
152 .starts_with("diff --git")
153 );
154 }
155}