Skip to main content

vvv_engine/protocol/
diff.rs

1//! A file's change as a unified diff: the rendered text that crosses the
2//! wire, and the hunks it is made of.
3//!
4//! The text is the wire form (a `--json` client reads it, `Serialize` writes
5//! it) and nothing here parses it. The model is [`Hunk`]/[`DiffLine`], built
6//! straight from `similar` when the diff is made: the `@@` grammar exists only
7//! as the text `similar` formats, never as something a consumer re-reads.
8
9use std::fmt;
10use std::ops::Range;
11use std::path::Path;
12
13use serde::{Deserialize, Serialize};
14use similar::{ChangeTag, TextDiff};
15
16use super::display::{Line, Role};
17
18/// How many context lines `similar` keeps around a change.
19const CONTEXT: usize = 3;
20
21/// Lines a hunk covers in one file: `start` is the first line (1-based) and
22/// `len` how many it spans. `len == 0` is an insertion between lines.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct LineRange {
25    pub start: u32,
26    pub len: u32,
27}
28
29impl LineRange {
30    /// The range `side` picks out of a hunk's ops, 1-based.
31    fn of(ops: &[similar::DiffOp], side: fn(&similar::DiffOp) -> Range<usize>) -> Self {
32        let first = side(&ops[0]).start;
33        let last = side(ops.last().expect("a hunk has an op")).end;
34        Self {
35            start: first as u32 + 1,
36            len: (last - first) as u32,
37        }
38    }
39
40    /// Whether 1-based `line` falls inside the range.
41    pub fn contains(self, line: u32) -> bool {
42        self.len > 0 && line >= self.start && line < self.start + self.len
43    }
44}
45
46/// The unified-diff spelling of a range: `start`, `start,len`, and the line
47/// before an empty one.
48impl fmt::Display for LineRange {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self.len {
51            0 => write!(f, "{},0", self.start.saturating_sub(1)),
52            1 => write!(f, "{}", self.start),
53            n => write!(f, "{},{n}", self.start),
54        }
55    }
56}
57
58/// What a diff line does to the file.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum DiffKind {
61    /// Unchanged, kept for context.
62    Context,
63    /// Added by the change.
64    Added,
65    /// Removed by the change.
66    Removed,
67}
68
69impl DiffKind {
70    /// The unified-diff marker a line of this kind is prefixed with.
71    pub fn marker(self) -> char {
72        match self {
73            Self::Context => ' ',
74            Self::Added => '+',
75            Self::Removed => '-',
76        }
77    }
78}
79
80/// One line of a hunk: its kind and its text, without the `+`/`-`/space
81/// marker. Its number is implied by the hunk's range and the lines before it.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct DiffLine {
84    pub kind: DiffKind,
85    pub text: String,
86}
87
88/// One `@@` block: the lines it covers in each file, and the lines
89/// themselves.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Hunk {
92    pub old: LineRange,
93    pub new: LineRange,
94    pub lines: Vec<DiffLine>,
95}
96
97impl Hunk {
98    /// The `@@ -a,b +c,d @@` header.
99    pub fn header(&self) -> String {
100        format!("@@ -{} +{} @@", self.old, self.new)
101    }
102}
103
104/// One file's change: the unified diff text (the wire) and its hunks (the
105/// model).
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
108#[serde(into = "String", from = "String")]
109pub struct Diff {
110    text: String,
111    hunks: Vec<Hunk>,
112}
113
114impl Diff {
115    /// A diff whose before and after headers name the same path.
116    pub fn new(path: &Path, before: &str, after: &str) -> Self {
117        Self::between(path, path, before, after)
118    }
119
120    /// The diff of `before` → `after`, its hunks read straight from `similar`.
121    pub fn between(old_path: &Path, new_path: &Path, before: &str, after: &str) -> Self {
122        let changes = TextDiff::from_lines(before, after);
123        let mut rendered = changes.unified_diff();
124        rendered.context_radius(CONTEXT).header(
125            &format!("a/{}", old_path.display()),
126            &format!("b/{}", new_path.display()),
127        );
128        let hunks = rendered
129            .iter_hunks()
130            .map(|hunk| {
131                let ops = hunk.ops();
132                let lines = hunk
133                    .iter_changes()
134                    .map(|change| DiffLine {
135                        kind: match change.tag() {
136                            ChangeTag::Equal => DiffKind::Context,
137                            ChangeTag::Delete => DiffKind::Removed,
138                            ChangeTag::Insert => DiffKind::Added,
139                        },
140                        text: change.value().trim_end_matches(['\r', '\n']).to_owned(),
141                    })
142                    .collect();
143                Hunk {
144                    old: LineRange::of(ops, |op| op.old_range()),
145                    new: LineRange::of(ops, |op| op.new_range()),
146                    lines,
147                }
148            })
149            .collect();
150        let mut text = rendered.to_string();
151        if text.is_empty() && old_path != new_path {
152            text = format!(
153                "--- a/{}\n+++ b/{}\n",
154                old_path.display(),
155                new_path.display()
156            );
157        }
158        Self { text, hunks }
159    }
160
161    /// The rendered unified diff: the wire form.
162    pub fn as_str(&self) -> &str {
163        &self.text
164    }
165
166    /// The hunks the diff is made of.
167    pub fn hunks(&self) -> &[Hunk] {
168        &self.hunks
169    }
170
171    /// The index of the hunk opening at or before 1-based old-file `line`;
172    /// the first when the line falls before them all.
173    pub fn opening(&self, line: u32) -> usize {
174        let mut open = 0;
175        for (i, hunk) in self.hunks.iter().enumerate() {
176            if hunk.old.start > line {
177                break;
178            }
179            open = i;
180        }
181        open
182    }
183
184    /// The whole diff as display lines: each hunk's header, then its lines
185    /// with their `+`/`-`/space marker.
186    pub fn lines(&self) -> impl Iterator<Item = Line> + '_ {
187        self.lines_from(0)
188    }
189
190    /// The display lines from the hunk opening at or before 1-based `line`.
191    pub fn lines_from(&self, line: u32) -> impl Iterator<Item = Line> + '_ {
192        self.hunks[self.opening(line)..].iter().flat_map(|hunk| {
193            std::iter::once(Line::single(Role::Hunk, hunk.header())).chain(hunk.lines.iter().map(
194                |line| {
195                    let role = match line.kind {
196                        DiffKind::Context => Role::Plain,
197                        DiffKind::Added => Role::Added,
198                        DiffKind::Removed => Role::Removed,
199                    };
200                    Line::single(role, format!("{}{}", line.kind.marker(), line.text))
201                },
202            ))
203        })
204    }
205}
206
207impl From<Diff> for String {
208    fn from(diff: Diff) -> Self {
209        diff.text
210    }
211}
212
213/// The text alone: the hunks a deserialized diff never had are left empty,
214/// which is fine because only `Serialize` crosses a wire.
215impl From<String> for Diff {
216    fn from(text: String) -> Self {
217        Self {
218            text,
219            hunks: Vec::new(),
220        }
221    }
222}
223
224impl fmt::Display for Diff {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        f.write_str(&self.text)
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use std::path::Path;
233
234    use super::*;
235
236    /// A twelve-line file with a change on line 2 and another on line 10:
237    /// two hunks, `old.start` 1 and 7.
238    fn two_hunks() -> Diff {
239        let before: String = (1..=12).map(|k| format!("line {k}\n")).collect();
240        let after = before
241            .replace("line 2\n", "line 2 changed\n")
242            .replace("line 10\n", "line 10 changed\n");
243        Diff::between(Path::new("a.rs"), Path::new("a.rs"), &before, &after)
244    }
245
246    #[test]
247    fn hunks_carry_their_ranges_and_lines() {
248        let diff = two_hunks();
249        assert_eq!(diff.hunks().len(), 2);
250        let first = &diff.hunks()[0];
251        assert_eq!((first.old.start, first.old.len), (1, 5));
252        assert!(first.old.contains(2), "the changed line is in the range");
253        assert!(
254            first
255                .lines
256                .iter()
257                .any(|l| l.kind == DiffKind::Removed && l.text == "line 2")
258        );
259        assert!(
260            first
261                .lines
262                .iter()
263                .any(|l| l.kind == DiffKind::Added && l.text == "line 2 changed")
264        );
265    }
266
267    #[test]
268    fn opening_finds_the_hunk_at_or_before_a_line() {
269        let diff = two_hunks();
270        assert_eq!(diff.opening(1), 0, "before the first hunk, the first hunk");
271        assert_eq!(diff.opening(2), 0);
272        assert_eq!(diff.opening(7), 1, "the second hunk opens at old line 7");
273        assert_eq!(diff.opening(10), 1);
274    }
275
276    #[test]
277    fn a_single_line_hunk_has_no_count_in_its_header() {
278        let diff = Diff::new(Path::new("a.rs"), "a\n", "b\n");
279        let hunk = &diff.hunks()[0];
280        assert_eq!(hunk.header(), "@@ -1 +1 @@");
281        assert_eq!((hunk.old.start, hunk.old.len), (1, 1));
282    }
283}