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 7898192..6178079 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 0000000..e69de29
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!("commit abc\nAuthor: A\n\n{PATCH}");
126 let doc = DiffDocument::decode_str(&with_preamble).expect("parses");
127
128 assert_eq!(doc.to_unified_string().expect("encodes"), with_preamble);
129 }
130
131 #[test]
132 fn hunk_header_omits_size_when_one() {
133 let header = HunkHeader::decode_str("@@ -7 +8 @@ fn f").expect("parses");
134
135 assert_eq!(
136 header.to_unified_string().expect("encodes"),
137 "@@ -7 +8 @@ fn f\n"
138 );
139 }
140
141 #[test]
142 fn encodes_a_single_hunk_for_git_apply() {
143 let doc = DiffDocument::decode_str(PATCH).expect("parses");
144 let only_first = doc.files[0].selected([0]);
145
146 assert!(
147 only_first
148 .to_unified_string()
149 .expect("encodes")
150 .starts_with("diff --git")
151 );
152 }
153}