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
666pub enum BufferDiffEvent {
667 DiffChanged {
668 changed_range: Option<Range<text::Anchor>>,
669 },
670 LanguageChanged,
671}
672
673impl EventEmitter<BufferDiffEvent> for BufferDiff {}
674
675impl BufferDiff {
676 #[cfg(test)]
677 fn build_sync(
678 buffer: text::BufferSnapshot,
679 diff_base: String,
680 cx: &mut gpui::TestAppContext,
681 ) -> BufferDiffInner {
682 let snapshot =
683 cx.update(|cx| Self::build(buffer, Some(Arc::new(diff_base)), None, None, cx));
684 cx.executor().block(snapshot)
685 }
686
687 fn build(
688 buffer: text::BufferSnapshot,
689 base_text: Option<Arc<String>>,
690 language: Option<Arc<Language>>,
691 language_registry: Option<Arc<LanguageRegistry>>,
692 cx: &mut App,
693 ) -> impl Future<Output = BufferDiffInner> {
694 let base_text_pair;
695 let base_text_exists;
696 let base_text_snapshot;
697 if let Some(text) = &base_text {
698 let base_text_rope = Rope::from(text.as_str());
699 base_text_pair = Some((text.clone(), base_text_rope.clone()));
700 let snapshot = language::Buffer::build_snapshot(
701 base_text_rope,
702 language.clone(),
703 language_registry.clone(),
704 cx,
705 );
706 base_text_snapshot = cx.background_spawn(snapshot);
707 base_text_exists = true;
708 } else {
709 base_text_pair = None;
710 base_text_snapshot = Task::ready(language::Buffer::build_empty_snapshot(cx));
711 base_text_exists = false;
712 };
713
714 let hunks = cx.background_spawn({
715 let buffer = buffer.clone();
716 async move { compute_hunks(base_text_pair, buffer) }
717 });
718
719 async move {
720 let (base_text, hunks) = futures::join!(base_text_snapshot, hunks);
721 BufferDiffInner {
722 base_text,
723 hunks,
724 base_text_exists,
725 pending_hunks: TreeMap::default(),
726 }
727 }
728 }
729
730 fn build_with_base_buffer(
731 buffer: text::BufferSnapshot,
732 base_text: Option<Arc<String>>,
733 base_text_snapshot: language::BufferSnapshot,
734 cx: &App,
735 ) -> impl Future<Output = BufferDiffInner> {
736 let base_text_exists = base_text.is_some();
737 let base_text_pair = base_text.map(|text| (text, base_text_snapshot.as_rope().clone()));
738 cx.background_spawn(async move {
739 BufferDiffInner {
740 base_text: base_text_snapshot,
741 hunks: compute_hunks(base_text_pair, buffer),
742 pending_hunks: TreeMap::default(),
743 base_text_exists,
744 }
745 })
746 }
747
748 fn build_empty(buffer: &text::BufferSnapshot, cx: &mut App) -> BufferDiffInner {
749 BufferDiffInner {
750 base_text: language::Buffer::build_empty_snapshot(cx),
751 hunks: SumTree::new(buffer),
752 pending_hunks: TreeMap::default(),
753 base_text_exists: false,
754 }
755 }
756
757 pub fn set_secondary_diff(&mut self, diff: Entity<BufferDiff>) {
758 self.secondary_diff = Some(diff);
759 }
760
761 pub fn secondary_diff(&self) -> Option<Entity<BufferDiff>> {
762 self.secondary_diff.clone()
763 }
764
765 pub fn stage_or_unstage_hunks(
766 &mut self,
767 stage: bool,
768 hunks: &[DiffHunk],
769 buffer: &text::BufferSnapshot,
770 file_exists: bool,
771 cx: &mut Context<Self>,
772 ) -> Option<Rope> {
773 let (new_index_text, pending_hunks) = self.inner.stage_or_unstage_hunks(
774 &self.secondary_diff.as_ref()?.read(cx).inner,
775 stage,
776 &hunks,
777 buffer,
778 file_exists,
779 );
780 if let Some(unstaged_diff) = &self.secondary_diff {
781 unstaged_diff.update(cx, |diff, _| {
782 for (offset, pending_hunk) in pending_hunks {
783 diff.inner.pending_hunks.insert(offset, pending_hunk);
784 }
785 });
786 }
787 if let Some((first, last)) = hunks.first().zip(hunks.last()) {
788 let changed_range = first.buffer_range.start..last.buffer_range.end;
789 cx.emit(BufferDiffEvent::DiffChanged {
790 changed_range: Some(changed_range),
791 });
792 }
793 new_index_text
794 }
795
796 pub fn range_to_hunk_range(
797 &self,
798 range: Range<Anchor>,
799 buffer: &text::BufferSnapshot,
800 cx: &App,
801 ) -> Option<Range<Anchor>> {
802 let start = self
803 .hunks_intersecting_range(range.clone(), &buffer, cx)
804 .next()?
805 .buffer_range
806 .start;
807 let end = self
808 .hunks_intersecting_range_rev(range.clone(), &buffer)
809 .next()?
810 .buffer_range
811 .end;
812 Some(start..end)
813 }
814
815 #[allow(clippy::too_many_arguments)]
816 pub async fn update_diff(
817 this: Entity<BufferDiff>,
818 buffer: text::BufferSnapshot,
819 base_text: Option<Arc<String>>,
820 base_text_changed: bool,
821 language_changed: bool,
822 language: Option<Arc<Language>>,
823 language_registry: Option<Arc<LanguageRegistry>>,
824 cx: &mut AsyncApp,
825 ) -> anyhow::Result<Option<Range<Anchor>>> {
826 let snapshot = if base_text_changed || language_changed {
827 cx.update(|cx| {
828 Self::build(
829 buffer.clone(),
830 base_text,
831 language.clone(),
832 language_registry.clone(),
833 cx,
834 )
835 })?
836 .await
837 } else {
838 this.read_with(cx, |this, cx| {
839 Self::build_with_base_buffer(
840 buffer.clone(),
841 base_text,
842 this.base_text().clone(),
843 cx,
844 )
845 })?
846 .await
847 };
848
849 this.update(cx, |this, _| this.set_state(snapshot, &buffer))
850 }
851
852 pub fn update_diff_from(
853 &mut self,
854 buffer: &text::BufferSnapshot,
855 other: &Entity<Self>,
856 cx: &mut Context<Self>,
857 ) -> Option<Range<Anchor>> {
858 let other = other.read(cx).inner.clone();
859 self.set_state(other, buffer)
860 }
861
862 fn set_state(
863 &mut self,
864 new_state: BufferDiffInner,
865 buffer: &text::BufferSnapshot,
866 ) -> Option<Range<Anchor>> {
867 let (base_text_changed, changed_range) =
868 match (self.inner.base_text_exists, new_state.base_text_exists) {
869 (false, false) => (true, None),
870 (true, true)
871 if self.inner.base_text.remote_id() == new_state.base_text.remote_id() =>
872 {
873 (false, new_state.compare(&self.inner, buffer))
874 }
875 _ => (true, Some(text::Anchor::MIN..text::Anchor::MAX)),
876 };
877 let pending_hunks = mem::take(&mut self.inner.pending_hunks);
878 self.inner = new_state;
879 if !base_text_changed {
880 self.inner.pending_hunks = pending_hunks;
881 }
882 changed_range
883 }
884
885 pub fn base_text(&self) -> &language::BufferSnapshot {
886 &self.inner.base_text
887 }
888
889 pub fn base_text_exists(&self) -> bool {
890 self.inner.base_text_exists
891 }
892
893 pub fn snapshot(&self, cx: &App) -> BufferDiffSnapshot {
894 BufferDiffSnapshot {
895 inner: self.inner.clone(),
896 secondary_diff: self
897 .secondary_diff
898 .as_ref()
899 .map(|diff| Box::new(diff.read(cx).snapshot(cx))),
900 }
901 }
902
903 pub fn hunks_intersecting_range<'a>(
904 &'a self,
905 range: Range<text::Anchor>,
906 buffer_snapshot: &'a text::BufferSnapshot,
907 cx: &'a App,
908 ) -> impl 'a + Iterator<Item = DiffHunk> {
909 let unstaged_counterpart = self
910 .secondary_diff
911 .as_ref()
912 .map(|diff| &diff.read(cx).inner);
913 self.inner
914 .hunks_intersecting_range(range, buffer_snapshot, unstaged_counterpart)
915 }
916
917 pub fn hunks_intersecting_range_rev<'a>(
918 &'a self,
919 range: Range<text::Anchor>,
920 buffer_snapshot: &'a text::BufferSnapshot,
921 ) -> impl 'a + Iterator<Item = DiffHunk> {
922 self.inner
923 .hunks_intersecting_range_rev(range, buffer_snapshot)
924 }
925
926 pub fn hunks_in_row_range<'a>(
927 &'a self,
928 range: Range<u32>,
929 buffer: &'a text::BufferSnapshot,
930 cx: &'a App,
931 ) -> impl 'a + Iterator<Item = DiffHunk> {
932 let start = buffer.anchor_before(Point::new(range.start, 0));
933 let end = buffer.anchor_after(Point::new(range.end, 0));
934 self.hunks_intersecting_range(start..end, buffer, cx)
935 }
936
937 /// Used in cases where the change set isn't derived from git.
938 pub fn set_base_text(
939 &mut self,
940 base_buffer: Entity<language::Buffer>,
941 buffer: text::BufferSnapshot,
942 cx: &mut Context<Self>,
943 ) -> oneshot::Receiver<()> {
944 let (tx, rx) = oneshot::channel();
945 let this = cx.weak_entity();
946 let base_buffer = base_buffer.read(cx);
947 let language_registry = base_buffer.language_registry();
948 let base_buffer = base_buffer.snapshot();
949 let base_text = Arc::new(base_buffer.text());
950
951 let snapshot = BufferDiff::build(
952 buffer.clone(),
953 Some(base_text),
954 base_buffer.language().cloned(),
955 language_registry,
956 cx,
957 );
958 let complete_on_drop = util::defer(|| {
959 tx.send(()).ok();
960 });
961 cx.spawn(|_, mut cx| async move {
962 let snapshot = snapshot.await;
963 let Some(this) = this.upgrade() else {
964 return;
965 };
966 this.update(&mut cx, |this, _| {
967 this.set_state(snapshot, &buffer);
968 })
969 .log_err();
970 drop(complete_on_drop)
971 })
972 .detach();
973 rx
974 }
975
976 pub fn base_text_string(&self) -> Option<String> {
977 self.inner
978 .base_text_exists
979 .then(|| self.inner.base_text.text())
980 }
981
982 pub fn new(buffer: &text::BufferSnapshot, cx: &mut App) -> Self {
983 BufferDiff {
984 buffer_id: buffer.remote_id(),
985 inner: BufferDiff::build_empty(buffer, cx),
986 secondary_diff: None,
987 }
988 }
989
990 #[cfg(any(test, feature = "test-support"))]
991 pub fn new_with_base_text(
992 base_text: &str,
993 buffer: &Entity<language::Buffer>,
994 cx: &mut App,
995 ) -> Self {
996 let mut base_text = base_text.to_owned();
997 text::LineEnding::normalize(&mut base_text);
998 let snapshot = BufferDiff::build(
999 buffer.read(cx).text_snapshot(),
1000 Some(base_text.into()),
1001 None,
1002 None,
1003 cx,
1004 );
1005 let snapshot = cx.background_executor().block(snapshot);
1006 BufferDiff {
1007 buffer_id: buffer.read(cx).remote_id(),
1008 inner: snapshot,
1009 secondary_diff: None,
1010 }
1011 }
1012
1013 #[cfg(any(test, feature = "test-support"))]
1014 pub fn recalculate_diff_sync(&mut self, buffer: text::BufferSnapshot, cx: &mut Context<Self>) {
1015 let base_text = self.base_text_string().map(Arc::new);
1016 let snapshot = BufferDiff::build_with_base_buffer(
1017 buffer.clone(),
1018 base_text,
1019 self.inner.base_text.clone(),
1020 cx,
1021 );
1022 let snapshot = cx.background_executor().block(snapshot);
1023 let changed_range = self.set_state(snapshot, &buffer);
1024 cx.emit(BufferDiffEvent::DiffChanged { changed_range });
1025 }
1026}
1027
1028impl DiffHunk {
1029 pub fn is_created_file(&self) -> bool {
1030 self.diff_base_byte_range == (0..0) && self.buffer_range == (Anchor::MIN..Anchor::MAX)
1031 }
1032
1033 pub fn status(&self) -> DiffHunkStatus {
1034 let kind = if self.buffer_range.start == self.buffer_range.end {
1035 DiffHunkStatusKind::Deleted
1036 } else if self.diff_base_byte_range.is_empty() {
1037 DiffHunkStatusKind::Added
1038 } else {
1039 DiffHunkStatusKind::Modified
1040 };
1041 DiffHunkStatus {
1042 kind,
1043 secondary: self.secondary_status,
1044 }
1045 }
1046}
1047
1048impl DiffHunkStatus {
1049 pub fn has_secondary_hunk(&self) -> bool {
1050 matches!(
1051 self.secondary,
1052 DiffHunkSecondaryStatus::HasSecondaryHunk
1053 | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending
1054 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
1055 )
1056 }
1057
1058 pub fn is_pending(&self) -> bool {
1059 matches!(
1060 self.secondary,
1061 DiffHunkSecondaryStatus::SecondaryHunkAdditionPending
1062 | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
1063 )
1064 }
1065
1066 pub fn is_deleted(&self) -> bool {
1067 self.kind == DiffHunkStatusKind::Deleted
1068 }
1069
1070 pub fn is_added(&self) -> bool {
1071 self.kind == DiffHunkStatusKind::Added
1072 }
1073
1074 pub fn is_modified(&self) -> bool {
1075 self.kind == DiffHunkStatusKind::Modified
1076 }
1077
1078 pub fn added(secondary: DiffHunkSecondaryStatus) -> Self {
1079 Self {
1080 kind: DiffHunkStatusKind::Added,
1081 secondary,
1082 }
1083 }
1084
1085 pub fn modified(secondary: DiffHunkSecondaryStatus) -> Self {
1086 Self {
1087 kind: DiffHunkStatusKind::Modified,
1088 secondary,
1089 }
1090 }
1091
1092 pub fn deleted(secondary: DiffHunkSecondaryStatus) -> Self {
1093 Self {
1094 kind: DiffHunkStatusKind::Deleted,
1095 secondary,
1096 }
1097 }
1098
1099 pub fn deleted_none() -> Self {
1100 Self {
1101 kind: DiffHunkStatusKind::Deleted,
1102 secondary: DiffHunkSecondaryStatus::None,
1103 }
1104 }
1105
1106 pub fn added_none() -> Self {
1107 Self {
1108 kind: DiffHunkStatusKind::Added,
1109 secondary: DiffHunkSecondaryStatus::None,
1110 }
1111 }
1112
1113 pub fn modified_none() -> Self {
1114 Self {
1115 kind: DiffHunkStatusKind::Modified,
1116 secondary: DiffHunkSecondaryStatus::None,
1117 }
1118 }
1119}
1120
1121/// Range (crossing new lines), old, new
1122#[cfg(any(test, feature = "test-support"))]
1123#[track_caller]
1124pub fn assert_hunks<Iter>(
1125 diff_hunks: Iter,
1126 buffer: &text::BufferSnapshot,
1127 diff_base: &str,
1128 expected_hunks: &[(Range<u32>, &str, &str, DiffHunkStatus)],
1129) where
1130 Iter: Iterator<Item = DiffHunk>,
1131{
1132 let actual_hunks = diff_hunks
1133 .map(|hunk| {
1134 (
1135 hunk.range.clone(),
1136 &diff_base[hunk.diff_base_byte_range.clone()],
1137 buffer
1138 .text_for_range(hunk.range.clone())
1139 .collect::<String>(),
1140 hunk.status(),
1141 )
1142 })
1143 .collect::<Vec<_>>();
1144
1145 let expected_hunks: Vec<_> = expected_hunks
1146 .iter()
1147 .map(|(r, old_text, new_text, status)| {
1148 (
1149 Point::new(r.start, 0)..Point::new(r.end, 0),
1150 *old_text,
1151 new_text.to_string(),
1152 *status,
1153 )
1154 })
1155 .collect();
1156
1157 assert_eq!(actual_hunks, expected_hunks);
1158}
1159
1160#[cfg(test)]
1161mod tests {
1162 use std::fmt::Write as _;
1163
1164 use super::*;
1165 use gpui::TestAppContext;
1166 use rand::{rngs::StdRng, Rng as _};
1167 use text::{Buffer, BufferId, Rope};
1168 use unindent::Unindent as _;
1169 use util::test::marked_text_ranges;
1170
1171 #[ctor::ctor]
1172 fn init_logger() {
1173 if std::env::var("RUST_LOG").is_ok() {
1174 env_logger::init();
1175 }
1176 }
1177
1178 #[gpui::test]
1179 async fn test_buffer_diff_simple(cx: &mut gpui::TestAppContext) {
1180 let diff_base = "
1181 one
1182 two
1183 three
1184 "
1185 .unindent();
1186
1187 let buffer_text = "
1188 one
1189 HELLO
1190 three
1191 "
1192 .unindent();
1193
1194 let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1195 let mut diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1196 assert_hunks(
1197 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1198 &buffer,
1199 &diff_base,
1200 &[(1..2, "two\n", "HELLO\n", DiffHunkStatus::modified_none())],
1201 );
1202
1203 buffer.edit([(0..0, "point five\n")]);
1204 diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1205 assert_hunks(
1206 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1207 &buffer,
1208 &diff_base,
1209 &[
1210 (0..1, "", "point five\n", DiffHunkStatus::added_none()),
1211 (2..3, "two\n", "HELLO\n", DiffHunkStatus::modified_none()),
1212 ],
1213 );
1214
1215 diff = cx.update(|cx| BufferDiff::build_empty(&buffer, cx));
1216 assert_hunks(
1217 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1218 &buffer,
1219 &diff_base,
1220 &[],
1221 );
1222 }
1223
1224 #[gpui::test]
1225 async fn test_buffer_diff_with_secondary(cx: &mut gpui::TestAppContext) {
1226 let head_text = "
1227 zero
1228 one
1229 two
1230 three
1231 four
1232 five
1233 six
1234 seven
1235 eight
1236 nine
1237 "
1238 .unindent();
1239
1240 let index_text = "
1241 zero
1242 one
1243 TWO
1244 three
1245 FOUR
1246 five
1247 six
1248 seven
1249 eight
1250 NINE
1251 "
1252 .unindent();
1253
1254 let buffer_text = "
1255 zero
1256 one
1257 TWO
1258 three
1259 FOUR
1260 FIVE
1261 six
1262 SEVEN
1263 eight
1264 nine
1265 "
1266 .unindent();
1267
1268 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1269 let unstaged_diff = BufferDiff::build_sync(buffer.clone(), index_text.clone(), cx);
1270
1271 let uncommitted_diff = BufferDiff::build_sync(buffer.clone(), head_text.clone(), cx);
1272
1273 let expected_hunks = vec![
1274 (2..3, "two\n", "TWO\n", DiffHunkStatus::modified_none()),
1275 (
1276 4..6,
1277 "four\nfive\n",
1278 "FOUR\nFIVE\n",
1279 DiffHunkStatus::modified(DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk),
1280 ),
1281 (
1282 7..8,
1283 "seven\n",
1284 "SEVEN\n",
1285 DiffHunkStatus::modified(DiffHunkSecondaryStatus::HasSecondaryHunk),
1286 ),
1287 ];
1288
1289 assert_hunks(
1290 uncommitted_diff.hunks_intersecting_range(
1291 Anchor::MIN..Anchor::MAX,
1292 &buffer,
1293 Some(&unstaged_diff),
1294 ),
1295 &buffer,
1296 &head_text,
1297 &expected_hunks,
1298 );
1299 }
1300
1301 #[gpui::test]
1302 async fn test_buffer_diff_range(cx: &mut TestAppContext) {
1303 let diff_base = Arc::new(
1304 "
1305 one
1306 two
1307 three
1308 four
1309 five
1310 six
1311 seven
1312 eight
1313 nine
1314 ten
1315 "
1316 .unindent(),
1317 );
1318
1319 let buffer_text = "
1320 A
1321 one
1322 B
1323 two
1324 C
1325 three
1326 HELLO
1327 four
1328 five
1329 SIXTEEN
1330 seven
1331 eight
1332 WORLD
1333 nine
1334
1335 ten
1336
1337 "
1338 .unindent();
1339
1340 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1341 let diff = cx
1342 .update(|cx| {
1343 BufferDiff::build(buffer.snapshot(), Some(diff_base.clone()), None, None, cx)
1344 })
1345 .await;
1346 assert_eq!(
1347 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None)
1348 .count(),
1349 8
1350 );
1351
1352 assert_hunks(
1353 diff.hunks_intersecting_range(
1354 buffer.anchor_before(Point::new(7, 0))..buffer.anchor_before(Point::new(12, 0)),
1355 &buffer,
1356 None,
1357 ),
1358 &buffer,
1359 &diff_base,
1360 &[
1361 (6..7, "", "HELLO\n", DiffHunkStatus::added_none()),
1362 (9..10, "six\n", "SIXTEEN\n", DiffHunkStatus::modified_none()),
1363 (12..13, "", "WORLD\n", DiffHunkStatus::added_none()),
1364 ],
1365 );
1366 }
1367
1368 #[gpui::test]
1369 async fn test_stage_hunk(cx: &mut TestAppContext) {
1370 struct Example {
1371 name: &'static str,
1372 head_text: String,
1373 index_text: String,
1374 buffer_marked_text: String,
1375 final_index_text: String,
1376 }
1377
1378 let table = [
1379 Example {
1380 name: "uncommitted hunk straddles end of unstaged hunk",
1381 head_text: "
1382 one
1383 two
1384 three
1385 four
1386 five
1387 "
1388 .unindent(),
1389 index_text: "
1390 one
1391 TWO_HUNDRED
1392 three
1393 FOUR_HUNDRED
1394 five
1395 "
1396 .unindent(),
1397 buffer_marked_text: "
1398 ZERO
1399 one
1400 two
1401 «THREE_HUNDRED
1402 FOUR_HUNDRED»
1403 five
1404 SIX
1405 "
1406 .unindent(),
1407 final_index_text: "
1408 one
1409 two
1410 THREE_HUNDRED
1411 FOUR_HUNDRED
1412 five
1413 "
1414 .unindent(),
1415 },
1416 Example {
1417 name: "uncommitted hunk straddles start of unstaged hunk",
1418 head_text: "
1419 one
1420 two
1421 three
1422 four
1423 five
1424 "
1425 .unindent(),
1426 index_text: "
1427 one
1428 TWO_HUNDRED
1429 three
1430 FOUR_HUNDRED
1431 five
1432 "
1433 .unindent(),
1434 buffer_marked_text: "
1435 ZERO
1436 one
1437 «TWO_HUNDRED
1438 THREE_HUNDRED»
1439 four
1440 five
1441 SIX
1442 "
1443 .unindent(),
1444 final_index_text: "
1445 one
1446 TWO_HUNDRED
1447 THREE_HUNDRED
1448 four
1449 five
1450 "
1451 .unindent(),
1452 },
1453 Example {
1454 name: "uncommitted hunk strictly contains unstaged hunks",
1455 head_text: "
1456 one
1457 two
1458 three
1459 four
1460 five
1461 six
1462 seven
1463 "
1464 .unindent(),
1465 index_text: "
1466 one
1467 TWO
1468 THREE
1469 FOUR
1470 FIVE
1471 SIX
1472 seven
1473 "
1474 .unindent(),
1475 buffer_marked_text: "
1476 one
1477 TWO
1478 «THREE_HUNDRED
1479 FOUR
1480 FIVE_HUNDRED»
1481 SIX
1482 seven
1483 "
1484 .unindent(),
1485 final_index_text: "
1486 one
1487 TWO
1488 THREE_HUNDRED
1489 FOUR
1490 FIVE_HUNDRED
1491 SIX
1492 seven
1493 "
1494 .unindent(),
1495 },
1496 Example {
1497 name: "uncommitted deletion hunk",
1498 head_text: "
1499 one
1500 two
1501 three
1502 four
1503 five
1504 "
1505 .unindent(),
1506 index_text: "
1507 one
1508 two
1509 three
1510 four
1511 five
1512 "
1513 .unindent(),
1514 buffer_marked_text: "
1515 one
1516 ˇfive
1517 "
1518 .unindent(),
1519 final_index_text: "
1520 one
1521 five
1522 "
1523 .unindent(),
1524 },
1525 ];
1526
1527 for example in table {
1528 let (buffer_text, ranges) = marked_text_ranges(&example.buffer_marked_text, false);
1529 let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1530 let hunk_range =
1531 buffer.anchor_before(ranges[0].start)..buffer.anchor_before(ranges[0].end);
1532
1533 let unstaged = BufferDiff::build_sync(buffer.clone(), example.index_text.clone(), cx);
1534 let uncommitted = BufferDiff::build_sync(buffer.clone(), example.head_text.clone(), cx);
1535
1536 let unstaged_diff = cx.new(|cx| {
1537 let mut diff = BufferDiff::new(&buffer, cx);
1538 diff.set_state(unstaged, &buffer);
1539 diff
1540 });
1541
1542 let uncommitted_diff = cx.new(|cx| {
1543 let mut diff = BufferDiff::new(&buffer, cx);
1544 diff.set_state(uncommitted, &buffer);
1545 diff.set_secondary_diff(unstaged_diff);
1546 diff
1547 });
1548
1549 uncommitted_diff.update(cx, |diff, cx| {
1550 let hunks = diff
1551 .hunks_intersecting_range(hunk_range.clone(), &buffer, &cx)
1552 .collect::<Vec<_>>();
1553 for hunk in &hunks {
1554 assert_ne!(hunk.secondary_status, DiffHunkSecondaryStatus::None)
1555 }
1556
1557 let new_index_text = diff
1558 .stage_or_unstage_hunks(true, &hunks, &buffer, true, cx)
1559 .unwrap()
1560 .to_string();
1561
1562 let hunks = diff
1563 .hunks_intersecting_range(hunk_range.clone(), &buffer, &cx)
1564 .collect::<Vec<_>>();
1565 for hunk in &hunks {
1566 assert_eq!(
1567 hunk.secondary_status,
1568 DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
1569 )
1570 }
1571
1572 pretty_assertions::assert_eq!(
1573 new_index_text,
1574 example.final_index_text,
1575 "example: {}",
1576 example.name
1577 );
1578 });
1579 }
1580 }
1581
1582 #[gpui::test]
1583 async fn test_buffer_diff_compare(cx: &mut TestAppContext) {
1584 let base_text = "
1585 zero
1586 one
1587 two
1588 three
1589 four
1590 five
1591 six
1592 seven
1593 eight
1594 nine
1595 "
1596 .unindent();
1597
1598 let buffer_text_1 = "
1599 one
1600 three
1601 four
1602 five
1603 SIX
1604 seven
1605 eight
1606 NINE
1607 "
1608 .unindent();
1609
1610 let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text_1);
1611
1612 let empty_diff = cx.update(|cx| BufferDiff::build_empty(&buffer, cx));
1613 let diff_1 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1614 let range = diff_1.compare(&empty_diff, &buffer).unwrap();
1615 assert_eq!(range.to_point(&buffer), Point::new(0, 0)..Point::new(8, 0));
1616
1617 // Edit does not affect the diff.
1618 buffer.edit_via_marked_text(
1619 &"
1620 one
1621 three
1622 four
1623 five
1624 «SIX.5»
1625 seven
1626 eight
1627 NINE
1628 "
1629 .unindent(),
1630 );
1631 let diff_2 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1632 assert_eq!(None, diff_2.compare(&diff_1, &buffer));
1633
1634 // Edit turns a deletion hunk into a modification.
1635 buffer.edit_via_marked_text(
1636 &"
1637 one
1638 «THREE»
1639 four
1640 five
1641 SIX.5
1642 seven
1643 eight
1644 NINE
1645 "
1646 .unindent(),
1647 );
1648 let diff_3 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1649 let range = diff_3.compare(&diff_2, &buffer).unwrap();
1650 assert_eq!(range.to_point(&buffer), Point::new(1, 0)..Point::new(2, 0));
1651
1652 // Edit turns a modification hunk into a deletion.
1653 buffer.edit_via_marked_text(
1654 &"
1655 one
1656 THREE
1657 four
1658 five«»
1659 seven
1660 eight
1661 NINE
1662 "
1663 .unindent(),
1664 );
1665 let diff_4 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1666 let range = diff_4.compare(&diff_3, &buffer).unwrap();
1667 assert_eq!(range.to_point(&buffer), Point::new(3, 4)..Point::new(4, 0));
1668
1669 // Edit introduces a new insertion hunk.
1670 buffer.edit_via_marked_text(
1671 &"
1672 one
1673 THREE
1674 four«
1675 FOUR.5
1676 »five
1677 seven
1678 eight
1679 NINE
1680 "
1681 .unindent(),
1682 );
1683 let diff_5 = BufferDiff::build_sync(buffer.snapshot(), base_text.clone(), cx);
1684 let range = diff_5.compare(&diff_4, &buffer).unwrap();
1685 assert_eq!(range.to_point(&buffer), Point::new(3, 0)..Point::new(4, 0));
1686
1687 // Edit removes a hunk.
1688 buffer.edit_via_marked_text(
1689 &"
1690 one
1691 THREE
1692 four
1693 FOUR.5
1694 five
1695 seven
1696 eight
1697 «nine»
1698 "
1699 .unindent(),
1700 );
1701 let diff_6 = BufferDiff::build_sync(buffer.snapshot(), base_text, cx);
1702 let range = diff_6.compare(&diff_5, &buffer).unwrap();
1703 assert_eq!(range.to_point(&buffer), Point::new(7, 0)..Point::new(8, 0));
1704 }
1705
1706 #[gpui::test(iterations = 100)]
1707 async fn test_staging_and_unstaging_hunks(cx: &mut TestAppContext, mut rng: StdRng) {
1708 fn gen_line(rng: &mut StdRng) -> String {
1709 if rng.gen_bool(0.2) {
1710 "\n".to_owned()
1711 } else {
1712 let c = rng.gen_range('A'..='Z');
1713 format!("{c}{c}{c}\n")
1714 }
1715 }
1716
1717 fn gen_working_copy(rng: &mut StdRng, head: &str) -> String {
1718 let mut old_lines = {
1719 let mut old_lines = Vec::new();
1720 let mut old_lines_iter = head.lines();
1721 while let Some(line) = old_lines_iter.next() {
1722 assert!(!line.ends_with("\n"));
1723 old_lines.push(line.to_owned());
1724 }
1725 if old_lines.last().is_some_and(|line| line.is_empty()) {
1726 old_lines.pop();
1727 }
1728 old_lines.into_iter()
1729 };
1730 let mut result = String::new();
1731 let unchanged_count = rng.gen_range(0..=old_lines.len());
1732 result +=
1733 &old_lines
1734 .by_ref()
1735 .take(unchanged_count)
1736 .fold(String::new(), |mut s, line| {
1737 writeln!(&mut s, "{line}").unwrap();
1738 s
1739 });
1740 while old_lines.len() > 0 {
1741 let deleted_count = rng.gen_range(0..=old_lines.len());
1742 let _advance = old_lines
1743 .by_ref()
1744 .take(deleted_count)
1745 .map(|line| line.len() + 1)
1746 .sum::<usize>();
1747 let minimum_added = if deleted_count == 0 { 1 } else { 0 };
1748 let added_count = rng.gen_range(minimum_added..=5);
1749 let addition = (0..added_count).map(|_| gen_line(rng)).collect::<String>();
1750 result += &addition;
1751
1752 if old_lines.len() > 0 {
1753 let blank_lines = old_lines.clone().take_while(|line| line.is_empty()).count();
1754 if blank_lines == old_lines.len() {
1755 break;
1756 };
1757 let unchanged_count = rng.gen_range((blank_lines + 1).max(1)..=old_lines.len());
1758 result += &old_lines.by_ref().take(unchanged_count).fold(
1759 String::new(),
1760 |mut s, line| {
1761 writeln!(&mut s, "{line}").unwrap();
1762 s
1763 },
1764 );
1765 }
1766 }
1767 result
1768 }
1769
1770 fn uncommitted_diff(
1771 working_copy: &language::BufferSnapshot,
1772 index_text: &Rope,
1773 head_text: String,
1774 cx: &mut TestAppContext,
1775 ) -> Entity<BufferDiff> {
1776 let inner = BufferDiff::build_sync(working_copy.text.clone(), head_text, cx);
1777 let secondary = BufferDiff {
1778 buffer_id: working_copy.remote_id(),
1779 inner: BufferDiff::build_sync(
1780 working_copy.text.clone(),
1781 index_text.to_string(),
1782 cx,
1783 ),
1784 secondary_diff: None,
1785 };
1786 let secondary = cx.new(|_| secondary);
1787 cx.new(|_| BufferDiff {
1788 buffer_id: working_copy.remote_id(),
1789 inner,
1790 secondary_diff: Some(secondary),
1791 })
1792 }
1793
1794 let operations = std::env::var("OPERATIONS")
1795 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1796 .unwrap_or(10);
1797
1798 let rng = &mut rng;
1799 let head_text = ('a'..='z').fold(String::new(), |mut s, c| {
1800 writeln!(&mut s, "{c}{c}{c}").unwrap();
1801 s
1802 });
1803 let working_copy = gen_working_copy(rng, &head_text);
1804 let working_copy = cx.new(|cx| {
1805 language::Buffer::local_normalized(
1806 Rope::from(working_copy.as_str()),
1807 text::LineEnding::default(),
1808 cx,
1809 )
1810 });
1811 let working_copy = working_copy.read_with(cx, |working_copy, _| working_copy.snapshot());
1812 let mut index_text = if rng.gen() {
1813 Rope::from(head_text.as_str())
1814 } else {
1815 working_copy.as_rope().clone()
1816 };
1817
1818 let mut diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
1819 let mut hunks = diff.update(cx, |diff, cx| {
1820 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
1821 .collect::<Vec<_>>()
1822 });
1823 if hunks.len() == 0 {
1824 return;
1825 }
1826
1827 for _ in 0..operations {
1828 let i = rng.gen_range(0..hunks.len());
1829 let hunk = &mut hunks[i];
1830 let hunk_to_change = hunk.clone();
1831 let stage = match hunk.secondary_status {
1832 DiffHunkSecondaryStatus::HasSecondaryHunk => {
1833 hunk.secondary_status = DiffHunkSecondaryStatus::None;
1834 true
1835 }
1836 DiffHunkSecondaryStatus::None => {
1837 hunk.secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
1838 false
1839 }
1840 _ => unreachable!(),
1841 };
1842
1843 index_text = diff.update(cx, |diff, cx| {
1844 diff.stage_or_unstage_hunks(stage, &[hunk_to_change], &working_copy, true, cx)
1845 .unwrap()
1846 });
1847
1848 diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
1849 let found_hunks = diff.update(cx, |diff, cx| {
1850 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
1851 .collect::<Vec<_>>()
1852 });
1853 assert_eq!(hunks.len(), found_hunks.len());
1854
1855 for (expected_hunk, found_hunk) in hunks.iter().zip(&found_hunks) {
1856 assert_eq!(
1857 expected_hunk.buffer_range.to_point(&working_copy),
1858 found_hunk.buffer_range.to_point(&working_copy)
1859 );
1860 assert_eq!(
1861 expected_hunk.diff_base_byte_range,
1862 found_hunk.diff_base_byte_range
1863 );
1864 assert_eq!(expected_hunk.secondary_status, found_hunk.secondary_status);
1865 }
1866 hunks = found_hunks;
1867 }
1868 }
1869}