Krolyxon
Commit 8f664fb

ferreniumsrcgitdiff.rs

408 lines · 12.9 KB · Rust

1//! What a commit changed: the file list (with renames) against its first
2//! parent, and line diffs grouped into hunks.
3
4use std::hash::Hash;
5
6use anyhow::Context;
7use gix::bstr::BString;
8use gix::diff::blob::{Algorithm, Diff, InternedInput};
9use gix::object::tree::diff::ChangeDetached;
10
11use super::ObjectId;
12use super::tree::EntryKind;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Status {
16 Added,
17 Deleted,
18 Modified,
19 Renamed,
20 Copied,
21}
22
23/// One side of a change.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Side {
26 pub path: BString,
27 pub oid: ObjectId,
28 pub kind: EntryKind,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct FileChange {
33 pub status: Status,
34 pub old: Option<Side>,
35 pub new: Option<Side>,
36 /// Rename/copy similarity in percent.
37 pub similarity: Option<u8>,
38}
39
40impl FileChange {
41 /// The path after the change (before it, for deletions).
42 pub fn path(&self) -> &BString {
43 match (&self.new, &self.old) {
44 (Some(side), _) | (None, Some(side)) => &side.path,
45 (None, None) => unreachable!("a change has at least one side"),
46 }
47 }
48}
49
50#[derive(Debug, Clone)]
51pub struct Changes {
52 /// The first parent; `None` for a root commit (compared to nothing).
53 pub parent: Option<ObjectId>,
54 pub files: Vec<FileChange>,
55}
56
57/// Files changed by `commit` relative to its first parent, renames
58/// detected like `git diff -M` (50% similarity), sorted by path.
59pub fn changes(repo: &gix::Repository, commit: ObjectId) -> anyhow::Result<Changes> {
60 let commit = repo.find_commit(commit).context("commit not found")?;
61 let new_tree = commit.tree().context("commit has no tree")?;
62 let parent = commit.parent_ids().next().map(|id| id.detach());
63 let old_tree = match parent {
64 Some(id) => Some(
65 repo.find_commit(id)
66 .context("parent commit not found")?
67 .tree()
68 .context("parent has no tree")?,
69 ),
70 None => None,
71 };
72 let options = gix::diff::Options::default().with_rewrites(Some(Default::default()));
73 let changes = repo
74 .diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), options)
75 .context("cannot diff trees")?;
76
77 let side = |path: &BString, mode: gix::object::tree::EntryMode, oid: ObjectId| {
78 (!mode.is_tree()).then(|| Side {
79 path: path.clone(),
80 oid,
81 kind: EntryKind::from_gix(mode.kind()),
82 })
83 };
84 let mut files = Vec::new();
85 for change in changes {
86 let file = match change {
87 ChangeDetached::Addition {
88 location,
89 entry_mode,
90 id,
91 ..
92 } => FileChange {
93 status: Status::Added,
94 old: None,
95 new: side(&location, entry_mode, id),
96 similarity: None,
97 },
98 ChangeDetached::Deletion {
99 location,
100 entry_mode,
101 id,
102 ..
103 } => FileChange {
104 status: Status::Deleted,
105 old: side(&location, entry_mode, id),
106 new: None,
107 similarity: None,
108 },
109 ChangeDetached::Modification {
110 location,
111 previous_entry_mode,
112 previous_id,
113 entry_mode,
114 id,
115 } => {
116 // A tree replaced by a file (or the reverse) is just an
117 // addition (deletion) of the file. A file that changed type
118 // (regular, symlink, submodule) is both, as git shows it.
119 let old = side(&location, previous_entry_mode, previous_id);
120 let new = side(&location, entry_mode, id);
121 match (old, new) {
122 (Some(old), Some(new)) if !old.kind.same_type(new.kind) => {
123 files.push(FileChange {
124 status: Status::Deleted,
125 old: Some(old),
126 new: None,
127 similarity: None,
128 });
129 FileChange {
130 status: Status::Added,
131 old: None,
132 new: Some(new),
133 similarity: None,
134 }
135 }
136 (old, new) => FileChange {
137 status: match (&old, &new) {
138 (None, _) => Status::Added,
139 (_, None) => Status::Deleted,
140 _ => Status::Modified,
141 },
142 old,
143 new,
144 similarity: None,
145 },
146 }
147 }
148 ChangeDetached::Rewrite {
149 source_location,
150 source_entry_mode,
151 source_id,
152 diff,
153 entry_mode,
154 id,
155 location,
156 copy,
157 ..
158 } => FileChange {
159 status: if copy {
160 Status::Copied
161 } else {
162 Status::Renamed
163 },
164 old: side(&source_location, source_entry_mode, source_id),
165 new: side(&location, entry_mode, id),
166 // Truncated like git's percentage.
167 similarity: Some(
168 diff.map_or(100.0, |d| d.similarity * 100.0)
169 .floor()
170 .clamp(0.0, 100.0) as u8,
171 ),
172 },
173 };
174 if file.old.is_some() || file.new.is_some() {
175 files.push(file);
176 }
177 }
178 files.sort_by(|a, b| a.path().cmp(b.path()));
179 Ok(Changes { parent, files })
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum LineKind {
184 Context,
185 Added,
186 Removed,
187}
188
189/// A line in a hunk; `old`/`new` are 0-based line indexes into each side.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub struct Line {
192 pub kind: LineKind,
193 pub old: Option<u32>,
194 pub new: Option<u32>,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct Hunk {
199 /// 0-based first line and length on each side.
200 pub old_start: u32,
201 pub old_len: u32,
202 pub new_start: u32,
203 pub new_len: u32,
204 pub lines: Vec<Line>,
205 /// The enclosing "function" line git shows after the ranges.
206 pub func: Option<String>,
207}
208
209impl Hunk {
210 /// `@@ -1,5 +1,8 @@ fn main() {`
211 pub fn header(&self) -> String {
212 fn range(start: u32, len: u32) -> String {
213 match len {
214 0 => format!("{start},0"),
215 1 => format!("{}", start + 1),
216 _ => format!("{},{len}", start + 1),
217 }
218 }
219 let mut header = format!(
220 "@@ -{} +{} @@",
221 range(self.old_start, self.old_len),
222 range(self.new_start, self.new_len)
223 );
224 if let Some(func) = &self.func {
225 header.push(' ');
226 header.push_str(func);
227 }
228 header
229 }
230}
231
232#[derive(Debug, Clone, Default, PartialEq, Eq)]
233pub struct LineDiff {
234 pub hunks: Vec<Hunk>,
235 pub added: u32,
236 pub removed: u32,
237}
238
239/// Line diff of two texts split into lines (each with its `\n`, so a
240/// missing final newline counts as a change), with `context` unchanged
241/// lines around each change. `ignore_ws` compares lines with all
242/// whitespace removed, like `git diff -w`.
243pub fn lines(old: &[&str], new: &[&str], context: u32, ignore_ws: bool) -> LineDiff {
244 let diff = if ignore_ws {
245 let strip =
246 |l: &&str| -> Vec<u8> { l.bytes().filter(|b| !b.is_ascii_whitespace()).collect() };
247 compute(old.iter().map(strip), new.iter().map(strip))
248 } else {
249 compute(
250 old.iter().map(|l| l.as_bytes()),
251 new.iter().map(|l| l.as_bytes()),
252 )
253 };
254 let raw: Vec<_> = diff.hunks().collect();
255 let (old_len, new_len) = (old.len() as u32, new.len() as u32);
256 let mut out = LineDiff {
257 hunks: Vec::new(),
258 added: diff.count_additions(),
259 removed: diff.count_removals(),
260 };
261 let mut i = 0;
262 while i < raw.len() {
263 // Merge changes whose context would overlap or touch.
264 let mut j = i;
265 while j + 1 < raw.len() && raw[j + 1].before.start - raw[j].before.end <= 2 * context {
266 j += 1;
267 }
268 let lead = raw[i].before.start.min(context);
269 let (old_start, new_start) = (raw[i].before.start - lead, raw[i].after.start - lead);
270 let trail = context.min(old_len - raw[j].before.end);
271 let (old_end, new_end) = (raw[j].before.end + trail, raw[j].after.end + trail);
272 debug_assert!(new_end <= new_len);
273
274 let mut lines = Vec::new();
275 let (mut o, mut n) = (old_start, new_start);
276 for h in &raw[i..=j] {
277 while o < h.before.start {
278 lines.push(Line {
279 kind: LineKind::Context,
280 old: Some(o),
281 new: Some(n),
282 });
283 o += 1;
284 n += 1;
285 }
286 for r in h.before.clone() {
287 lines.push(Line {
288 kind: LineKind::Removed,
289 old: Some(r),
290 new: None,
291 });
292 }
293 for a in h.after.clone() {
294 lines.push(Line {
295 kind: LineKind::Added,
296 old: None,
297 new: Some(a),
298 });
299 }
300 o = h.before.end;
301 n = h.after.end;
302 }
303 while o < old_end {
304 lines.push(Line {
305 kind: LineKind::Context,
306 old: Some(o),
307 new: Some(n),
308 });
309 o += 1;
310 n += 1;
311 }
312 out.hunks.push(Hunk {
313 old_start,
314 old_len: old_end - old_start,
315 new_start,
316 new_len: new_end - new_start,
317 lines,
318 func: func_line(&old[..old_start as usize]),
319 });
320 i = j + 1;
321 }
322 out
323}
324
325/// git's default hunk-header context: the closest line above the hunk
326/// that starts like an identifier, trailing whitespace trimmed, at most
327/// 80 bytes.
328fn func_line(before: &[&str]) -> Option<String> {
329 let line = before.iter().rev().find(|l| {
330 l.bytes()
331 .next()
332 .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_' || b == b'$')
333 })?;
334 let bytes = &line.as_bytes()[..line.len().min(80)];
335 let end = bytes
336 .iter()
337 .rposition(|b| !b.is_ascii_whitespace())
338 .map_or(0, |i| i + 1);
339 Some(String::from_utf8_lossy(&bytes[..end]).into_owned())
340}
341
342fn compute<T: AsRef<[u8]> + Hash + Eq + Default>(
343 old: impl Iterator<Item = T>,
344 new: impl Iterator<Item = T>,
345) -> Diff {
346 let mut input = InternedInput::default();
347 input.update_before(old);
348 input.update_after(new);
349 gix::diff::blob::diff_with_slider_heuristics(Algorithm::Myers, &input)
350}
351
352/// Git's mode for an entry kind (`100644`, …).
353pub fn mode(kind: EntryKind) -> &'static str {
354 match kind {
355 EntryKind::Blob => "100644",
356 EntryKind::Executable => "100755",
357 EntryKind::Symlink => "120000",
358 EntryKind::Submodule => "160000",
359 EntryKind::Tree => "040000",
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 fn split(text: &str) -> Vec<&str> {
368 text.split_inclusive('\n').collect()
369 }
370
371 #[test]
372 fn hunks_with_context_and_merging() {
373 let old = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
374 let new = "a\nB\nc\nd\ne\nf\ng\nh\ni\nJ\n";
375 let diff = lines(&split(old), &split(new), 3, false);
376 assert_eq!((diff.added, diff.removed), (2, 2));
377 // Changes at lines 2 and 10 are 7 apart: with 3 lines of context
378 // they stay separate hunks.
379 assert_eq!(diff.hunks.len(), 2);
380 assert_eq!(diff.hunks[0].header(), "@@ -1,5 +1,5 @@");
381 assert_eq!(diff.hunks[1].header(), "@@ -7,4 +7,4 @@ f");
382 // With more context they merge.
383 let diff = lines(&split(old), &split(new), 4, false);
384 assert_eq!(diff.hunks.len(), 1);
385 assert_eq!(diff.hunks[0].header(), "@@ -1,10 +1,10 @@");
386 }
387
388 #[test]
389 fn additions_to_empty_and_whitespace() {
390 let diff = lines(&[], &split("x\ny\n"), 3, false);
391 assert_eq!(diff.hunks[0].header(), "@@ -0,0 +1,2 @@");
392 assert_eq!(diff.hunks[0].lines.len(), 2);
393
394 let old = split("fn x() {\n a;\n}\n");
395 let new = split("fn x() {\n\ta;\n}\n");
396 assert_eq!(lines(&old, &new, 3, false).added, 1);
397 let ws = lines(&old, &new, 3, true);
398 assert!(ws.hunks.is_empty());
399 assert_eq!((ws.added, ws.removed), (0, 0));
400 }
401
402 #[test]
403 fn missing_final_newline_is_a_change() {
404 let diff = lines(&split("a\nb\n"), &split("a\nb"), 0, false);
405 assert_eq!((diff.added, diff.removed), (1, 1));
406 assert_eq!(diff.hunks[0].header(), "@@ -2 +2 @@ a");
407 }
408}