crates/diff/src/encode.rs 4.9 KiB raw
1
//! Unified diff encoder.
2
//!
3
//! Mirror image of [`crate::decode`]: takes a [`DiffDocument`] tree and emits
4
//! Git-style unified-diff text. Round-tripping `decode` → `encode` is
5
//! byte-for-byte for any document the decoder accepted, including the
6
//! preamble and the raw header lines preserved on each [`crate::FileHeader`].
7
8
use std::io::{self, Write};
9
10
use crate::document::{DiffDocument, DiffLine, DiffLineKind, FileDiff, FileKind, Hunk, HunkHeader};
11
12
/// Encodes a value as unified-diff text.
13
pub trait Encode {
14
    /// Writes the unified-diff representation to `out`.
15
    fn encode(&self, out: &mut impl Write) -> io::Result<()>;
16
17
    /// Returns the unified-diff representation as a `String`.
18
    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
25
impl 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
37
impl 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
        if self.header.kind != FileKind::Binary {
43
            for hunk in &self.hunks {
44
                hunk.encode(out)?;
45
            }
46
        }
47
        Ok(())
48
    }
49
}
50
51
impl Encode for Hunk {
52
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
53
        self.header.encode(out)?;
54
        for line in &self.lines {
55
            line.encode(out)?;
56
        }
57
        Ok(())
58
    }
59
}
60
61
impl Encode for HunkHeader {
62
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
63
        let old = if self.old_size == 1 {
64
            self.old_line_no.to_string()
65
        } else {
66
            format!("{},{}", self.old_line_no, self.old_size)
67
        };
68
        let new = if self.new_size == 1 {
69
            self.new_line_no.to_string()
70
        } else {
71
            format!("{},{}", self.new_line_no, self.new_size)
72
        };
73
        if self.text.is_empty() {
74
            writeln!(out, "@@ -{old} +{new} @@")
75
        } else {
76
            writeln!(out, "@@ -{old} +{new} @@ {}", self.text)
77
        }
78
    }
79
}
80
81
impl Encode for DiffLine {
82
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
83
        match self.kind {
84
            DiffLineKind::Context => writeln!(out, " {}", self.text),
85
            DiffLineKind::Addition => writeln!(out, "+{}", self.text),
86
            DiffLineKind::Deletion => writeln!(out, "-{}", self.text),
87
            DiffLineKind::NoNewline => writeln!(out, "\\ No newline at end of file"),
88
        }
89
    }
90
}
91
92
#[cfg(test)]
93
#[allow(clippy::expect_used)]
94
mod tests {
95
    use super::*;
96
    use crate::{Decode, DiffDocument, HunkHeader};
97
98
    const PATCH: &str = "\
99
diff --git a/a.txt b/a.txt
100
index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644
101
--- a/a.txt
102
+++ b/a.txt
103
@@ -1,3 +1,4 @@
104
 one
105
+two
106
 three
107
-four
108
+five
109
diff --git a/b.txt b/b.txt
110
new file mode 100644
111
index 0000000000000000000000000000000000000000..e69de29e69de29e69de29e69de29e69de29e69de
112
--- /dev/null
113
+++ b/b.txt
114
@@ -0,0 +1 @@
115
+new
116
";
117
118
    #[test]
119
    fn round_trips_a_full_patch() {
120
        let doc = DiffDocument::decode_str(PATCH).expect("parses");
121
122
        assert_eq!(doc.to_unified_string().expect("encodes"), PATCH);
123
    }
124
125
    #[test]
126
    fn round_trips_a_binary_patch_without_encoding_its_synthetic_hunk() {
127
        let patch = "\
128
diff --git a/image.png b/image.png
129
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
130
Binary files a/image.png and b/image.png differ
131
";
132
        let doc = DiffDocument::decode_str(patch).expect("parses");
133
134
        assert_eq!(doc.to_unified_string().expect("encodes"), patch);
135
    }
136
137
    #[test]
138
    fn round_trips_with_preamble() {
139
        let with_preamble = format!(
140
            "commit 1234567890abcdef1234567890abcdef12345678\nGood signature\nAuthor: A\n\n{PATCH}"
141
        );
142
        let doc = DiffDocument::decode_str(&with_preamble).expect("parses");
143
144
        assert_eq!(doc.to_unified_string().expect("encodes"), with_preamble);
145
    }
146
147
    #[test]
148
    fn hunk_header_omits_size_when_one() {
149
        let header = HunkHeader::decode_str("@@ -7 +8 @@ fn f").expect("parses");
150
151
        assert_eq!(
152
            header.to_unified_string().expect("encodes"),
153
            "@@ -7 +8 @@ fn f\n"
154
        );
155
    }
156
157
    #[test]
158
    fn encodes_a_single_hunk_for_git_apply() {
159
        let doc = DiffDocument::decode_str(PATCH).expect("parses");
160
        let only_first = doc.files[0].selected([0]);
161
162
        assert!(
163
            only_first
164
                .to_unified_string()
165
                .expect("encodes")
166
                .starts_with("diff --git")
167
        );
168
    }
169
}