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