1use 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
18const CONTEXT: usize = 3;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct LineRange {
25 pub start: u32,
26 pub len: u32,
27}
28
29impl LineRange {
30 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 pub fn contains(self, line: u32) -> bool {
42 self.len > 0 && line >= self.start && line < self.start + self.len
43 }
44}
45
46impl 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum DiffKind {
61 Context,
63 Added,
65 Removed,
67}
68
69impl DiffKind {
70 pub fn marker(self) -> char {
72 match self {
73 Self::Context => ' ',
74 Self::Added => '+',
75 Self::Removed => '-',
76 }
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct DiffLine {
84 pub kind: DiffKind,
85 pub text: String,
86}
87
88#[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 pub fn header(&self) -> String {
100 format!("@@ -{} +{} @@", self.old, self.new)
101 }
102}
103
104#[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 pub fn new(path: &Path, before: &str, after: &str) -> Self {
117 Self::between(path, path, before, after)
118 }
119
120 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 pub fn as_str(&self) -> &str {
163 &self.text
164 }
165
166 pub fn hunks(&self) -> &[Hunk] {
168 &self.hunks
169 }
170
171 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 pub fn lines(&self) -> impl Iterator<Item = Line> + '_ {
187 self.lines_from(0)
188 }
189
190 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
213impl 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 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}