1use futures::channel::oneshot;
2use git2::{DiffLineType as GitDiffLineType, DiffOptions as GitOptions, Patch as GitPatch};
3use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Task};
4use language::{Language, LanguageRegistry};
5use rope::Rope;
6use std::{cmp::Ordering, future::Future, iter, mem, ops::Range, sync::Arc};
7use sum_tree::SumTree;
8use text::{Anchor, Bias, BufferId, OffsetRangeExt, Point, ToOffset as _};
9use util::ResultExt;
10
11pub struct BufferDiff {
12 pub buffer_id: BufferId,
13 inner: BufferDiffInner,
14 secondary_diff: Option<Entity<BufferDiff>>,
15}
16
17#[derive(Clone, Debug)]
18pub struct BufferDiffSnapshot {
19 inner: BufferDiffInner,
20 secondary_diff: Option<Box<BufferDiffSnapshot>>,
21}
22
23#[derive(Clone)]
24struct BufferDiffInner {
25 hunks: SumTree<InternalDiffHunk>,
26 pending_hunks: SumTree<PendingHunk>,
27 base_text: language::BufferSnapshot,
28 base_text_exists: bool,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub struct DiffHunkStatus {
33 pub kind: DiffHunkStatusKind,
34 pub secondary: DiffHunkSecondaryStatus,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum DiffHunkStatusKind {
39 Added,
40 Modified,
41 Deleted,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum DiffHunkSecondaryStatus {
46 HasSecondaryHunk,
47 OverlapsWithSecondaryHunk,
48 NoSecondaryHunk,
49 SecondaryHunkAdditionPending,
50 SecondaryHunkRemovalPending,
51}
52
53/// A diff hunk resolved to rows in the buffer.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct DiffHunk {
56 /// The buffer range as points.
57 pub range: Range<Point>,
58 /// The range in the buffer to which this hunk corresponds.
59 pub buffer_range: Range<Anchor>,
60 /// The range in the buffer's diff base text to which this hunk corresponds.
61 pub diff_base_byte_range: Range<usize>,
62 pub secondary_status: DiffHunkSecondaryStatus,
63}
64
65/// We store [`InternalDiffHunk`]s internally so we don't need to store the additional row range.
66#[derive(Debug, Clone, PartialEq, Eq)]
67struct InternalDiffHunk {
68 buffer_range: Range<Anchor>,
69 diff_base_byte_range: Range<usize>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
73struct PendingHunk {
74 buffer_range: Range<Anchor>,
75 diff_base_byte_range: Range<usize>,
76 buffer_version: clock::Global,
77 new_status: DiffHunkSecondaryStatus,
78}
79
80#[derive(Debug, Default, Clone)]
81pub struct DiffHunkSummary {
82 buffer_range: Range<Anchor>,
83}
84
85impl sum_tree::Item for InternalDiffHunk {
86 type Summary = DiffHunkSummary;
87
88 fn summary(&self, _cx: &text::BufferSnapshot) -> Self::Summary {
89 DiffHunkSummary {
90 buffer_range: self.buffer_range.clone(),
91 }
92 }
93}
94
95impl sum_tree::Item for PendingHunk {
96 type Summary = DiffHunkSummary;
97
98 fn summary(&self, _cx: &text::BufferSnapshot) -> Self::Summary {
99 DiffHunkSummary {
100 buffer_range: self.buffer_range.clone(),
101 }
102 }
103}
104
105impl sum_tree::Summary for DiffHunkSummary {
106 type Context = text::BufferSnapshot;
107
108 fn zero(_cx: &Self::Context) -> Self {
109 Default::default()
110 }
111
112 fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
113 self.buffer_range.start = self
114 .buffer_range
115 .start
116 .min(&other.buffer_range.start, buffer);
117 self.buffer_range.end = self.buffer_range.end.max(&other.buffer_range.end, buffer);
118 }
119}
120
121impl sum_tree::SeekTarget<'_, DiffHunkSummary, DiffHunkSummary> for Anchor {
122 fn cmp(&self, cursor_location: &DiffHunkSummary, buffer: &text::BufferSnapshot) -> Ordering {
123 if self
124 .cmp(&cursor_location.buffer_range.start, buffer)
125 .is_lt()
126 {
127 Ordering::Less
128 } else if self.cmp(&cursor_location.buffer_range.end, buffer).is_gt() {
129 Ordering::Greater
130 } else {
131 Ordering::Equal
132 }
133 }
134}
135
136impl std::fmt::Debug for BufferDiffInner {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 f.debug_struct("BufferDiffSnapshot")
139 .field("hunks", &self.hunks)
140 .finish()
141 }
142}
143
144impl BufferDiffSnapshot {
145 pub fn is_empty(&self) -> bool {
146 self.inner.hunks.is_empty()
147 }
148
149 pub fn secondary_diff(&self) -> Option<&BufferDiffSnapshot> {
150 self.secondary_diff.as_deref()
151 }
152
153 pub fn hunks_intersecting_range<'a>(
154 &'a self,
155 range: Range<Anchor>,
156 buffer: &'a text::BufferSnapshot,
157 ) -> impl 'a + Iterator<Item = DiffHunk> {
158 let unstaged_counterpart = self.secondary_diff.as_ref().map(|diff| &diff.inner);
159 self.inner
160 .hunks_intersecting_range(range, buffer, unstaged_counterpart)
161 }
162
163 pub fn hunks_intersecting_range_rev<'a>(
164 &'a self,
165 range: Range<Anchor>,
166 buffer: &'a text::BufferSnapshot,
167 ) -> impl 'a + Iterator<Item = DiffHunk> {
168 self.inner.hunks_intersecting_range_rev(range, buffer)
169 }
170
171 pub fn base_text(&self) -> &language::BufferSnapshot {
172 &self.inner.base_text
173 }
174
175 pub fn base_texts_eq(&self, other: &Self) -> bool {
176 if self.inner.base_text_exists != other.inner.base_text_exists {
177 return false;
178 }
179 let left = &self.inner.base_text;
180 let right = &other.inner.base_text;
181 let (old_id, old_empty) = (left.remote_id(), left.is_empty());
182 let (new_id, new_empty) = (right.remote_id(), right.is_empty());
183 new_id == old_id || (new_empty && old_empty)
184 }
185}
186
187impl BufferDiffInner {
188 /// Returns the new index text and new pending hunks.
189 fn stage_or_unstage_hunks_impl(
190 &mut self,
191 unstaged_diff: &Self,
192 stage: bool,
193 hunks: &[DiffHunk],
194 buffer: &text::BufferSnapshot,
195 file_exists: bool,
196 ) -> Option<Rope> {
197 let head_text = self
198 .base_text_exists
199 .then(|| self.base_text.as_rope().clone());
200 let index_text = unstaged_diff
201 .base_text_exists
202 .then(|| unstaged_diff.base_text.as_rope().clone());
203
204 // If the file doesn't exist in either HEAD or the index, then the
205 // entire file must be either created or deleted in the index.
206 let (index_text, head_text) = match (index_text, head_text) {
207 (Some(index_text), Some(head_text)) if file_exists || !stage => (index_text, head_text),
208 (index_text, head_text) => {
209 let (new_index_text, new_status) = if stage {
210 log::debug!("stage all");
211 (
212 file_exists.then(|| buffer.as_rope().clone()),
213 DiffHunkSecondaryStatus::SecondaryHunkRemovalPending,
214 )
215 } else {
216 log::debug!("unstage all");
217 (
218 head_text,
219 DiffHunkSecondaryStatus::SecondaryHunkAdditionPending,
220 )
221 };
222
223 let hunk = PendingHunk {
224 buffer_range: Anchor::MIN..Anchor::MAX,
225 diff_base_byte_range: 0..index_text.map_or(0, |rope| rope.len()),
226 buffer_version: buffer.version().clone(),
227 new_status,
228 };
229 self.pending_hunks = SumTree::from_item(hunk, buffer);
230 return new_index_text;
231 }
232 };
233
234 let mut pending_hunks = SumTree::new(buffer);
235 let mut old_pending_hunks = self.pending_hunks.cursor::<DiffHunkSummary>(buffer);
236
237 // first, merge new hunks into pending_hunks
238 for DiffHunk {
239 buffer_range,
240 diff_base_byte_range,
241 secondary_status,
242 ..
243 } in hunks.iter().cloned()
244 {
245 let preceding_pending_hunks =
246 old_pending_hunks.slice(&buffer_range.start, Bias::Left, buffer);
247 pending_hunks.append(preceding_pending_hunks, buffer);
248
249 // Skip all overlapping or adjacent old pending hunks
250 while old_pending_hunks.item().is_some_and(|old_hunk| {
251 old_hunk
252 .buffer_range
253 .start
254 .cmp(&buffer_range.end, buffer)
255 .is_le()
256 }) {
257 old_pending_hunks.next(buffer);
258 }
259
260 if (stage && secondary_status == DiffHunkSecondaryStatus::NoSecondaryHunk)
261 || (!stage && secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
262 {
263 continue;
264 }
265
266 pending_hunks.push(
267 PendingHunk {
268 buffer_range,
269 diff_base_byte_range,
270 buffer_version: buffer.version().clone(),
271 new_status: if stage {
272 DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
273 } else {
274 DiffHunkSecondaryStatus::SecondaryHunkAdditionPending
275 },
276 },
277 buffer,
278 );
279 }
280 // append the remainder
281 pending_hunks.append(old_pending_hunks.suffix(buffer), buffer);
282
283 let mut unstaged_hunk_cursor = unstaged_diff.hunks.cursor::<DiffHunkSummary>(buffer);
284 unstaged_hunk_cursor.next(buffer);
285
286 // then, iterate over all pending hunks (both new ones and the existing ones) and compute the edits
287 let mut prev_unstaged_hunk_buffer_end = 0;
288 let mut prev_unstaged_hunk_base_text_end = 0;
289 let mut edits = Vec::<(Range<usize>, String)>::new();
290 let mut pending_hunks_iter = pending_hunks.iter().cloned().peekable();
291 while let Some(PendingHunk {
292 buffer_range,
293 diff_base_byte_range,
294 ..
295 }) = pending_hunks_iter.next()
296 {
297 // Advance unstaged_hunk_cursor to skip unstaged hunks before current hunk
298 let skipped_unstaged =
299 unstaged_hunk_cursor.slice(&buffer_range.start, Bias::Left, buffer);
300
301 if let Some(unstaged_hunk) = skipped_unstaged.last() {
302 prev_unstaged_hunk_base_text_end = unstaged_hunk.diff_base_byte_range.end;
303 prev_unstaged_hunk_buffer_end = unstaged_hunk.buffer_range.end.to_offset(buffer);
304 }
305
306 // Find where this hunk is in the index if it doesn't overlap
307 let mut buffer_offset_range = buffer_range.to_offset(buffer);
308 let start_overshoot = buffer_offset_range.start - prev_unstaged_hunk_buffer_end;
309 let mut index_start = prev_unstaged_hunk_base_text_end + start_overshoot;
310
311 loop {
312 // Merge this hunk with any overlapping unstaged hunks.
313 if let Some(unstaged_hunk) = unstaged_hunk_cursor.item() {
314 let unstaged_hunk_offset_range = unstaged_hunk.buffer_range.to_offset(buffer);
315 if unstaged_hunk_offset_range.start <= buffer_offset_range.end {
316 prev_unstaged_hunk_base_text_end = unstaged_hunk.diff_base_byte_range.end;
317 prev_unstaged_hunk_buffer_end = unstaged_hunk_offset_range.end;
318
319 index_start = index_start.min(unstaged_hunk.diff_base_byte_range.start);
320 buffer_offset_range.start = buffer_offset_range
321 .start
322 .min(unstaged_hunk_offset_range.start);
323 buffer_offset_range.end =
324 buffer_offset_range.end.max(unstaged_hunk_offset_range.end);
325
326 unstaged_hunk_cursor.next(buffer);
327 continue;
328 }
329 }
330
331 // If any unstaged hunks were merged, then subsequent pending hunks may
332 // now overlap this hunk. Merge them.
333 if let Some(next_pending_hunk) = pending_hunks_iter.peek() {
334 let next_pending_hunk_offset_range =
335 next_pending_hunk.buffer_range.to_offset(buffer);
336 if next_pending_hunk_offset_range.start <= buffer_offset_range.end {
337 buffer_offset_range.end = next_pending_hunk_offset_range.end;
338 pending_hunks_iter.next();
339 continue;
340 }
341 }
342
343 break;
344 }
345
346 let end_overshoot = buffer_offset_range
347 .end
348 .saturating_sub(prev_unstaged_hunk_buffer_end);
349 let index_end = prev_unstaged_hunk_base_text_end + end_overshoot;
350 let index_byte_range = index_start..index_end;
351
352 let replacement_text = if stage {
353 log::debug!("stage hunk {:?}", buffer_offset_range);
354 buffer
355 .text_for_range(buffer_offset_range)
356 .collect::<String>()
357 } else {
358 log::debug!("unstage hunk {:?}", buffer_offset_range);
359 head_text
360 .chunks_in_range(diff_base_byte_range.clone())
361 .collect::<String>()
362 };
363
364 edits.push((index_byte_range, replacement_text));
365 }
366 drop(pending_hunks_iter);
367 drop(old_pending_hunks);
368 self.pending_hunks = pending_hunks;
369
370 #[cfg(debug_assertions)] // invariants: non-overlapping and sorted
371 {
372 for window in edits.windows(2) {
373 let (range_a, range_b) = (&window[0].0, &window[1].0);
374 debug_assert!(range_a.end < range_b.start);
375 }
376 }
377
378 let mut new_index_text = Rope::new();
379 let mut index_cursor = index_text.cursor(0);
380
381 for (old_range, replacement_text) in edits {
382 new_index_text.append(index_cursor.slice(old_range.start));
383 index_cursor.seek_forward(old_range.end);
384 new_index_text.push(&replacement_text);
385 }
386 new_index_text.append(index_cursor.suffix());
387 Some(new_index_text)
388 }
389
390 fn hunks_intersecting_range<'a>(
391 &'a self,
392 range: Range<Anchor>,
393 buffer: &'a text::BufferSnapshot,
394 secondary: Option<&'a Self>,
395 ) -> impl 'a + Iterator<Item = DiffHunk> {
396 let range = range.to_offset(buffer);
397
398 let mut cursor = self
399 .hunks
400 .filter::<_, DiffHunkSummary>(buffer, move |summary| {
401 let summary_range = summary.buffer_range.to_offset(buffer);
402 let before_start = summary_range.end < range.start;
403 let after_end = summary_range.start > range.end;
404 !before_start && !after_end
405 });
406
407 let anchor_iter = iter::from_fn(move || {
408 cursor.next(buffer);
409 cursor.item()
410 })
411 .flat_map(move |hunk| {
412 [
413 (
414 &hunk.buffer_range.start,
415 (hunk.buffer_range.start, hunk.diff_base_byte_range.start),
416 ),
417 (
418 &hunk.buffer_range.end,
419 (hunk.buffer_range.end, hunk.diff_base_byte_range.end),
420 ),
421 ]
422 });
423
424 let mut pending_hunks_cursor = self.pending_hunks.cursor::<DiffHunkSummary>(buffer);
425 pending_hunks_cursor.next(buffer);
426
427 let mut secondary_cursor = None;
428 if let Some(secondary) = secondary.as_ref() {
429 let mut cursor = secondary.hunks.cursor::<DiffHunkSummary>(buffer);
430 cursor.next(buffer);
431 secondary_cursor = Some(cursor);
432 }
433
434 let max_point = buffer.max_point();
435 let mut summaries = buffer.summaries_for_anchors_with_payload::<Point, _, _>(anchor_iter);
436 iter::from_fn(move || {
437 loop {
438 let (start_point, (start_anchor, start_base)) = summaries.next()?;
439 let (mut end_point, (mut end_anchor, end_base)) = summaries.next()?;
440
441 if !start_anchor.is_valid(buffer) {
442 continue;
443 }
444
445 if end_point.column > 0 && end_point < max_point {
446 end_point.row += 1;
447 end_point.column = 0;
448 end_anchor = buffer.anchor_before(end_point);
449 }
450
451 let mut secondary_status = DiffHunkSecondaryStatus::NoSecondaryHunk;
452
453 let mut has_pending = false;
454 if start_anchor
455 .cmp(&pending_hunks_cursor.start().buffer_range.start, buffer)
456 .is_gt()
457 {
458 pending_hunks_cursor.seek_forward(&start_anchor, Bias::Left, buffer);
459 }
460
461 if let Some(pending_hunk) = pending_hunks_cursor.item() {
462 let mut pending_range = pending_hunk.buffer_range.to_point(buffer);
463 if pending_range.end.column > 0 {
464 pending_range.end.row += 1;
465 pending_range.end.column = 0;
466 }
467
468 if pending_range == (start_point..end_point) {
469 if !buffer.has_edits_since_in_range(
470 &pending_hunk.buffer_version,
471 start_anchor..end_anchor,
472 ) {
473 has_pending = true;
474 secondary_status = pending_hunk.new_status;
475 }
476 }
477 }
478
479 if let (Some(secondary_cursor), false) = (secondary_cursor.as_mut(), has_pending) {
480 if start_anchor
481 .cmp(&secondary_cursor.start().buffer_range.start, buffer)
482 .is_gt()
483 {
484 secondary_cursor.seek_forward(&start_anchor, Bias::Left, buffer);
485 }
486
487 if let Some(secondary_hunk) = secondary_cursor.item() {
488 let mut secondary_range = secondary_hunk.buffer_range.to_point(buffer);
489 if secondary_range.end.column > 0 {
490 secondary_range.end.row += 1;
491 secondary_range.end.column = 0;
492 }
493 if secondary_range.is_empty()
494 && secondary_hunk.diff_base_byte_range.is_empty()
495 {
496 // ignore
497 } else if secondary_range == (start_point..end_point) {
498 secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
499 } else if secondary_range.start <= end_point {
500 secondary_status = DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk;
501 }
502 }
503 }
504
505 return Some(DiffHunk {
506 range: start_point..end_point,
507 diff_base_byte_range: start_base..end_base,
508 buffer_range: start_anchor..end_anchor,
509 secondary_status,
510 });
511 }
512 })
513 }
514
515 fn hunks_intersecting_range_rev<'a>(
516 &'a self,
517 range: Range<Anchor>,
518 buffer: &'a text::BufferSnapshot,
519 ) -> impl 'a + Iterator<Item = DiffHunk> {
520 let mut cursor = self
521 .hunks
522 .filter::<_, DiffHunkSummary>(buffer, move |summary| {
523 let before_start = summary.buffer_range.end.cmp(&range.start, buffer).is_lt();
524 let after_end = summary.buffer_range.start.cmp(&range.end, buffer).is_gt();
525 !before_start && !after_end
526 });
527
528 iter::from_fn(move || {
529 cursor.prev(buffer);
530
531 let hunk = cursor.item()?;
532 let range = hunk.buffer_range.to_point(buffer);
533
534 Some(DiffHunk {
535 range,
536 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
537 buffer_range: hunk.buffer_range.clone(),
538 // The secondary status is not used by callers of this method.
539 secondary_status: DiffHunkSecondaryStatus::NoSecondaryHunk,
540 })
541 })
542 }
543
544 fn compare(&self, old: &Self, new_snapshot: &text::BufferSnapshot) -> Option<Range<Anchor>> {
545 let mut new_cursor = self.hunks.cursor::<()>(new_snapshot);
546 let mut old_cursor = old.hunks.cursor::<()>(new_snapshot);
547 old_cursor.next(new_snapshot);
548 new_cursor.next(new_snapshot);
549 let mut start = None;
550 let mut end = None;
551
552 loop {
553 match (new_cursor.item(), old_cursor.item()) {
554 (Some(new_hunk), Some(old_hunk)) => {
555 match new_hunk
556 .buffer_range
557 .start
558 .cmp(&old_hunk.buffer_range.start, new_snapshot)
559 {
560 Ordering::Less => {
561 start.get_or_insert(new_hunk.buffer_range.start);
562 end.replace(new_hunk.buffer_range.end);
563 new_cursor.next(new_snapshot);
564 }
565 Ordering::Equal => {
566 if new_hunk != old_hunk {
567 start.get_or_insert(new_hunk.buffer_range.start);
568 if old_hunk
569 .buffer_range
570 .end
571 .cmp(&new_hunk.buffer_range.end, new_snapshot)
572 .is_ge()
573 {
574 end.replace(old_hunk.buffer_range.end);
575 } else {
576 end.replace(new_hunk.buffer_range.end);
577 }
578 }
579
580 new_cursor.next(new_snapshot);
581 old_cursor.next(new_snapshot);
582 }
583 Ordering::Greater => {
584 start.get_or_insert(old_hunk.buffer_range.start);
585 end.replace(old_hunk.buffer_range.end);
586 old_cursor.next(new_snapshot);
587 }
588 }
589 }
590 (Some(new_hunk), None) => {
591 start.get_or_insert(new_hunk.buffer_range.start);
592 end.replace(new_hunk.buffer_range.end);
593 new_cursor.next(new_snapshot);
594 }
595 (None, Some(old_hunk)) => {
596 start.get_or_insert(old_hunk.buffer_range.start);
597 end.replace(old_hunk.buffer_range.end);
598 old_cursor.next(new_snapshot);
599 }
600 (None, None) => break,
601 }
602 }
603
604 start.zip(end).map(|(start, end)| start..end)
605 }
606}
607
608fn compute_hunks(
609 diff_base: Option<(Arc<String>, Rope)>,
610 buffer: text::BufferSnapshot,
611) -> SumTree<InternalDiffHunk> {
612 let mut tree = SumTree::new(&buffer);
613
614 if let Some((diff_base, diff_base_rope)) = diff_base {
615 let buffer_text = buffer.as_rope().to_string();
616
617 let mut options = GitOptions::default();
618 options.context_lines(0);
619 let patch = GitPatch::from_buffers(
620 diff_base.as_bytes(),
621 None,
622 buffer_text.as_bytes(),
623 None,
624 Some(&mut options),
625 )
626 .log_err();
627
628 // A common case in Zed is that the empty buffer is represented as just a newline,
629 // but if we just compute a naive diff you get a "preserved" line in the middle,
630 // which is a bit odd.
631 if buffer_text == "\n" && diff_base.ends_with("\n") && diff_base.len() > 1 {
632 tree.push(
633 InternalDiffHunk {
634 buffer_range: buffer.anchor_before(0)..buffer.anchor_before(0),
635 diff_base_byte_range: 0..diff_base.len() - 1,
636 },
637 &buffer,
638 );
639 return tree;
640 }
641
642 if let Some(patch) = patch {
643 let mut divergence = 0;
644 for hunk_index in 0..patch.num_hunks() {
645 let hunk = process_patch_hunk(
646 &patch,
647 hunk_index,
648 &diff_base_rope,
649 &buffer,
650 &mut divergence,
651 );
652 tree.push(hunk, &buffer);
653 }
654 }
655 } else {
656 tree.push(
657 InternalDiffHunk {
658 buffer_range: Anchor::MIN..Anchor::MAX,
659 diff_base_byte_range: 0..0,
660 },
661 &buffer,
662 );
663 }
664
665 tree
666}
667
668fn process_patch_hunk(
669 patch: &GitPatch<'_>,
670 hunk_index: usize,
671 diff_base: &Rope,
672 buffer: &text::BufferSnapshot,
673 buffer_row_divergence: &mut i64,
674) -> InternalDiffHunk {
675 let line_item_count = patch.num_lines_in_hunk(hunk_index).unwrap();
676 assert!(line_item_count > 0);
677
678 let mut first_deletion_buffer_row: Option<u32> = None;
679 let mut buffer_row_range: Option<Range<u32>> = None;
680 let mut diff_base_byte_range: Option<Range<usize>> = None;
681 let mut first_addition_old_row: Option<u32> = None;
682
683 for line_index in 0..line_item_count {
684 let line = patch.line_in_hunk(hunk_index, line_index).unwrap();
685 let kind = line.origin_value();
686 let content_offset = line.content_offset() as isize;
687 let content_len = line.content().len() as isize;
688 match kind {
689 GitDiffLineType::Addition => {
690 if first_addition_old_row.is_none() {
691 first_addition_old_row = Some(
692 (line.new_lineno().unwrap() as i64 - *buffer_row_divergence - 1) as u32,
693 );
694 }
695 *buffer_row_divergence += 1;
696 let row = line.new_lineno().unwrap().saturating_sub(1);
697
698 match &mut buffer_row_range {
699 Some(Range { end, .. }) => *end = row + 1,
700 None => buffer_row_range = Some(row..row + 1),
701 }
702 }
703 GitDiffLineType::Deletion => {
704 let end = content_offset + content_len;
705
706 match &mut diff_base_byte_range {
707 Some(head_byte_range) => head_byte_range.end = end as usize,
708 None => diff_base_byte_range = Some(content_offset as usize..end as usize),
709 }
710
711 if first_deletion_buffer_row.is_none() {
712 let old_row = line.old_lineno().unwrap().saturating_sub(1);
713 let row = old_row as i64 + *buffer_row_divergence;
714 first_deletion_buffer_row = Some(row as u32);
715 }
716
717 *buffer_row_divergence -= 1;
718 }
719 _ => {}
720 }
721 }
722
723 let buffer_row_range = buffer_row_range.unwrap_or_else(|| {
724 // Pure deletion hunk without addition.
725 let row = first_deletion_buffer_row.unwrap();
726 row..row
727 });
728 let diff_base_byte_range = diff_base_byte_range.unwrap_or_else(|| {
729 // Pure addition hunk without deletion.
730 let row = first_addition_old_row.unwrap();
731 let offset = diff_base.point_to_offset(Point::new(row, 0));
732 offset..offset
733 });
734
735 let start = Point::new(buffer_row_range.start, 0);
736 let end = Point::new(buffer_row_range.end, 0);
737 let buffer_range = buffer.anchor_before(start)..buffer.anchor_before(end);
738 InternalDiffHunk {
739 buffer_range,
740 diff_base_byte_range,
741 }
742}
743
744impl std::fmt::Debug for BufferDiff {
745 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
746 f.debug_struct("BufferChangeSet")
747 .field("buffer_id", &self.buffer_id)
748 .field("snapshot", &self.inner)
749 .finish()
750 }
751}
752
753#[derive(Clone, Debug)]
754pub enum BufferDiffEvent {
755 DiffChanged {
756 changed_range: Option<Range<text::Anchor>>,
757 },
758 LanguageChanged,
759 HunksStagedOrUnstaged(Option<Rope>),
760}
761
762impl EventEmitter<BufferDiffEvent> for BufferDiff {}
763
764impl BufferDiff {
765 #[cfg(test)]
766 fn build_sync(
767 buffer: text::BufferSnapshot,
768 diff_base: String,
769 cx: &mut gpui::TestAppContext,
770 ) -> BufferDiffInner {
771 let snapshot =
772 cx.update(|cx| Self::build(buffer, Some(Arc::new(diff_base)), None, None, cx));
773 cx.executor().block(snapshot)
774 }
775
776 fn build(
777 buffer: text::BufferSnapshot,
778 base_text: Option<Arc<String>>,
779 language: Option<Arc<Language>>,
780 language_registry: Option<Arc<LanguageRegistry>>,
781 cx: &mut App,
782 ) -> impl Future<Output = BufferDiffInner> + use<> {
783 let base_text_pair;
784 let base_text_exists;
785 let base_text_snapshot;
786 if let Some(text) = &base_text {
787 let base_text_rope = Rope::from(text.as_str());
788 base_text_pair = Some((text.clone(), base_text_rope.clone()));
789 let snapshot = language::Buffer::build_snapshot(
790 base_text_rope,
791 language.clone(),
792 language_registry.clone(),
793 cx,
794 );
795 base_text_snapshot = cx.background_spawn(snapshot);
796 base_text_exists = true;
797 } else {
798 base_text_pair = None;
799 base_text_snapshot = Task::ready(language::Buffer::build_empty_snapshot(cx));
800 base_text_exists = false;
801 };
802
803 let hunks = cx.background_spawn({
804 let buffer = buffer.clone();
805 async move { compute_hunks(base_text_pair, buffer) }
806 });
807
808 async move {
809 let (base_text, hunks) = futures::join!(base_text_snapshot, hunks);
810 BufferDiffInner {
811 base_text,
812 hunks,
813 base_text_exists,
814 pending_hunks: SumTree::new(&buffer),
815 }
816 }
817 }
818
819 fn build_with_base_buffer(
820 buffer: text::BufferSnapshot,
821 base_text: Option<Arc<String>>,
822 base_text_snapshot: language::BufferSnapshot,
823 cx: &App,
824 ) -> impl Future<Output = BufferDiffInner> + use<> {
825 let base_text_exists = base_text.is_some();
826 let base_text_pair = base_text.map(|text| (text, base_text_snapshot.as_rope().clone()));
827 cx.background_spawn(async move {
828 BufferDiffInner {
829 base_text: base_text_snapshot,
830 pending_hunks: SumTree::new(&buffer),
831 hunks: compute_hunks(base_text_pair, buffer),
832 base_text_exists,
833 }
834 })
835 }
836
837 fn build_empty(buffer: &text::BufferSnapshot, cx: &mut App) -> BufferDiffInner {
838 BufferDiffInner {
839 base_text: language::Buffer::build_empty_snapshot(cx),
840 hunks: SumTree::new(buffer),
841 pending_hunks: SumTree::new(buffer),
842 base_text_exists: false,
843 }
844 }
845
846 pub fn set_secondary_diff(&mut self, diff: Entity<BufferDiff>) {
847 self.secondary_diff = Some(diff);
848 }
849
850 pub fn secondary_diff(&self) -> Option<Entity<BufferDiff>> {
851 self.secondary_diff.clone()
852 }
853
854 pub fn clear_pending_hunks(&mut self, cx: &mut Context<Self>) {
855 if self.secondary_diff.is_some() {
856 self.inner.pending_hunks = SumTree::from_summary(DiffHunkSummary::default());
857 cx.emit(BufferDiffEvent::DiffChanged {
858 changed_range: Some(Anchor::MIN..Anchor::MAX),
859 });
860 }
861 }
862
863 pub fn stage_or_unstage_hunks(
864 &mut self,
865 stage: bool,
866 hunks: &[DiffHunk],
867 buffer: &text::BufferSnapshot,
868 file_exists: bool,
869 cx: &mut Context<Self>,
870 ) -> Option<Rope> {
871 let new_index_text = self.inner.stage_or_unstage_hunks_impl(
872 &self.secondary_diff.as_ref()?.read(cx).inner,
873 stage,
874 &hunks,
875 buffer,
876 file_exists,
877 );
878
879 cx.emit(BufferDiffEvent::HunksStagedOrUnstaged(
880 new_index_text.clone(),
881 ));
882 if let Some((first, last)) = hunks.first().zip(hunks.last()) {
883 let changed_range = first.buffer_range.start..last.buffer_range.end;
884 cx.emit(BufferDiffEvent::DiffChanged {
885 changed_range: Some(changed_range),
886 });
887 }
888 new_index_text
889 }
890
891 pub fn range_to_hunk_range(
892 &self,
893 range: Range<Anchor>,
894 buffer: &text::BufferSnapshot,
895 cx: &App,
896 ) -> Option<Range<Anchor>> {
897 let start = self
898 .hunks_intersecting_range(range.clone(), &buffer, cx)
899 .next()?
900 .buffer_range
901 .start;
902 let end = self
903 .hunks_intersecting_range_rev(range.clone(), &buffer)
904 .next()?
905 .buffer_range
906 .end;
907 Some(start..end)
908 }
909
910 pub async fn update_diff(
911 this: Entity<BufferDiff>,
912 buffer: text::BufferSnapshot,
913 base_text: Option<Arc<String>>,
914 base_text_changed: bool,
915 language_changed: bool,
916 language: Option<Arc<Language>>,
917 language_registry: Option<Arc<LanguageRegistry>>,
918 cx: &mut AsyncApp,
919 ) -> anyhow::Result<BufferDiffSnapshot> {
920 let inner = if base_text_changed || language_changed {
921 cx.update(|cx| {
922 Self::build(
923 buffer.clone(),
924 base_text,
925 language.clone(),
926 language_registry.clone(),
927 cx,
928 )
929 })?
930 .await
931 } else {
932 this.read_with(cx, |this, cx| {
933 Self::build_with_base_buffer(
934 buffer.clone(),
935 base_text,
936 this.base_text().clone(),
937 cx,
938 )
939 })?
940 .await
941 };
942 Ok(BufferDiffSnapshot {
943 inner,
944 secondary_diff: None,
945 })
946 }
947
948 pub fn set_snapshot(
949 &mut self,
950 buffer: &text::BufferSnapshot,
951 new_snapshot: BufferDiffSnapshot,
952 language_changed: bool,
953 secondary_changed_range: Option<Range<Anchor>>,
954 cx: &mut Context<Self>,
955 ) -> Option<Range<Anchor>> {
956 let changed_range = self.set_state(new_snapshot.inner, buffer);
957 if language_changed {
958 cx.emit(BufferDiffEvent::LanguageChanged);
959 }
960
961 let changed_range = match (secondary_changed_range, changed_range) {
962 (None, None) => None,
963 (Some(unstaged_range), None) => self.range_to_hunk_range(unstaged_range, &buffer, cx),
964 (None, Some(uncommitted_range)) => Some(uncommitted_range),
965 (Some(unstaged_range), Some(uncommitted_range)) => {
966 let mut start = uncommitted_range.start;
967 let mut end = uncommitted_range.end;
968 if let Some(unstaged_range) = self.range_to_hunk_range(unstaged_range, &buffer, cx)
969 {
970 start = unstaged_range.start.min(&uncommitted_range.start, &buffer);
971 end = unstaged_range.end.max(&uncommitted_range.end, &buffer);
972 }
973 Some(start..end)
974 }
975 };
976
977 cx.emit(BufferDiffEvent::DiffChanged {
978 changed_range: changed_range.clone(),
979 });
980 changed_range
981 }
982
983 fn set_state(
984 &mut self,
985 new_state: BufferDiffInner,
986 buffer: &text::BufferSnapshot,
987 ) -> Option<Range<Anchor>> {
988 let (base_text_changed, changed_range) =
989 match (self.inner.base_text_exists, new_state.base_text_exists) {
990 (false, false) => (true, None),
991 (true, true)
992 if self.inner.base_text.remote_id() == new_state.base_text.remote_id() =>
993 {
994 (false, new_state.compare(&self.inner, buffer))
995 }
996 _ => (true, Some(text::Anchor::MIN..text::Anchor::MAX)),
997 };
998
999 let pending_hunks = mem::replace(&mut self.inner.pending_hunks, SumTree::new(buffer));
1000
1001 self.inner = new_state;
1002 if !base_text_changed {
1003 self.inner.pending_hunks = pending_hunks;
1004 }
1005 changed_range
1006 }
1007
1008 pub fn base_text(&self) -> &language::BufferSnapshot {
1009 &self.inner.base_text
1010 }
1011
1012 pub fn base_text_exists(&self) -> bool {
1013 self.inner.base_text_exists
1014 }
1015
1016 pub fn snapshot(&self, cx: &App) -> BufferDiffSnapshot {
1017 BufferDiffSnapshot {
1018 inner: self.inner.clone(),
1019 secondary_diff: self
1020 .secondary_diff
1021 .as_ref()
1022 .map(|diff| Box::new(diff.read(cx).snapshot(cx))),
1023 }
1024 }
1025
1026 pub fn hunks<'a>(
1027 &'a self,
1028 buffer_snapshot: &'a text::BufferSnapshot,
1029 cx: &'a App,
1030 ) -> impl 'a + Iterator<Item = DiffHunk> {
1031 self.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer_snapshot, cx)
1032 }
1033
1034 pub fn hunks_intersecting_range<'a>(
1035 &'a self,
1036 range: Range<text::Anchor>,
1037 buffer_snapshot: &'a text::BufferSnapshot,
1038 cx: &'a App,
1039 ) -> impl 'a + Iterator<Item = DiffHunk> {
1040 let unstaged_counterpart = self
1041 .secondary_diff
1042 .as_ref()
1043 .map(|diff| &diff.read(cx).inner);
1044 self.inner
1045 .hunks_intersecting_range(range, buffer_snapshot, unstaged_counterpart)
1046 }
1047
1048 pub fn hunks_intersecting_range_rev<'a>(
1049 &'a self,
1050 range: Range<text::Anchor>,
1051 buffer_snapshot: &'a text::BufferSnapshot,
1052 ) -> impl 'a + Iterator<Item = DiffHunk> {
1053 self.inner
1054 .hunks_intersecting_range_rev(range, buffer_snapshot)
1055 }
1056
1057 pub fn hunks_in_row_range<'a>(
1058 &'a self,
1059 range: Range<u32>,
1060 buffer: &'a text::BufferSnapshot,
1061 cx: &'a App,
1062 ) -> impl 'a + Iterator<Item = DiffHunk> {
1063 let start = buffer.anchor_before(Point::new(range.start, 0));
1064 let end = buffer.anchor_after(Point::new(range.end, 0));
1065 self.hunks_intersecting_range(start..end, buffer, cx)
1066 }
1067
1068 /// Used in cases where the change set isn't derived from git.
1069 pub fn set_base_text(
1070 &mut self,
1071 base_buffer: Entity<language::Buffer>,
1072 buffer: text::BufferSnapshot,
1073 cx: &mut Context<Self>,
1074 ) -> oneshot::Receiver<()> {
1075 let (tx, rx) = oneshot::channel();
1076 let this = cx.weak_entity();
1077 let base_buffer = base_buffer.read(cx);
1078 let language_registry = base_buffer.language_registry();
1079 let base_buffer = base_buffer.snapshot();
1080 let base_text = Arc::new(base_buffer.text());
1081
1082 let snapshot = BufferDiff::build(
1083 buffer.clone(),
1084 Some(base_text),
1085 base_buffer.language().cloned(),
1086 language_registry,
1087 cx,
1088 );
1089 let complete_on_drop = util::defer(|| {
1090 tx.send(()).ok();
1091 });
1092 cx.spawn(async move |_, cx| {
1093 let snapshot = snapshot.await;
1094 let Some(this) = this.upgrade() else {
1095 return;
1096 };
1097 this.update(cx, |this, _| {
1098 this.set_state(snapshot, &buffer);
1099 })
1100 .log_err();
1101 drop(complete_on_drop)
1102 })
1103 .detach();
1104 rx
1105 }
1106
1107 pub fn base_text_string(&self) -> Option<String> {
1108 self.inner
1109 .base_text_exists
1110 .then(|| self.inner.base_text.text())
1111 }
1112
1113 pub fn new(buffer: &text::BufferSnapshot, cx: &mut App) -> Self {
1114 BufferDiff {
1115 buffer_id: buffer.remote_id(),
1116 inner: BufferDiff::build_empty(buffer, cx),
1117 secondary_diff: None,
1118 }
1119 }
1120
1121 #[cfg(any(test, feature = "test-support"))]
1122 pub fn new_with_base_text(
1123 base_text: &str,
1124 buffer: &Entity<language::Buffer>,
1125 cx: &mut App,
1126 ) -> Self {
1127 let mut base_text = base_text.to_owned();
1128 text::LineEnding::normalize(&mut base_text);
1129 let snapshot = BufferDiff::build(
1130 buffer.read(cx).text_snapshot(),
1131 Some(base_text.into()),
1132 None,
1133 None,
1134 cx,
1135 );
1136 let snapshot = cx.background_executor().block(snapshot);
1137 BufferDiff {
1138 buffer_id: buffer.read(cx).remote_id(),
1139 inner: snapshot,
1140 secondary_diff: None,
1141 }
1142 }
1143
1144 #[cfg(any(test, feature = "test-support"))]
1145 pub fn recalculate_diff_sync(&mut self, buffer: text::BufferSnapshot, cx: &mut Context<Self>) {
1146 let base_text = self.base_text_string().map(Arc::new);
1147 let snapshot = BufferDiff::build_with_base_buffer(
1148 buffer.clone(),
1149 base_text,
1150 self.inner.base_text.clone(),
1151 cx,
1152 );
1153 let snapshot = cx.background_executor().block(snapshot);
1154 let changed_range = self.set_state(snapshot, &buffer);
1155 cx.emit(BufferDiffEvent::DiffChanged { changed_range });
1156 }
1157}
1158
1159impl DiffHunk {
1160 pub fn is_created_file(&self) -> bool {
1161 self.diff_base_byte_range == (0..0) && self.buffer_range == (Anchor::MIN..Anchor::MAX)
1162 }
1163
1164 pub fn status(&self) -> DiffHunkStatus {
1165 let kind = if self.buffer_range.start == self.buffer_range.end {
1166 DiffHunkStatusKind::Deleted
1167 } else if self.diff_base_byte_range.is_empty() {
1168 DiffHunkStatusKind::Added
1169 } else {
1170 DiffHunkStatusKind::Modified
1171 };
1172 DiffHunkStatus {
1173 kind,
1174 secondary: self.secondary_status,
1175 }
1176 }
1177}
1178
1179impl DiffHunkStatus {
1180 pub fn has_secondary_hunk(&self) -> bool {
1181 matches!(
1182 self.secondary,
1183 DiffHunkSecondaryStatus::HasSecondaryHunk
1184 | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending
1185 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
1186 )
1187 }
1188
1189 pub fn is_pending(&self) -> bool {
1190 matches!(
1191 self.secondary,
1192 DiffHunkSecondaryStatus::SecondaryHunkAdditionPending
1193 | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
1194 )
1195 }
1196
1197 pub fn is_deleted(&self) -> bool {
1198 self.kind == DiffHunkStatusKind::Deleted
1199 }
1200
1201 pub fn is_added(&self) -> bool {
1202 self.kind == DiffHunkStatusKind::Added
1203 }
1204
1205 pub fn is_modified(&self) -> bool {
1206 self.kind == DiffHunkStatusKind::Modified
1207 }
1208
1209 pub fn added(secondary: DiffHunkSecondaryStatus) -> Self {
1210 Self {
1211 kind: DiffHunkStatusKind::Added,
1212 secondary,
1213 }
1214 }
1215
1216 pub fn modified(secondary: DiffHunkSecondaryStatus) -> Self {
1217 Self {
1218 kind: DiffHunkStatusKind::Modified,
1219 secondary,
1220 }
1221 }
1222
1223 pub fn deleted(secondary: DiffHunkSecondaryStatus) -> Self {
1224 Self {
1225 kind: DiffHunkStatusKind::Deleted,
1226 secondary,
1227 }
1228 }
1229
1230 pub fn deleted_none() -> Self {
1231 Self {
1232 kind: DiffHunkStatusKind::Deleted,
1233 secondary: DiffHunkSecondaryStatus::NoSecondaryHunk,
1234 }
1235 }
1236
1237 pub fn added_none() -> Self {
1238 Self {
1239 kind: DiffHunkStatusKind::Added,
1240 secondary: DiffHunkSecondaryStatus::NoSecondaryHunk,
1241 }
1242 }
1243
1244 pub fn modified_none() -> Self {
1245 Self {
1246 kind: DiffHunkStatusKind::Modified,
1247 secondary: DiffHunkSecondaryStatus::NoSecondaryHunk,
1248 }
1249 }
1250}
1251
1252#[cfg(any(test, feature = "test-support"))]
1253#[track_caller]
1254pub fn assert_hunks<ExpectedText, HunkIter>(
1255 diff_hunks: HunkIter,
1256 buffer: &text::BufferSnapshot,
1257 diff_base: &str,
1258 // Line range, deleted, added, status
1259 expected_hunks: &[(Range<u32>, ExpectedText, ExpectedText, DiffHunkStatus)],
1260) where
1261 HunkIter: Iterator<Item = DiffHunk>,
1262 ExpectedText: AsRef<str>,
1263{
1264 let actual_hunks = diff_hunks
1265 .map(|hunk| {
1266 (
1267 hunk.range.clone(),
1268 &diff_base[hunk.diff_base_byte_range.clone()],
1269 buffer
1270 .text_for_range(hunk.range.clone())
1271 .collect::<String>(),
1272 hunk.status(),
1273 )
1274 })
1275 .collect::<Vec<_>>();
1276
1277 let expected_hunks: Vec<_> = expected_hunks
1278 .iter()
1279 .map(|(line_range, deleted_text, added_text, status)| {
1280 (
1281 Point::new(line_range.start, 0)..Point::new(line_range.end, 0),
1282 deleted_text.as_ref(),
1283 added_text.as_ref().to_string(),
1284 *status,
1285 )
1286 })
1287 .collect();
1288
1289 pretty_assertions::assert_eq!(actual_hunks, expected_hunks);
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294 use std::fmt::Write as _;
1295
1296 use super::*;
1297 use gpui::TestAppContext;
1298 use pretty_assertions::{assert_eq, assert_ne};
1299 use rand::{Rng as _, rngs::StdRng};
1300 use text::{Buffer, BufferId, Rope};
1301 use unindent::Unindent as _;
1302 use util::test::marked_text_ranges;
1303
1304 #[ctor::ctor]
1305 fn init_logger() {
1306 if std::env::var("RUST_LOG").is_ok() {
1307 env_logger::init();
1308 }
1309 }
1310
1311 #[gpui::test]
1312 async fn test_buffer_diff_simple(cx: &mut gpui::TestAppContext) {
1313 let diff_base = "
1314 one
1315 two
1316 three
1317 "
1318 .unindent();
1319
1320 let buffer_text = "
1321 one
1322 HELLO
1323 three
1324 "
1325 .unindent();
1326
1327 let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1328 let mut diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1329 assert_hunks(
1330 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1331 &buffer,
1332 &diff_base,
1333 &[(1..2, "two\n", "HELLO\n", DiffHunkStatus::modified_none())],
1334 );
1335
1336 buffer.edit([(0..0, "point five\n")]);
1337 diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1338 assert_hunks(
1339 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1340 &buffer,
1341 &diff_base,
1342 &[
1343 (0..1, "", "point five\n", DiffHunkStatus::added_none()),
1344 (2..3, "two\n", "HELLO\n", DiffHunkStatus::modified_none()),
1345 ],
1346 );
1347
1348 diff = cx.update(|cx| BufferDiff::build_empty(&buffer, cx));
1349 assert_hunks::<&str, _>(
1350 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1351 &buffer,
1352 &diff_base,
1353 &[],
1354 );
1355 }
1356
1357 #[gpui::test]
1358 async fn test_buffer_diff_with_secondary(cx: &mut gpui::TestAppContext) {
1359 let head_text = "
1360 zero
1361 one
1362 two
1363 three
1364 four
1365 five
1366 six
1367 seven
1368 eight
1369 nine
1370 "
1371 .unindent();
1372
1373 let index_text = "
1374 zero
1375 one
1376 TWO
1377 three
1378 FOUR
1379 five
1380 six
1381 seven
1382 eight
1383 NINE
1384 "
1385 .unindent();
1386
1387 let buffer_text = "
1388 zero
1389 one
1390 TWO
1391 three
1392 FOUR
1393 FIVE
1394 six
1395 SEVEN
1396 eight
1397 nine
1398 "
1399 .unindent();
1400
1401 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1402 let unstaged_diff = BufferDiff::build_sync(buffer.clone(), index_text.clone(), cx);
1403
1404 let uncommitted_diff = BufferDiff::build_sync(buffer.clone(), head_text.clone(), cx);
1405
1406 let expected_hunks = vec![
1407 (2..3, "two\n", "TWO\n", DiffHunkStatus::modified_none()),
1408 (
1409 4..6,
1410 "four\nfive\n",
1411 "FOUR\nFIVE\n",
1412 DiffHunkStatus::modified(DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk),
1413 ),
1414 (
1415 7..8,
1416 "seven\n",
1417 "SEVEN\n",
1418 DiffHunkStatus::modified(DiffHunkSecondaryStatus::HasSecondaryHunk),
1419 ),
1420 ];
1421
1422 assert_hunks(
1423 uncommitted_diff.hunks_intersecting_range(
1424 Anchor::MIN..Anchor::MAX,
1425 &buffer,
1426 Some(&unstaged_diff),
1427 ),
1428 &buffer,
1429 &head_text,
1430 &expected_hunks,
1431 );
1432 }
1433
1434 #[gpui::test]
1435 async fn test_buffer_diff_range(cx: &mut TestAppContext) {
1436 let diff_base = Arc::new(
1437 "
1438 one
1439 two
1440 three
1441 four
1442 five
1443 six
1444 seven
1445 eight
1446 nine
1447 ten
1448 "
1449 .unindent(),
1450 );
1451
1452 let buffer_text = "
1453 A
1454 one
1455 B
1456 two
1457 C
1458 three
1459 HELLO
1460 four
1461 five
1462 SIXTEEN
1463 seven
1464 eight
1465 WORLD
1466 nine
1467
1468 ten
1469
1470 "
1471 .unindent();
1472
1473 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1474 let diff = cx
1475 .update(|cx| {
1476 BufferDiff::build(buffer.snapshot(), Some(diff_base.clone()), None, None, cx)
1477 })
1478 .await;
1479 assert_eq!(
1480 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None)
1481 .count(),
1482 8
1483 );
1484
1485 assert_hunks(
1486 diff.hunks_intersecting_range(
1487 buffer.anchor_before(Point::new(7, 0))..buffer.anchor_before(Point::new(12, 0)),
1488 &buffer,
1489 None,
1490 ),
1491 &buffer,
1492 &diff_base,
1493 &[
1494 (6..7, "", "HELLO\n", DiffHunkStatus::added_none()),
1495 (9..10, "six\n", "SIXTEEN\n", DiffHunkStatus::modified_none()),
1496 (12..13, "", "WORLD\n", DiffHunkStatus::added_none()),
1497 ],
1498 );
1499 }
1500
1501 #[gpui::test]
1502 async fn test_stage_hunk(cx: &mut TestAppContext) {
1503 struct Example {
1504 name: &'static str,
1505 head_text: String,
1506 index_text: String,
1507 buffer_marked_text: String,
1508 final_index_text: String,
1509 }
1510
1511 let table = [
1512 Example {
1513 name: "uncommitted hunk straddles end of unstaged hunk",
1514 head_text: "
1515 one
1516 two
1517 three
1518 four
1519 five
1520 "
1521 .unindent(),
1522 index_text: "
1523 one
1524 TWO_HUNDRED
1525 three
1526 FOUR_HUNDRED
1527 five
1528 "
1529 .unindent(),
1530 buffer_marked_text: "
1531 ZERO
1532 one
1533 two
1534 «THREE_HUNDRED
1535 FOUR_HUNDRED»
1536 five
1537 SIX
1538 "
1539 .unindent(),
1540 final_index_text: "
1541 one
1542 two
1543 THREE_HUNDRED
1544 FOUR_HUNDRED
1545 five
1546 "
1547 .unindent(),
1548 },
1549 Example {
1550 name: "uncommitted hunk straddles start of unstaged hunk",
1551 head_text: "
1552 one
1553 two
1554 three
1555 four
1556 five
1557 "
1558 .unindent(),
1559 index_text: "
1560 one
1561 TWO_HUNDRED
1562 three
1563 FOUR_HUNDRED
1564 five
1565 "
1566 .unindent(),
1567 buffer_marked_text: "
1568 ZERO
1569 one
1570 «TWO_HUNDRED
1571 THREE_HUNDRED»
1572 four
1573 five
1574 SIX
1575 "
1576 .unindent(),
1577 final_index_text: "
1578 one
1579 TWO_HUNDRED
1580 THREE_HUNDRED
1581 four
1582 five
1583 "
1584 .unindent(),
1585 },
1586 Example {
1587 name: "uncommitted hunk strictly contains unstaged hunks",
1588 head_text: "
1589 one
1590 two
1591 three
1592 four
1593 five
1594 six
1595 seven
1596 "
1597 .unindent(),
1598 index_text: "
1599 one
1600 TWO
1601 THREE
1602 FOUR
1603 FIVE
1604 SIX
1605 seven
1606 "
1607 .unindent(),
1608 buffer_marked_text: "
1609 one
1610 TWO
1611 «THREE_HUNDRED
1612 FOUR
1613 FIVE_HUNDRED»
1614 SIX
1615 seven
1616 "
1617 .unindent(),
1618 final_index_text: "
1619 one
1620 TWO
1621 THREE_HUNDRED
1622 FOUR
1623 FIVE_HUNDRED
1624 SIX
1625 seven
1626 "
1627 .unindent(),
1628 },
1629 Example {
1630 name: "uncommitted deletion hunk",
1631 head_text: "
1632 one
1633 two
1634 three
1635 four
1636 five
1637 "
1638 .unindent(),
1639 index_text: "
1640 one
1641 two
1642 three
1643 four
1644 five
1645 "
1646 .unindent(),
1647 buffer_marked_text: "
1648 one
1649 ˇfive
1650 "
1651 .unindent(),
1652 final_index_text: "
1653 one
1654 five
1655 "
1656 .unindent(),
1657 },
1658 Example {
1659 name: "one unstaged hunk that contains two uncommitted hunks",
1660 head_text: "
1661 one
1662 two
1663
1664 three
1665 four
1666 "
1667 .unindent(),
1668 index_text: "
1669 one
1670 two
1671 three
1672 four
1673 "
1674 .unindent(),
1675 buffer_marked_text: "
1676 «one
1677
1678 three // modified
1679 four»
1680 "
1681 .unindent(),
1682 final_index_text: "
1683 one
1684
1685 three // modified
1686 four
1687 "
1688 .unindent(),
1689 },
1690 Example {
1691 name: "one uncommitted hunk that contains two unstaged hunks",
1692 head_text: "
1693 one
1694 two
1695 three
1696 four
1697 five
1698 "
1699 .unindent(),
1700 index_text: "
1701 ZERO
1702 one
1703 TWO
1704 THREE
1705 FOUR
1706 five
1707 "
1708 .unindent(),
1709 buffer_marked_text: "
1710 «one
1711 TWO_HUNDRED
1712 THREE
1713 FOUR_HUNDRED
1714 five»
1715 "
1716 .unindent(),
1717 final_index_text: "
1718 ZERO
1719 one
1720 TWO_HUNDRED
1721 THREE
1722 FOUR_HUNDRED
1723 five
1724 "
1725 .unindent(),
1726 },
1727 ];
1728
1729 for example in table {
1730 let (buffer_text, ranges) = marked_text_ranges(&example.buffer_marked_text, false);
1731 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1732 let hunk_range =
1733 buffer.anchor_before(ranges[0].start)..buffer.anchor_before(ranges[0].end);
1734
1735 let unstaged = BufferDiff::build_sync(buffer.clone(), example.index_text.clone(), cx);
1736 let uncommitted = BufferDiff::build_sync(buffer.clone(), example.head_text.clone(), cx);
1737
1738 let unstaged_diff = cx.new(|cx| {
1739 let mut diff = BufferDiff::new(&buffer, cx);
1740 diff.set_state(unstaged, &buffer);
1741 diff
1742 });
1743
1744 let uncommitted_diff = cx.new(|cx| {
1745 let mut diff = BufferDiff::new(&buffer, cx);
1746 diff.set_state(uncommitted, &buffer);
1747 diff.set_secondary_diff(unstaged_diff);
1748 diff
1749 });
1750
1751 uncommitted_diff.update(cx, |diff, cx| {
1752 let hunks = diff
1753 .hunks_intersecting_range(hunk_range.clone(), &buffer, &cx)
1754 .collect::<Vec<_>>();
1755 for hunk in &hunks {
1756 assert_ne!(
1757 hunk.secondary_status,
1758 DiffHunkSecondaryStatus::NoSecondaryHunk
1759 )
1760 }
1761
1762 let new_index_text = diff
1763 .stage_or_unstage_hunks(true, &hunks, &buffer, true, cx)
1764 .unwrap()
1765 .to_string();
1766
1767 let hunks = diff
1768 .hunks_intersecting_range(hunk_range.clone(), &buffer, &cx)
1769 .collect::<Vec<_>>();
1770 for hunk in &hunks {
1771 assert_eq!(
1772 hunk.secondary_status,
1773 DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
1774 )
1775 }
1776
1777 pretty_assertions::assert_eq!(
1778 new_index_text,
1779 example.final_index_text,
1780 "example: {}",
1781 example.name
1782 );
1783 });
1784 }
1785 }
1786
1787 #[gpui::test]
1788 async fn test_toggling_stage_and_unstage_same_hunk(cx: &mut TestAppContext) {
1789 let head_text = "
1790 one
1791 two
1792 three
1793 "
1794 .unindent();
1795 let index_text = head_text.clone();
1796 let buffer_text = "
1797 one
1798 three
1799 "
1800 .unindent();
1801
1802 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text.clone());
1803 let unstaged = BufferDiff::build_sync(buffer.clone(), index_text, cx);
1804 let uncommitted = BufferDiff::build_sync(buffer.clone(), head_text.clone(), cx);
1805 let unstaged_diff = cx.new(|cx| {
1806 let mut diff = BufferDiff::new(&buffer, cx);
1807 diff.set_state(unstaged, &buffer);
1808 diff
1809 });
1810 let uncommitted_diff = cx.new(|cx| {
1811 let mut diff = BufferDiff::new(&buffer, cx);
1812 diff.set_state(uncommitted, &buffer);
1813 diff.set_secondary_diff(unstaged_diff.clone());
1814 diff
1815 });
1816
1817 uncommitted_diff.update(cx, |diff, cx| {
1818 let hunk = diff.hunks(&buffer, cx).next().unwrap();
1819
1820 let new_index_text = diff
1821 .stage_or_unstage_hunks(true, &[hunk.clone()], &buffer, true, cx)
1822 .unwrap()
1823 .to_string();
1824 assert_eq!(new_index_text, buffer_text);
1825
1826 let hunk = diff.hunks(&buffer, &cx).next().unwrap();
1827 assert_eq!(
1828 hunk.secondary_status,
1829 DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
1830 );
1831
1832 let index_text = diff
1833 .stage_or_unstage_hunks(false, &[hunk], &buffer, true, cx)
1834 .unwrap()
1835 .to_string();
1836 assert_eq!(index_text, head_text);
1837
1838 let hunk = diff.hunks(&buffer, &cx).next().unwrap();
1839 // optimistically unstaged (fine, could also be HasSecondaryHunk)
1840 assert_eq!(
1841 hunk.secondary_status,
1842 DiffHunkSecondaryStatus::SecondaryHunkAdditionPending
1843 );
1844 });
1845 }
1846
1847 #[gpui::test]
1848 async fn test_buffer_diff_compare(cx: &mut TestAppContext) {
1849 let base_text = "
1850 zero
1851 one
1852 two
1853 three
1854 four
1855 five
1856 six
1857 seven
1858 eight
1859 nine
1860 "
1861 .unindent();
1862
1863 let buffer_text_1 = "
1864 one
1865 three
1866 four
1867 five
1868 SIX
1869 seven
1870 eight
1871 NINE
1872 "
1873 .unindent();
1874
1875 let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text_1);
1876
1877 let empty_diff = cx.update(|cx| BufferDiff::build_empty(&buffer, cx));
1878 let diff_1 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1879 let range = diff_1.compare(&empty_diff, &buffer).unwrap();
1880 assert_eq!(range.to_point(&buffer), Point::new(0, 0)..Point::new(8, 0));
1881
1882 // Edit does not affect the diff.
1883 buffer.edit_via_marked_text(
1884 &"
1885 one
1886 three
1887 four
1888 five
1889 «SIX.5»
1890 seven
1891 eight
1892 NINE
1893 "
1894 .unindent(),
1895 );
1896 let diff_2 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1897 assert_eq!(None, diff_2.compare(&diff_1, &buffer));
1898
1899 // Edit turns a deletion hunk into a modification.
1900 buffer.edit_via_marked_text(
1901 &"
1902 one
1903 «THREE»
1904 four
1905 five
1906 SIX.5
1907 seven
1908 eight
1909 NINE
1910 "
1911 .unindent(),
1912 );
1913 let diff_3 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1914 let range = diff_3.compare(&diff_2, &buffer).unwrap();
1915 assert_eq!(range.to_point(&buffer), Point::new(1, 0)..Point::new(2, 0));
1916
1917 // Edit turns a modification hunk into a deletion.
1918 buffer.edit_via_marked_text(
1919 &"
1920 one
1921 THREE
1922 four
1923 five«»
1924 seven
1925 eight
1926 NINE
1927 "
1928 .unindent(),
1929 );
1930 let diff_4 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1931 let range = diff_4.compare(&diff_3, &buffer).unwrap();
1932 assert_eq!(range.to_point(&buffer), Point::new(3, 4)..Point::new(4, 0));
1933
1934 // Edit introduces a new insertion hunk.
1935 buffer.edit_via_marked_text(
1936 &"
1937 one
1938 THREE
1939 four«
1940 FOUR.5
1941 »five
1942 seven
1943 eight
1944 NINE
1945 "
1946 .unindent(),
1947 );
1948 let diff_5 = BufferDiff::build_sync(buffer.snapshot(), base_text.clone(), cx);
1949 let range = diff_5.compare(&diff_4, &buffer).unwrap();
1950 assert_eq!(range.to_point(&buffer), Point::new(3, 0)..Point::new(4, 0));
1951
1952 // Edit removes a hunk.
1953 buffer.edit_via_marked_text(
1954 &"
1955 one
1956 THREE
1957 four
1958 FOUR.5
1959 five
1960 seven
1961 eight
1962 «nine»
1963 "
1964 .unindent(),
1965 );
1966 let diff_6 = BufferDiff::build_sync(buffer.snapshot(), base_text, cx);
1967 let range = diff_6.compare(&diff_5, &buffer).unwrap();
1968 assert_eq!(range.to_point(&buffer), Point::new(7, 0)..Point::new(8, 0));
1969 }
1970
1971 #[gpui::test(iterations = 100)]
1972 async fn test_staging_and_unstaging_hunks(cx: &mut TestAppContext, mut rng: StdRng) {
1973 fn gen_line(rng: &mut StdRng) -> String {
1974 if rng.gen_bool(0.2) {
1975 "\n".to_owned()
1976 } else {
1977 let c = rng.gen_range('A'..='Z');
1978 format!("{c}{c}{c}\n")
1979 }
1980 }
1981
1982 fn gen_working_copy(rng: &mut StdRng, head: &str) -> String {
1983 let mut old_lines = {
1984 let mut old_lines = Vec::new();
1985 let mut old_lines_iter = head.lines();
1986 while let Some(line) = old_lines_iter.next() {
1987 assert!(!line.ends_with("\n"));
1988 old_lines.push(line.to_owned());
1989 }
1990 if old_lines.last().is_some_and(|line| line.is_empty()) {
1991 old_lines.pop();
1992 }
1993 old_lines.into_iter()
1994 };
1995 let mut result = String::new();
1996 let unchanged_count = rng.gen_range(0..=old_lines.len());
1997 result +=
1998 &old_lines
1999 .by_ref()
2000 .take(unchanged_count)
2001 .fold(String::new(), |mut s, line| {
2002 writeln!(&mut s, "{line}").unwrap();
2003 s
2004 });
2005 while old_lines.len() > 0 {
2006 let deleted_count = rng.gen_range(0..=old_lines.len());
2007 let _advance = old_lines
2008 .by_ref()
2009 .take(deleted_count)
2010 .map(|line| line.len() + 1)
2011 .sum::<usize>();
2012 let minimum_added = if deleted_count == 0 { 1 } else { 0 };
2013 let added_count = rng.gen_range(minimum_added..=5);
2014 let addition = (0..added_count).map(|_| gen_line(rng)).collect::<String>();
2015 result += &addition;
2016
2017 if old_lines.len() > 0 {
2018 let blank_lines = old_lines.clone().take_while(|line| line.is_empty()).count();
2019 if blank_lines == old_lines.len() {
2020 break;
2021 };
2022 let unchanged_count = rng.gen_range((blank_lines + 1).max(1)..=old_lines.len());
2023 result += &old_lines.by_ref().take(unchanged_count).fold(
2024 String::new(),
2025 |mut s, line| {
2026 writeln!(&mut s, "{line}").unwrap();
2027 s
2028 },
2029 );
2030 }
2031 }
2032 result
2033 }
2034
2035 fn uncommitted_diff(
2036 working_copy: &language::BufferSnapshot,
2037 index_text: &Rope,
2038 head_text: String,
2039 cx: &mut TestAppContext,
2040 ) -> Entity<BufferDiff> {
2041 let inner = BufferDiff::build_sync(working_copy.text.clone(), head_text, cx);
2042 let secondary = BufferDiff {
2043 buffer_id: working_copy.remote_id(),
2044 inner: BufferDiff::build_sync(
2045 working_copy.text.clone(),
2046 index_text.to_string(),
2047 cx,
2048 ),
2049 secondary_diff: None,
2050 };
2051 let secondary = cx.new(|_| secondary);
2052 cx.new(|_| BufferDiff {
2053 buffer_id: working_copy.remote_id(),
2054 inner,
2055 secondary_diff: Some(secondary),
2056 })
2057 }
2058
2059 let operations = std::env::var("OPERATIONS")
2060 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2061 .unwrap_or(10);
2062
2063 let rng = &mut rng;
2064 let head_text = ('a'..='z').fold(String::new(), |mut s, c| {
2065 writeln!(&mut s, "{c}{c}{c}").unwrap();
2066 s
2067 });
2068 let working_copy = gen_working_copy(rng, &head_text);
2069 let working_copy = cx.new(|cx| {
2070 language::Buffer::local_normalized(
2071 Rope::from(working_copy.as_str()),
2072 text::LineEnding::default(),
2073 cx,
2074 )
2075 });
2076 let working_copy = working_copy.read_with(cx, |working_copy, _| working_copy.snapshot());
2077 let mut index_text = if rng.r#gen() {
2078 Rope::from(head_text.as_str())
2079 } else {
2080 working_copy.as_rope().clone()
2081 };
2082
2083 let mut diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
2084 let mut hunks = diff.update(cx, |diff, cx| {
2085 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
2086 .collect::<Vec<_>>()
2087 });
2088 if hunks.len() == 0 {
2089 return;
2090 }
2091
2092 for _ in 0..operations {
2093 let i = rng.gen_range(0..hunks.len());
2094 let hunk = &mut hunks[i];
2095 let hunk_to_change = hunk.clone();
2096 let stage = match hunk.secondary_status {
2097 DiffHunkSecondaryStatus::HasSecondaryHunk => {
2098 hunk.secondary_status = DiffHunkSecondaryStatus::NoSecondaryHunk;
2099 true
2100 }
2101 DiffHunkSecondaryStatus::NoSecondaryHunk => {
2102 hunk.secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
2103 false
2104 }
2105 _ => unreachable!(),
2106 };
2107
2108 index_text = diff.update(cx, |diff, cx| {
2109 diff.stage_or_unstage_hunks(stage, &[hunk_to_change], &working_copy, true, cx)
2110 .unwrap()
2111 });
2112
2113 diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
2114 let found_hunks = diff.update(cx, |diff, cx| {
2115 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
2116 .collect::<Vec<_>>()
2117 });
2118 assert_eq!(hunks.len(), found_hunks.len());
2119
2120 for (expected_hunk, found_hunk) in hunks.iter().zip(&found_hunks) {
2121 assert_eq!(
2122 expected_hunk.buffer_range.to_point(&working_copy),
2123 found_hunk.buffer_range.to_point(&working_copy)
2124 );
2125 assert_eq!(
2126 expected_hunk.diff_base_byte_range,
2127 found_hunk.diff_base_byte_range
2128 );
2129 assert_eq!(expected_hunk.secondary_status, found_hunk.secondary_status);
2130 }
2131 hunks = found_hunks;
2132 }
2133 }
2134}