git.rs

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