git.rs

  1use std::ops::Range;
  2
  3use sum_tree::{Bias, SumTree};
  4use text::{Anchor, BufferSnapshot, OffsetRangeExt, Point, Rope, ToOffset, ToPoint};
  5
  6pub use git2 as libgit;
  7use libgit::{
  8    DiffLine as GitDiffLine, DiffLineType as GitDiffLineType, DiffOptions as GitOptions,
  9    Patch as GitPatch,
 10};
 11
 12#[derive(Debug, Clone, Copy)]
 13pub enum DiffHunkStatus {
 14    Added,
 15    Modified,
 16    Removed,
 17}
 18
 19#[derive(Debug, Clone, PartialEq, Eq)]
 20pub struct DiffHunk<T> {
 21    pub buffer_range: Range<T>,
 22    pub head_byte_range: Range<usize>,
 23}
 24
 25impl DiffHunk<u32> {
 26    pub fn status(&self) -> DiffHunkStatus {
 27        if self.head_byte_range.is_empty() {
 28            DiffHunkStatus::Added
 29        } else if self.buffer_range.is_empty() {
 30            DiffHunkStatus::Removed
 31        } else {
 32            DiffHunkStatus::Modified
 33        }
 34    }
 35}
 36
 37impl sum_tree::Item for DiffHunk<Anchor> {
 38    type Summary = DiffHunkSummary;
 39
 40    fn summary(&self) -> Self::Summary {
 41        DiffHunkSummary {
 42            buffer_range: self.buffer_range.clone(),
 43            head_range: self.head_byte_range.clone(),
 44        }
 45    }
 46}
 47
 48#[derive(Debug, Default, Clone)]
 49pub struct DiffHunkSummary {
 50    buffer_range: Range<Anchor>,
 51    head_range: Range<usize>,
 52}
 53
 54impl sum_tree::Summary for DiffHunkSummary {
 55    type Context = text::BufferSnapshot;
 56
 57    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
 58        self.head_range.start = self.head_range.start.min(other.head_range.start);
 59        self.head_range.end = self.head_range.end.max(other.head_range.end);
 60    }
 61}
 62
 63#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
 64struct HunkHeadEnd(usize);
 65
 66impl<'a> sum_tree::Dimension<'a, DiffHunkSummary> for HunkHeadEnd {
 67    fn add_summary(&mut self, summary: &'a DiffHunkSummary, _: &text::BufferSnapshot) {
 68        self.0 = summary.head_range.end;
 69    }
 70
 71    fn from_summary(summary: &'a DiffHunkSummary, _: &text::BufferSnapshot) -> Self {
 72        HunkHeadEnd(summary.head_range.end)
 73    }
 74}
 75
 76#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
 77struct HunkBufferStart(u32);
 78
 79impl<'a> sum_tree::Dimension<'a, DiffHunkSummary> for HunkBufferStart {
 80    fn add_summary(&mut self, summary: &'a DiffHunkSummary, buffer: &text::BufferSnapshot) {
 81        self.0 = summary.buffer_range.start.to_point(buffer).row;
 82    }
 83
 84    fn from_summary(summary: &'a DiffHunkSummary, buffer: &text::BufferSnapshot) -> Self {
 85        HunkBufferStart(summary.buffer_range.start.to_point(buffer).row)
 86    }
 87}
 88
 89#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
 90struct HunkBufferEnd(u32);
 91
 92impl<'a> sum_tree::Dimension<'a, DiffHunkSummary> for HunkBufferEnd {
 93    fn add_summary(&mut self, summary: &'a DiffHunkSummary, buffer: &text::BufferSnapshot) {
 94        self.0 = summary.buffer_range.end.to_point(buffer).row;
 95    }
 96
 97    fn from_summary(summary: &'a DiffHunkSummary, buffer: &text::BufferSnapshot) -> Self {
 98        HunkBufferEnd(summary.buffer_range.end.to_point(buffer).row)
 99    }
100}
101
102struct HunkLineIter<'a, 'b> {
103    patch: &'a GitPatch<'b>,
104    hunk_index: usize,
105    line_index: usize,
106}
107
108impl<'a, 'b> HunkLineIter<'a, 'b> {
109    fn new(patch: &'a GitPatch<'b>, hunk_index: usize) -> Self {
110        HunkLineIter {
111            patch,
112            hunk_index,
113            line_index: 0,
114        }
115    }
116}
117
118impl<'a, 'b> std::iter::Iterator for HunkLineIter<'a, 'b> {
119    type Item = GitDiffLine<'b>;
120
121    fn next(&mut self) -> Option<Self::Item> {
122        if self.line_index >= self.patch.num_lines_in_hunk(self.hunk_index).unwrap() {
123            return None;
124        }
125
126        let line_index = self.line_index;
127        self.line_index += 1;
128        Some(
129            self.patch
130                .line_in_hunk(self.hunk_index, line_index)
131                .unwrap(),
132        )
133    }
134}
135
136#[derive(Clone)]
137pub struct BufferDiffSnapshot {
138    tree: SumTree<DiffHunk<Anchor>>,
139}
140
141impl BufferDiffSnapshot {
142    pub fn hunks_in_range<'a>(
143        &'a self,
144        query_row_range: Range<u32>,
145        buffer: &'a BufferSnapshot,
146    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
147        self.tree.iter().filter_map(move |hunk| {
148            let range = hunk.buffer_range.to_point(&buffer);
149
150            if range.start.row <= query_row_range.end && query_row_range.start <= range.end.row {
151                let end_row = if range.end.column > 0 {
152                    range.end.row + 1
153                } else {
154                    range.end.row
155                };
156
157                Some(DiffHunk {
158                    buffer_range: range.start.row..end_row,
159                    head_byte_range: hunk.head_byte_range.clone(),
160                })
161            } else {
162                None
163            }
164        })
165    }
166
167    #[cfg(test)]
168    fn hunks<'a>(&'a self, text: &'a BufferSnapshot) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
169        self.hunks_in_range(0..u32::MAX, text)
170    }
171}
172
173pub struct BufferDiff {
174    last_update_version: clock::Global,
175    snapshot: BufferDiffSnapshot,
176}
177
178impl BufferDiff {
179    pub fn new(head_text: &Option<String>, buffer: &text::BufferSnapshot) -> BufferDiff {
180        let mut tree = SumTree::new();
181
182        if let Some(head_text) = head_text {
183            let buffer_text = buffer.as_rope().to_string();
184            let patch = Self::diff(&head_text, &buffer_text);
185
186            if let Some(patch) = patch {
187                for hunk_index in 0..patch.num_hunks() {
188                    let hunk = Self::process_patch_hunk(&patch, hunk_index, buffer);
189                    tree.push(hunk, buffer);
190                }
191            }
192        }
193
194        BufferDiff {
195            last_update_version: buffer.version().clone(),
196            snapshot: BufferDiffSnapshot { tree },
197        }
198    }
199
200    pub fn snapshot(&self) -> BufferDiffSnapshot {
201        self.snapshot.clone()
202    }
203
204    pub fn update(&mut self, head_text: &str, buffer: &text::BufferSnapshot) {
205        let mut tree = SumTree::new();
206
207        let buffer_text = buffer.as_rope().to_string();
208        let patch = Self::diff(&head_text, &buffer_text);
209
210        if let Some(patch) = patch {
211            for hunk_index in 0..patch.num_hunks() {
212                let hunk = Self::process_patch_hunk(&patch, hunk_index, buffer);
213                tree.push(hunk, buffer);
214            }
215        }
216
217        self.last_update_version = buffer.version().clone();
218        self.snapshot.tree = tree;
219    }
220
221    fn diff<'a>(head: &'a str, current: &'a str) -> Option<GitPatch<'a>> {
222        let mut options = GitOptions::default();
223        options.context_lines(0);
224
225        let patch = GitPatch::from_buffers(
226            head.as_bytes(),
227            None,
228            current.as_bytes(),
229            None,
230            Some(&mut options),
231        );
232
233        match patch {
234            Ok(patch) => Some(patch),
235
236            Err(err) => {
237                log::error!("`GitPatch::from_buffers` failed: {}", err);
238                None
239            }
240        }
241    }
242
243    fn group_edit_ranges(&self, buffer: &text::BufferSnapshot) -> Vec<Range<u32>> {
244        const EXPAND_BY: u32 = 20;
245        const COMBINE_DISTANCE: u32 = 5;
246
247        // let mut cursor = self.snapshot.tree.cursor::<HunkBufferStart>();
248
249        let mut ranges = Vec::<Range<u32>>::new();
250
251        for edit in buffer.edits_since::<Point>(&self.last_update_version) {
252            let buffer_start = edit.new.start.row.saturating_sub(EXPAND_BY);
253            let buffer_end = (edit.new.end.row + EXPAND_BY).min(buffer.row_count());
254
255            match ranges.last_mut() {
256                Some(last_range) if last_range.end.abs_diff(buffer_end) <= COMBINE_DISTANCE => {
257                    last_range.start = last_range.start.min(buffer_start);
258                    last_range.end = last_range.end.max(buffer_end);
259                }
260
261                _ => ranges.push(buffer_start..buffer_end),
262            }
263        }
264
265        ranges
266    }
267
268    fn process_patch_hunk<'a>(
269        patch: &GitPatch<'a>,
270        hunk_index: usize,
271        buffer: &text::BufferSnapshot,
272    ) -> DiffHunk<Anchor> {
273        let line_item_count = patch.num_lines_in_hunk(hunk_index).unwrap();
274        assert!(line_item_count > 0);
275
276        let mut first_deletion_buffer_row: Option<u32> = None;
277        let mut buffer_byte_range: Option<Range<usize>> = None;
278        let mut head_byte_range: Option<Range<usize>> = None;
279
280        for line_index in 0..line_item_count {
281            let line = patch.line_in_hunk(hunk_index, line_index).unwrap();
282            let kind = line.origin_value();
283            let content_offset = line.content_offset() as isize;
284            let content_len = line.content().len() as isize;
285
286            match (kind, &mut buffer_byte_range, &mut head_byte_range) {
287                (GitDiffLineType::Addition, None, _) => {
288                    let end = content_offset + content_len;
289                    buffer_byte_range = Some(content_offset as usize..end as usize);
290                }
291
292                (GitDiffLineType::Addition, Some(buffer_byte_range), _) => {
293                    let end = content_offset + content_len;
294                    buffer_byte_range.end = end as usize;
295                }
296
297                (GitDiffLineType::Deletion, _, None) => {
298                    let end = content_offset + content_len;
299                    head_byte_range = Some(content_offset as usize..end as usize);
300                }
301
302                (GitDiffLineType::Deletion, _, Some(head_byte_range)) => {
303                    let end = content_offset + content_len;
304                    head_byte_range.end = end as usize;
305                }
306
307                _ => {}
308            }
309
310            if kind == GitDiffLineType::Deletion && first_deletion_buffer_row.is_none() {
311                //old_lineno is guarenteed to be Some for deletions
312                //libgit gives us line numbers that are 1-indexed but also returns a 0 for some states
313                let row = line.old_lineno().unwrap().saturating_sub(1);
314                first_deletion_buffer_row = Some(row);
315            }
316        }
317
318        //unwrap_or deletion without addition
319        let buffer_byte_range = buffer_byte_range.unwrap_or_else(|| {
320            //we cannot have an addition-less hunk without deletion(s) or else there would be no hunk
321            let row = first_deletion_buffer_row.unwrap();
322            let anchor = buffer.anchor_before(Point::new(row, 0));
323            let offset = anchor.to_offset(buffer);
324            offset..offset
325        });
326
327        //unwrap_or addition without deletion
328        let head_byte_range = head_byte_range.unwrap_or(0..0);
329
330        DiffHunk {
331            buffer_range: buffer.anchor_before(buffer_byte_range.start)
332                ..buffer.anchor_before(buffer_byte_range.end),
333            head_byte_range,
334        }
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341    use text::Buffer;
342    use unindent::Unindent as _;
343
344    #[gpui::test]
345    fn test_buffer_diff_simple() {
346        let head_text = "
347            one
348            two
349            three
350        "
351        .unindent();
352
353        let buffer_text = "
354            one
355            hello
356            three
357        "
358        .unindent();
359
360        let mut buffer = Buffer::new(0, 0, buffer_text);
361        let diff = BufferDiff::new(&Some(head_text.clone()), &buffer);
362        assert_hunks(&diff, &buffer, &head_text, &[(1..2, "two\n")]);
363
364        buffer.edit([(0..0, "point five\n")]);
365        assert_hunks(&diff, &buffer, &head_text, &[(2..3, "two\n")]);
366    }
367
368    #[track_caller]
369    fn assert_hunks(
370        diff: &BufferDiff,
371        buffer: &BufferSnapshot,
372        head_text: &str,
373        expected_hunks: &[(Range<u32>, &str)],
374    ) {
375        let hunks = diff.snapshot.hunks(buffer).collect::<Vec<_>>();
376        assert_eq!(
377            hunks.len(),
378            expected_hunks.len(),
379            "actual hunks are {hunks:#?}"
380        );
381
382        let diff_iter = hunks.iter().enumerate();
383        for ((index, hunk), (expected_range, expected_str)) in diff_iter.zip(expected_hunks) {
384            assert_eq!(&hunk.buffer_range, expected_range, "for hunk {index}");
385            assert_eq!(
386                &head_text[hunk.head_byte_range.clone()],
387                *expected_str,
388                "for hunk {index}"
389            );
390        }
391    }
392
393    // use rand::rngs::StdRng;
394    // #[gpui::test(iterations = 100)]
395    // fn test_buffer_diff_random(mut rng: StdRng) {}
396}