buffer_diff.rs

   1use futures::{channel::oneshot, future::OptionFuture};
   2use git2::{DiffLineType as GitDiffLineType, DiffOptions as GitOptions, Patch as GitPatch};
   3use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter};
   4use language::{Language, LanguageRegistry};
   5use rope::Rope;
   6use std::{cmp, future::Future, iter, ops::Range, sync::Arc};
   7use sum_tree::SumTree;
   8use text::ToOffset as _;
   9use text::{Anchor, Bias, BufferId, OffsetRangeExt, Point};
  10use util::ResultExt;
  11
  12pub struct BufferDiff {
  13    pub buffer_id: BufferId,
  14    inner: BufferDiffInner,
  15    secondary_diff: Option<Entity<BufferDiff>>,
  16}
  17
  18#[derive(Clone, Debug)]
  19pub struct BufferDiffSnapshot {
  20    inner: BufferDiffInner,
  21    secondary_diff: Option<Box<BufferDiffSnapshot>>,
  22    pub is_single_insertion: bool,
  23}
  24
  25#[derive(Clone)]
  26struct BufferDiffInner {
  27    hunks: SumTree<InternalDiffHunk>,
  28    base_text: Option<language::BufferSnapshot>,
  29}
  30
  31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  32pub enum DiffHunkStatus {
  33    Added(DiffHunkSecondaryStatus),
  34    Modified(DiffHunkSecondaryStatus),
  35    Removed(DiffHunkSecondaryStatus),
  36}
  37
  38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  39pub enum DiffHunkSecondaryStatus {
  40    HasSecondaryHunk,
  41    OverlapsWithSecondaryHunk,
  42    None,
  43}
  44
  45/// A diff hunk resolved to rows in the buffer.
  46#[derive(Debug, Clone, PartialEq, Eq)]
  47pub struct DiffHunk {
  48    /// The buffer range, expressed in terms of rows.
  49    pub row_range: Range<u32>,
  50    /// The range in the buffer to which this hunk corresponds.
  51    pub buffer_range: Range<Anchor>,
  52    /// The range in the buffer's diff base text to which this hunk corresponds.
  53    pub diff_base_byte_range: Range<usize>,
  54    pub secondary_status: DiffHunkSecondaryStatus,
  55    pub secondary_diff_base_byte_range: Option<Range<usize>>,
  56}
  57
  58/// We store [`InternalDiffHunk`]s internally so we don't need to store the additional row range.
  59#[derive(Debug, Clone, PartialEq, Eq)]
  60struct InternalDiffHunk {
  61    buffer_range: Range<Anchor>,
  62    diff_base_byte_range: Range<usize>,
  63}
  64
  65impl sum_tree::Item for InternalDiffHunk {
  66    type Summary = DiffHunkSummary;
  67
  68    fn summary(&self, _cx: &text::BufferSnapshot) -> Self::Summary {
  69        DiffHunkSummary {
  70            buffer_range: self.buffer_range.clone(),
  71        }
  72    }
  73}
  74
  75#[derive(Debug, Default, Clone)]
  76pub struct DiffHunkSummary {
  77    buffer_range: Range<Anchor>,
  78}
  79
  80impl sum_tree::Summary for DiffHunkSummary {
  81    type Context = text::BufferSnapshot;
  82
  83    fn zero(_cx: &Self::Context) -> Self {
  84        Default::default()
  85    }
  86
  87    fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
  88        self.buffer_range.start = self
  89            .buffer_range
  90            .start
  91            .min(&other.buffer_range.start, buffer);
  92        self.buffer_range.end = self.buffer_range.end.max(&other.buffer_range.end, buffer);
  93    }
  94}
  95
  96impl<'a> sum_tree::SeekTarget<'a, DiffHunkSummary, DiffHunkSummary> for Anchor {
  97    fn cmp(
  98        &self,
  99        cursor_location: &DiffHunkSummary,
 100        buffer: &text::BufferSnapshot,
 101    ) -> cmp::Ordering {
 102        self.cmp(&cursor_location.buffer_range.end, buffer)
 103    }
 104}
 105
 106impl std::fmt::Debug for BufferDiffInner {
 107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 108        f.debug_struct("BufferDiffSnapshot")
 109            .field("hunks", &self.hunks)
 110            .finish()
 111    }
 112}
 113
 114impl BufferDiffSnapshot {
 115    pub fn is_empty(&self) -> bool {
 116        self.inner.hunks.is_empty()
 117    }
 118
 119    pub fn secondary_diff(&self) -> Option<&BufferDiffSnapshot> {
 120        self.secondary_diff.as_deref()
 121    }
 122
 123    pub fn hunks_intersecting_range<'a>(
 124        &'a self,
 125        range: Range<Anchor>,
 126        buffer: &'a text::BufferSnapshot,
 127    ) -> impl 'a + Iterator<Item = DiffHunk> {
 128        let unstaged_counterpart = self.secondary_diff.as_ref().map(|diff| &diff.inner);
 129        self.inner
 130            .hunks_intersecting_range(range, buffer, unstaged_counterpart)
 131    }
 132
 133    pub fn hunks_intersecting_range_rev<'a>(
 134        &'a self,
 135        range: Range<Anchor>,
 136        buffer: &'a text::BufferSnapshot,
 137    ) -> impl 'a + Iterator<Item = DiffHunk> {
 138        self.inner.hunks_intersecting_range_rev(range, buffer)
 139    }
 140
 141    pub fn base_text(&self) -> Option<&language::BufferSnapshot> {
 142        self.inner.base_text.as_ref()
 143    }
 144
 145    pub fn base_texts_eq(&self, other: &Self) -> bool {
 146        match (other.base_text(), self.base_text()) {
 147            (None, None) => true,
 148            (None, Some(_)) => false,
 149            (Some(_), None) => false,
 150            (Some(old), Some(new)) => {
 151                let (old_id, old_empty) = (old.remote_id(), old.is_empty());
 152                let (new_id, new_empty) = (new.remote_id(), new.is_empty());
 153                new_id == old_id || (new_empty && old_empty)
 154            }
 155        }
 156    }
 157
 158    fn buffer_range_to_unchanged_diff_base_range(
 159        &self,
 160        buffer_range: Range<Anchor>,
 161        buffer: &text::BufferSnapshot,
 162    ) -> Option<Range<usize>> {
 163        let mut hunks = self.inner.hunks.iter();
 164        let mut start = 0;
 165        let mut pos = buffer.anchor_before(0);
 166        while let Some(hunk) = hunks.next() {
 167            assert!(buffer_range.start.cmp(&pos, buffer).is_ge());
 168            assert!(hunk.buffer_range.start.cmp(&pos, buffer).is_ge());
 169            if hunk
 170                .buffer_range
 171                .start
 172                .cmp(&buffer_range.end, buffer)
 173                .is_ge()
 174            {
 175                // target buffer range is contained in the unchanged stretch leading up to this next hunk,
 176                // so do a final adjustment based on that
 177                break;
 178            }
 179
 180            // if the target buffer range intersects this hunk at all, no dice
 181            if buffer_range
 182                .start
 183                .cmp(&hunk.buffer_range.end, buffer)
 184                .is_lt()
 185            {
 186                return None;
 187            }
 188
 189            start += hunk.buffer_range.start.to_offset(buffer) - pos.to_offset(buffer);
 190            start += hunk.diff_base_byte_range.end - hunk.diff_base_byte_range.start;
 191            pos = hunk.buffer_range.end;
 192        }
 193        start += buffer_range.start.to_offset(buffer) - pos.to_offset(buffer);
 194        let end = start + buffer_range.end.to_offset(buffer) - buffer_range.start.to_offset(buffer);
 195        Some(start..end)
 196    }
 197
 198    pub fn secondary_edits_for_stage_or_unstage(
 199        &self,
 200        stage: bool,
 201        hunks: impl Iterator<Item = (Range<usize>, Option<Range<usize>>, Range<Anchor>)>,
 202        buffer: &text::BufferSnapshot,
 203    ) -> Vec<(Range<usize>, String)> {
 204        let Some(secondary_diff) = self.secondary_diff() else {
 205            log::debug!("no secondary diff");
 206            return Vec::new();
 207        };
 208        let index_base = secondary_diff.base_text().map_or_else(
 209            || Rope::from(""),
 210            |snapshot| snapshot.text.as_rope().clone(),
 211        );
 212        let head_base = self.base_text().map_or_else(
 213            || Rope::from(""),
 214            |snapshot| snapshot.text.as_rope().clone(),
 215        );
 216        log::debug!("original: {:?}", index_base.to_string());
 217        let mut edits = Vec::new();
 218        for (diff_base_byte_range, secondary_diff_base_byte_range, buffer_range) in hunks {
 219            let (index_byte_range, replacement_text) = if stage {
 220                log::debug!("staging");
 221                let mut replacement_text = String::new();
 222                let Some(index_byte_range) = secondary_diff_base_byte_range.clone() else {
 223                    log::debug!("not a stageable hunk");
 224                    continue;
 225                };
 226                log::debug!("using {:?}", index_byte_range);
 227                for chunk in buffer.text_for_range(buffer_range.clone()) {
 228                    replacement_text.push_str(chunk);
 229                }
 230                (index_byte_range, replacement_text)
 231            } else {
 232                log::debug!("unstaging");
 233                let mut replacement_text = String::new();
 234                let Some(index_byte_range) = secondary_diff
 235                    .buffer_range_to_unchanged_diff_base_range(buffer_range.clone(), &buffer)
 236                else {
 237                    log::debug!("not an unstageable hunk");
 238                    continue;
 239                };
 240                for chunk in head_base.chunks_in_range(diff_base_byte_range.clone()) {
 241                    replacement_text.push_str(chunk);
 242                }
 243                (index_byte_range, replacement_text)
 244            };
 245            edits.push((index_byte_range, replacement_text));
 246        }
 247        log::debug!("edits: {edits:?}");
 248        edits
 249    }
 250}
 251
 252impl BufferDiffInner {
 253    fn hunks_intersecting_range<'a>(
 254        &'a self,
 255        range: Range<Anchor>,
 256        buffer: &'a text::BufferSnapshot,
 257        secondary: Option<&'a Self>,
 258    ) -> impl 'a + Iterator<Item = DiffHunk> {
 259        let range = range.to_offset(buffer);
 260
 261        let mut cursor = self
 262            .hunks
 263            .filter::<_, DiffHunkSummary>(buffer, move |summary| {
 264                let summary_range = summary.buffer_range.to_offset(buffer);
 265                let before_start = summary_range.end < range.start;
 266                let after_end = summary_range.start > range.end;
 267                !before_start && !after_end
 268            });
 269
 270        let anchor_iter = iter::from_fn(move || {
 271            cursor.next(buffer);
 272            cursor.item()
 273        })
 274        .flat_map(move |hunk| {
 275            [
 276                (
 277                    &hunk.buffer_range.start,
 278                    (hunk.buffer_range.start, hunk.diff_base_byte_range.start),
 279                ),
 280                (
 281                    &hunk.buffer_range.end,
 282                    (hunk.buffer_range.end, hunk.diff_base_byte_range.end),
 283                ),
 284            ]
 285        });
 286
 287        let mut secondary_cursor = secondary.as_ref().map(|diff| {
 288            let mut cursor = diff.hunks.cursor::<DiffHunkSummary>(buffer);
 289            cursor.next(buffer);
 290            cursor
 291        });
 292
 293        let mut summaries = buffer.summaries_for_anchors_with_payload::<Point, _, _>(anchor_iter);
 294        iter::from_fn(move || loop {
 295            let (start_point, (start_anchor, start_base)) = summaries.next()?;
 296            let (mut end_point, (mut end_anchor, end_base)) = summaries.next()?;
 297
 298            if !start_anchor.is_valid(buffer) {
 299                continue;
 300            }
 301
 302            if end_point.column > 0 {
 303                end_point.row += 1;
 304                end_point.column = 0;
 305                end_anchor = buffer.anchor_before(end_point);
 306            }
 307
 308            let mut secondary_status = DiffHunkSecondaryStatus::None;
 309            let mut secondary_diff_base_byte_range = None;
 310            if let Some(secondary_cursor) = secondary_cursor.as_mut() {
 311                if start_anchor
 312                    .cmp(&secondary_cursor.start().buffer_range.start, buffer)
 313                    .is_gt()
 314                {
 315                    secondary_cursor.seek_forward(&end_anchor, Bias::Left, buffer);
 316                }
 317
 318                if let Some(secondary_hunk) = secondary_cursor.item() {
 319                    let mut secondary_range = secondary_hunk.buffer_range.to_point(buffer);
 320                    if secondary_range.end.column > 0 {
 321                        secondary_range.end.row += 1;
 322                        secondary_range.end.column = 0;
 323                    }
 324                    if secondary_range == (start_point..end_point) {
 325                        secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
 326                        secondary_diff_base_byte_range =
 327                            Some(secondary_hunk.diff_base_byte_range.clone());
 328                    } else if secondary_range.start <= end_point {
 329                        secondary_status = DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk;
 330                    }
 331                }
 332            }
 333
 334            return Some(DiffHunk {
 335                row_range: start_point.row..end_point.row,
 336                diff_base_byte_range: start_base..end_base,
 337                buffer_range: start_anchor..end_anchor,
 338                secondary_status,
 339                secondary_diff_base_byte_range,
 340            });
 341        })
 342    }
 343
 344    fn hunks_intersecting_range_rev<'a>(
 345        &'a self,
 346        range: Range<Anchor>,
 347        buffer: &'a text::BufferSnapshot,
 348    ) -> impl 'a + Iterator<Item = DiffHunk> {
 349        let mut cursor = self
 350            .hunks
 351            .filter::<_, DiffHunkSummary>(buffer, move |summary| {
 352                let before_start = summary.buffer_range.end.cmp(&range.start, buffer).is_lt();
 353                let after_end = summary.buffer_range.start.cmp(&range.end, buffer).is_gt();
 354                !before_start && !after_end
 355            });
 356
 357        iter::from_fn(move || {
 358            cursor.prev(buffer);
 359
 360            let hunk = cursor.item()?;
 361            let range = hunk.buffer_range.to_point(buffer);
 362            let end_row = if range.end.column > 0 {
 363                range.end.row + 1
 364            } else {
 365                range.end.row
 366            };
 367
 368            Some(DiffHunk {
 369                row_range: range.start.row..end_row,
 370                diff_base_byte_range: hunk.diff_base_byte_range.clone(),
 371                buffer_range: hunk.buffer_range.clone(),
 372                // The secondary status is not used by callers of this method.
 373                secondary_status: DiffHunkSecondaryStatus::None,
 374                secondary_diff_base_byte_range: None,
 375            })
 376        })
 377    }
 378
 379    fn compare(&self, old: &Self, new_snapshot: &text::BufferSnapshot) -> Option<Range<Anchor>> {
 380        let mut new_cursor = self.hunks.cursor::<()>(new_snapshot);
 381        let mut old_cursor = old.hunks.cursor::<()>(new_snapshot);
 382        old_cursor.next(new_snapshot);
 383        new_cursor.next(new_snapshot);
 384        let mut start = None;
 385        let mut end = None;
 386
 387        loop {
 388            match (new_cursor.item(), old_cursor.item()) {
 389                (Some(new_hunk), Some(old_hunk)) => {
 390                    match new_hunk
 391                        .buffer_range
 392                        .start
 393                        .cmp(&old_hunk.buffer_range.start, new_snapshot)
 394                    {
 395                        cmp::Ordering::Less => {
 396                            start.get_or_insert(new_hunk.buffer_range.start);
 397                            end.replace(new_hunk.buffer_range.end);
 398                            new_cursor.next(new_snapshot);
 399                        }
 400                        cmp::Ordering::Equal => {
 401                            if new_hunk != old_hunk {
 402                                start.get_or_insert(new_hunk.buffer_range.start);
 403                                if old_hunk
 404                                    .buffer_range
 405                                    .end
 406                                    .cmp(&new_hunk.buffer_range.end, new_snapshot)
 407                                    .is_ge()
 408                                {
 409                                    end.replace(old_hunk.buffer_range.end);
 410                                } else {
 411                                    end.replace(new_hunk.buffer_range.end);
 412                                }
 413                            }
 414
 415                            new_cursor.next(new_snapshot);
 416                            old_cursor.next(new_snapshot);
 417                        }
 418                        cmp::Ordering::Greater => {
 419                            start.get_or_insert(old_hunk.buffer_range.start);
 420                            end.replace(old_hunk.buffer_range.end);
 421                            old_cursor.next(new_snapshot);
 422                        }
 423                    }
 424                }
 425                (Some(new_hunk), None) => {
 426                    start.get_or_insert(new_hunk.buffer_range.start);
 427                    end.replace(new_hunk.buffer_range.end);
 428                    new_cursor.next(new_snapshot);
 429                }
 430                (None, Some(old_hunk)) => {
 431                    start.get_or_insert(old_hunk.buffer_range.start);
 432                    end.replace(old_hunk.buffer_range.end);
 433                    old_cursor.next(new_snapshot);
 434                }
 435                (None, None) => break,
 436            }
 437        }
 438
 439        start.zip(end).map(|(start, end)| start..end)
 440    }
 441}
 442
 443fn compute_hunks(
 444    diff_base: Option<(Arc<String>, Rope)>,
 445    buffer: text::BufferSnapshot,
 446) -> SumTree<InternalDiffHunk> {
 447    let mut tree = SumTree::new(&buffer);
 448
 449    if let Some((diff_base, diff_base_rope)) = diff_base {
 450        let buffer_text = buffer.as_rope().to_string();
 451
 452        let mut options = GitOptions::default();
 453        options.context_lines(0);
 454        let patch = GitPatch::from_buffers(
 455            diff_base.as_bytes(),
 456            None,
 457            buffer_text.as_bytes(),
 458            None,
 459            Some(&mut options),
 460        )
 461        .log_err();
 462
 463        // A common case in Zed is that the empty buffer is represented as just a newline,
 464        // but if we just compute a naive diff you get a "preserved" line in the middle,
 465        // which is a bit odd.
 466        if buffer_text == "\n" && diff_base.ends_with("\n") && diff_base.len() > 1 {
 467            tree.push(
 468                InternalDiffHunk {
 469                    buffer_range: buffer.anchor_before(0)..buffer.anchor_before(0),
 470                    diff_base_byte_range: 0..diff_base.len() - 1,
 471                },
 472                &buffer,
 473            );
 474            return tree;
 475        }
 476
 477        if let Some(patch) = patch {
 478            let mut divergence = 0;
 479            for hunk_index in 0..patch.num_hunks() {
 480                let hunk = process_patch_hunk(
 481                    &patch,
 482                    hunk_index,
 483                    &diff_base_rope,
 484                    &buffer,
 485                    &mut divergence,
 486                );
 487                tree.push(hunk, &buffer);
 488            }
 489        }
 490    }
 491
 492    tree
 493}
 494
 495fn process_patch_hunk(
 496    patch: &GitPatch<'_>,
 497    hunk_index: usize,
 498    diff_base: &Rope,
 499    buffer: &text::BufferSnapshot,
 500    buffer_row_divergence: &mut i64,
 501) -> InternalDiffHunk {
 502    let line_item_count = patch.num_lines_in_hunk(hunk_index).unwrap();
 503    assert!(line_item_count > 0);
 504
 505    let mut first_deletion_buffer_row: Option<u32> = None;
 506    let mut buffer_row_range: Option<Range<u32>> = None;
 507    let mut diff_base_byte_range: Option<Range<usize>> = None;
 508    let mut first_addition_old_row: Option<u32> = None;
 509
 510    for line_index in 0..line_item_count {
 511        let line = patch.line_in_hunk(hunk_index, line_index).unwrap();
 512        let kind = line.origin_value();
 513        let content_offset = line.content_offset() as isize;
 514        let content_len = line.content().len() as isize;
 515        match kind {
 516            GitDiffLineType::Addition => {
 517                if first_addition_old_row.is_none() {
 518                    first_addition_old_row = Some(
 519                        (line.new_lineno().unwrap() as i64 - *buffer_row_divergence - 1) as u32,
 520                    );
 521                }
 522                *buffer_row_divergence += 1;
 523                let row = line.new_lineno().unwrap().saturating_sub(1);
 524
 525                match &mut buffer_row_range {
 526                    Some(Range { end, .. }) => *end = row + 1,
 527                    None => buffer_row_range = Some(row..row + 1),
 528                }
 529            }
 530            GitDiffLineType::Deletion => {
 531                let end = content_offset + content_len;
 532
 533                match &mut diff_base_byte_range {
 534                    Some(head_byte_range) => head_byte_range.end = end as usize,
 535                    None => diff_base_byte_range = Some(content_offset as usize..end as usize),
 536                }
 537
 538                if first_deletion_buffer_row.is_none() {
 539                    let old_row = line.old_lineno().unwrap().saturating_sub(1);
 540                    let row = old_row as i64 + *buffer_row_divergence;
 541                    first_deletion_buffer_row = Some(row as u32);
 542                }
 543
 544                *buffer_row_divergence -= 1;
 545            }
 546            _ => {}
 547        }
 548    }
 549
 550    let buffer_row_range = buffer_row_range.unwrap_or_else(|| {
 551        // Pure deletion hunk without addition.
 552        let row = first_deletion_buffer_row.unwrap();
 553        row..row
 554    });
 555    let diff_base_byte_range = diff_base_byte_range.unwrap_or_else(|| {
 556        // Pure addition hunk without deletion.
 557        let row = first_addition_old_row.unwrap();
 558        let offset = diff_base.point_to_offset(Point::new(row, 0));
 559        offset..offset
 560    });
 561
 562    let start = Point::new(buffer_row_range.start, 0);
 563    let end = Point::new(buffer_row_range.end, 0);
 564    let buffer_range = buffer.anchor_before(start)..buffer.anchor_before(end);
 565    InternalDiffHunk {
 566        buffer_range,
 567        diff_base_byte_range,
 568    }
 569}
 570
 571impl std::fmt::Debug for BufferDiff {
 572    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 573        f.debug_struct("BufferChangeSet")
 574            .field("buffer_id", &self.buffer_id)
 575            .field("snapshot", &self.inner)
 576            .finish()
 577    }
 578}
 579
 580pub enum BufferDiffEvent {
 581    DiffChanged {
 582        changed_range: Option<Range<text::Anchor>>,
 583    },
 584    LanguageChanged,
 585}
 586
 587impl EventEmitter<BufferDiffEvent> for BufferDiff {}
 588
 589impl BufferDiff {
 590    #[cfg(test)]
 591    fn build_sync(
 592        buffer: text::BufferSnapshot,
 593        diff_base: String,
 594        cx: &mut gpui::TestAppContext,
 595    ) -> BufferDiffInner {
 596        let snapshot =
 597            cx.update(|cx| Self::build(buffer, Some(Arc::new(diff_base)), None, None, cx));
 598        cx.executor().block(snapshot)
 599    }
 600
 601    fn build(
 602        buffer: text::BufferSnapshot,
 603        diff_base: Option<Arc<String>>,
 604        language: Option<Arc<Language>>,
 605        language_registry: Option<Arc<LanguageRegistry>>,
 606        cx: &mut App,
 607    ) -> impl Future<Output = BufferDiffInner> {
 608        let diff_base =
 609            diff_base.map(|diff_base| (diff_base.clone(), Rope::from(diff_base.as_str())));
 610        let base_text_snapshot = diff_base.as_ref().map(|(_, diff_base)| {
 611            language::Buffer::build_snapshot(
 612                diff_base.clone(),
 613                language.clone(),
 614                language_registry.clone(),
 615                cx,
 616            )
 617        });
 618        let base_text_snapshot = cx.background_spawn(OptionFuture::from(base_text_snapshot));
 619
 620        let hunks = cx.background_spawn({
 621            let buffer = buffer.clone();
 622            async move { compute_hunks(diff_base, buffer) }
 623        });
 624
 625        async move {
 626            let (base_text, hunks) = futures::join!(base_text_snapshot, hunks);
 627            BufferDiffInner { base_text, hunks }
 628        }
 629    }
 630
 631    fn build_with_base_buffer(
 632        buffer: text::BufferSnapshot,
 633        diff_base: Option<Arc<String>>,
 634        diff_base_buffer: Option<language::BufferSnapshot>,
 635        cx: &App,
 636    ) -> impl Future<Output = BufferDiffInner> {
 637        let diff_base = diff_base.clone().zip(
 638            diff_base_buffer
 639                .clone()
 640                .map(|buffer| buffer.as_rope().clone()),
 641        );
 642        cx.background_spawn(async move {
 643            BufferDiffInner {
 644                hunks: compute_hunks(diff_base, buffer),
 645                base_text: diff_base_buffer,
 646            }
 647        })
 648    }
 649
 650    fn build_empty(buffer: &text::BufferSnapshot) -> BufferDiffInner {
 651        BufferDiffInner {
 652            hunks: SumTree::new(buffer),
 653            base_text: None,
 654        }
 655    }
 656
 657    pub fn build_with_single_insertion(
 658        insertion_present_in_secondary_diff: bool,
 659        buffer: language::BufferSnapshot,
 660        cx: &mut App,
 661    ) -> BufferDiffSnapshot {
 662        let base_text = language::Buffer::build_empty_snapshot(cx);
 663        let hunks = SumTree::from_item(
 664            InternalDiffHunk {
 665                buffer_range: Anchor::MIN..Anchor::MAX,
 666                diff_base_byte_range: 0..0,
 667            },
 668            &base_text,
 669        );
 670        BufferDiffSnapshot {
 671            inner: BufferDiffInner {
 672                hunks: hunks.clone(),
 673                base_text: Some(base_text.clone()),
 674            },
 675            secondary_diff: Some(Box::new(BufferDiffSnapshot {
 676                inner: BufferDiffInner {
 677                    hunks: if insertion_present_in_secondary_diff {
 678                        hunks
 679                    } else {
 680                        SumTree::new(&buffer.text)
 681                    },
 682                    base_text: Some(if insertion_present_in_secondary_diff {
 683                        base_text
 684                    } else {
 685                        buffer
 686                    }),
 687                },
 688                secondary_diff: None,
 689                is_single_insertion: true,
 690            })),
 691            is_single_insertion: true,
 692        }
 693    }
 694
 695    pub fn set_secondary_diff(&mut self, diff: Entity<BufferDiff>) {
 696        self.secondary_diff = Some(diff);
 697    }
 698
 699    pub fn secondary_diff(&self) -> Option<Entity<BufferDiff>> {
 700        Some(self.secondary_diff.as_ref()?.clone())
 701    }
 702
 703    pub fn range_to_hunk_range(
 704        &self,
 705        range: Range<Anchor>,
 706        buffer: &text::BufferSnapshot,
 707        cx: &App,
 708    ) -> Option<Range<Anchor>> {
 709        let start = self
 710            .hunks_intersecting_range(range.clone(), &buffer, cx)
 711            .next()?
 712            .buffer_range
 713            .start;
 714        let end = self
 715            .hunks_intersecting_range_rev(range.clone(), &buffer)
 716            .next()?
 717            .buffer_range
 718            .end;
 719        Some(start..end)
 720    }
 721
 722    #[allow(clippy::too_many_arguments)]
 723    pub async fn update_diff(
 724        this: Entity<BufferDiff>,
 725        buffer: text::BufferSnapshot,
 726        base_text: Option<Arc<String>>,
 727        base_text_changed: bool,
 728        language_changed: bool,
 729        language: Option<Arc<Language>>,
 730        language_registry: Option<Arc<LanguageRegistry>>,
 731        cx: &mut AsyncApp,
 732    ) -> anyhow::Result<Option<Range<Anchor>>> {
 733        let snapshot = if base_text_changed || language_changed {
 734            cx.update(|cx| {
 735                Self::build(
 736                    buffer.clone(),
 737                    base_text,
 738                    language.clone(),
 739                    language_registry.clone(),
 740                    cx,
 741                )
 742            })?
 743            .await
 744        } else {
 745            this.read_with(cx, |this, cx| {
 746                Self::build_with_base_buffer(
 747                    buffer.clone(),
 748                    base_text,
 749                    this.base_text().cloned(),
 750                    cx,
 751                )
 752            })?
 753            .await
 754        };
 755
 756        this.update(cx, |this, _| this.set_state(snapshot, &buffer))
 757    }
 758
 759    pub fn update_diff_from(
 760        &mut self,
 761        buffer: &text::BufferSnapshot,
 762        other: &Entity<Self>,
 763        cx: &mut Context<Self>,
 764    ) -> Option<Range<Anchor>> {
 765        let other = other.read(cx).inner.clone();
 766        self.set_state(other, buffer)
 767    }
 768
 769    fn set_state(
 770        &mut self,
 771        inner: BufferDiffInner,
 772        buffer: &text::BufferSnapshot,
 773    ) -> Option<Range<Anchor>> {
 774        let changed_range = match (self.inner.base_text.as_ref(), inner.base_text.as_ref()) {
 775            (None, None) => None,
 776            (Some(old), Some(new)) if old.remote_id() == new.remote_id() => {
 777                inner.compare(&self.inner, buffer)
 778            }
 779            _ => Some(text::Anchor::MIN..text::Anchor::MAX),
 780        };
 781        self.inner = inner;
 782        changed_range
 783    }
 784
 785    pub fn base_text(&self) -> Option<&language::BufferSnapshot> {
 786        self.inner.base_text.as_ref()
 787    }
 788
 789    pub fn snapshot(&self, cx: &App) -> BufferDiffSnapshot {
 790        BufferDiffSnapshot {
 791            inner: self.inner.clone(),
 792            secondary_diff: self
 793                .secondary_diff
 794                .as_ref()
 795                .map(|diff| Box::new(diff.read(cx).snapshot(cx))),
 796            is_single_insertion: false,
 797        }
 798    }
 799
 800    pub fn hunks_intersecting_range<'a>(
 801        &'a self,
 802        range: Range<text::Anchor>,
 803        buffer_snapshot: &'a text::BufferSnapshot,
 804        cx: &'a App,
 805    ) -> impl 'a + Iterator<Item = DiffHunk> {
 806        let unstaged_counterpart = self
 807            .secondary_diff
 808            .as_ref()
 809            .map(|diff| &diff.read(cx).inner);
 810        self.inner
 811            .hunks_intersecting_range(range, buffer_snapshot, unstaged_counterpart)
 812    }
 813
 814    pub fn hunks_intersecting_range_rev<'a>(
 815        &'a self,
 816        range: Range<text::Anchor>,
 817        buffer_snapshot: &'a text::BufferSnapshot,
 818    ) -> impl 'a + Iterator<Item = DiffHunk> {
 819        self.inner
 820            .hunks_intersecting_range_rev(range, buffer_snapshot)
 821    }
 822
 823    pub fn hunks_in_row_range<'a>(
 824        &'a self,
 825        range: Range<u32>,
 826        buffer: &'a text::BufferSnapshot,
 827        cx: &'a App,
 828    ) -> impl 'a + Iterator<Item = DiffHunk> {
 829        let start = buffer.anchor_before(Point::new(range.start, 0));
 830        let end = buffer.anchor_after(Point::new(range.end, 0));
 831        self.hunks_intersecting_range(start..end, buffer, cx)
 832    }
 833
 834    /// Used in cases where the change set isn't derived from git.
 835    pub fn set_base_text(
 836        &mut self,
 837        base_buffer: Entity<language::Buffer>,
 838        buffer: text::BufferSnapshot,
 839        cx: &mut Context<Self>,
 840    ) -> oneshot::Receiver<()> {
 841        let (tx, rx) = oneshot::channel();
 842        let this = cx.weak_entity();
 843        let base_buffer = base_buffer.read(cx);
 844        let language_registry = base_buffer.language_registry();
 845        let base_buffer = base_buffer.snapshot();
 846        let base_text = Arc::new(base_buffer.text());
 847
 848        let snapshot = BufferDiff::build(
 849            buffer.clone(),
 850            Some(base_text),
 851            base_buffer.language().cloned(),
 852            language_registry,
 853            cx,
 854        );
 855        let complete_on_drop = util::defer(|| {
 856            tx.send(()).ok();
 857        });
 858        cx.spawn(|_, mut cx| async move {
 859            let snapshot = snapshot.await;
 860            let Some(this) = this.upgrade() else {
 861                return;
 862            };
 863            this.update(&mut cx, |this, _| {
 864                this.set_state(snapshot, &buffer);
 865            })
 866            .log_err();
 867            drop(complete_on_drop)
 868        })
 869        .detach();
 870        rx
 871    }
 872
 873    #[cfg(any(test, feature = "test-support"))]
 874    pub fn base_text_string(&self) -> Option<String> {
 875        self.inner.base_text.as_ref().map(|buffer| buffer.text())
 876    }
 877
 878    pub fn new(buffer: &text::BufferSnapshot) -> Self {
 879        BufferDiff {
 880            buffer_id: buffer.remote_id(),
 881            inner: BufferDiff::build_empty(buffer),
 882            secondary_diff: None,
 883        }
 884    }
 885
 886    #[cfg(any(test, feature = "test-support"))]
 887    pub fn new_with_base_text(
 888        base_text: &str,
 889        buffer: &Entity<language::Buffer>,
 890        cx: &mut App,
 891    ) -> Self {
 892        let mut base_text = base_text.to_owned();
 893        text::LineEnding::normalize(&mut base_text);
 894        let snapshot = BufferDiff::build(
 895            buffer.read(cx).text_snapshot(),
 896            Some(base_text.into()),
 897            None,
 898            None,
 899            cx,
 900        );
 901        let snapshot = cx.background_executor().block(snapshot);
 902        BufferDiff {
 903            buffer_id: buffer.read(cx).remote_id(),
 904            inner: snapshot,
 905            secondary_diff: None,
 906        }
 907    }
 908
 909    #[cfg(any(test, feature = "test-support"))]
 910    pub fn recalculate_diff_sync(&mut self, buffer: text::BufferSnapshot, cx: &mut Context<Self>) {
 911        let base_text = self
 912            .inner
 913            .base_text
 914            .as_ref()
 915            .map(|base_text| base_text.text());
 916        let snapshot = BufferDiff::build_with_base_buffer(
 917            buffer.clone(),
 918            base_text.clone().map(Arc::new),
 919            self.inner.base_text.clone(),
 920            cx,
 921        );
 922        let snapshot = cx.background_executor().block(snapshot);
 923        let changed_range = self.set_state(snapshot, &buffer);
 924        cx.emit(BufferDiffEvent::DiffChanged { changed_range });
 925    }
 926}
 927
 928impl DiffHunk {
 929    pub fn status(&self) -> DiffHunkStatus {
 930        if self.buffer_range.start == self.buffer_range.end {
 931            DiffHunkStatus::Removed(self.secondary_status)
 932        } else if self.diff_base_byte_range.is_empty() {
 933            DiffHunkStatus::Added(self.secondary_status)
 934        } else {
 935            DiffHunkStatus::Modified(self.secondary_status)
 936        }
 937    }
 938}
 939
 940impl DiffHunkStatus {
 941    pub fn is_removed(&self) -> bool {
 942        matches!(self, DiffHunkStatus::Removed(_))
 943    }
 944
 945    #[cfg(any(test, feature = "test-support"))]
 946    pub fn removed() -> Self {
 947        DiffHunkStatus::Removed(DiffHunkSecondaryStatus::None)
 948    }
 949
 950    #[cfg(any(test, feature = "test-support"))]
 951    pub fn added() -> Self {
 952        DiffHunkStatus::Added(DiffHunkSecondaryStatus::None)
 953    }
 954
 955    #[cfg(any(test, feature = "test-support"))]
 956    pub fn modified() -> Self {
 957        DiffHunkStatus::Modified(DiffHunkSecondaryStatus::None)
 958    }
 959}
 960
 961/// Range (crossing new lines), old, new
 962#[cfg(any(test, feature = "test-support"))]
 963#[track_caller]
 964pub fn assert_hunks<Iter>(
 965    diff_hunks: Iter,
 966    buffer: &text::BufferSnapshot,
 967    diff_base: &str,
 968    expected_hunks: &[(Range<u32>, &str, &str, DiffHunkStatus)],
 969) where
 970    Iter: Iterator<Item = DiffHunk>,
 971{
 972    let actual_hunks = diff_hunks
 973        .map(|hunk| {
 974            (
 975                hunk.row_range.clone(),
 976                &diff_base[hunk.diff_base_byte_range.clone()],
 977                buffer
 978                    .text_for_range(
 979                        Point::new(hunk.row_range.start, 0)..Point::new(hunk.row_range.end, 0),
 980                    )
 981                    .collect::<String>(),
 982                hunk.status(),
 983            )
 984        })
 985        .collect::<Vec<_>>();
 986
 987    let expected_hunks: Vec<_> = expected_hunks
 988        .iter()
 989        .map(|(r, s, h, status)| (r.clone(), *s, h.to_string(), *status))
 990        .collect();
 991
 992    assert_eq!(actual_hunks, expected_hunks);
 993}
 994
 995#[cfg(test)]
 996mod tests {
 997    use std::fmt::Write as _;
 998
 999    use super::*;
1000    use gpui::TestAppContext;
1001    use rand::{rngs::StdRng, Rng as _};
1002    use text::{Buffer, BufferId, Rope};
1003    use unindent::Unindent as _;
1004
1005    #[ctor::ctor]
1006    fn init_logger() {
1007        if std::env::var("RUST_LOG").is_ok() {
1008            env_logger::init();
1009        }
1010    }
1011
1012    #[gpui::test]
1013    async fn test_buffer_diff_simple(cx: &mut gpui::TestAppContext) {
1014        let diff_base = "
1015            one
1016            two
1017            three
1018        "
1019        .unindent();
1020
1021        let buffer_text = "
1022            one
1023            HELLO
1024            three
1025        "
1026        .unindent();
1027
1028        let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1029        let mut diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1030        assert_hunks(
1031            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1032            &buffer,
1033            &diff_base,
1034            &[(1..2, "two\n", "HELLO\n", DiffHunkStatus::modified())],
1035        );
1036
1037        buffer.edit([(0..0, "point five\n")]);
1038        diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1039        assert_hunks(
1040            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1041            &buffer,
1042            &diff_base,
1043            &[
1044                (0..1, "", "point five\n", DiffHunkStatus::added()),
1045                (2..3, "two\n", "HELLO\n", DiffHunkStatus::modified()),
1046            ],
1047        );
1048
1049        diff = BufferDiff::build_empty(&buffer);
1050        assert_hunks(
1051            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1052            &buffer,
1053            &diff_base,
1054            &[],
1055        );
1056    }
1057
1058    #[gpui::test]
1059    async fn test_buffer_diff_with_secondary(cx: &mut gpui::TestAppContext) {
1060        let head_text = "
1061            zero
1062            one
1063            two
1064            three
1065            four
1066            five
1067            six
1068            seven
1069            eight
1070            nine
1071        "
1072        .unindent();
1073
1074        let index_text = "
1075            zero
1076            one
1077            TWO
1078            three
1079            FOUR
1080            five
1081            six
1082            seven
1083            eight
1084            NINE
1085        "
1086        .unindent();
1087
1088        let buffer_text = "
1089            zero
1090            one
1091            TWO
1092            three
1093            FOUR
1094            FIVE
1095            six
1096            SEVEN
1097            eight
1098            nine
1099        "
1100        .unindent();
1101
1102        let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1103        let unstaged_diff = BufferDiff::build_sync(buffer.clone(), index_text.clone(), cx);
1104
1105        let uncommitted_diff = BufferDiff::build_sync(buffer.clone(), head_text.clone(), cx);
1106
1107        let expected_hunks = vec![
1108            (
1109                2..3,
1110                "two\n",
1111                "TWO\n",
1112                DiffHunkStatus::Modified(DiffHunkSecondaryStatus::None),
1113            ),
1114            (
1115                4..6,
1116                "four\nfive\n",
1117                "FOUR\nFIVE\n",
1118                DiffHunkStatus::Modified(DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk),
1119            ),
1120            (
1121                7..8,
1122                "seven\n",
1123                "SEVEN\n",
1124                DiffHunkStatus::Modified(DiffHunkSecondaryStatus::HasSecondaryHunk),
1125            ),
1126        ];
1127
1128        assert_hunks(
1129            uncommitted_diff.hunks_intersecting_range(
1130                Anchor::MIN..Anchor::MAX,
1131                &buffer,
1132                Some(&unstaged_diff),
1133            ),
1134            &buffer,
1135            &head_text,
1136            &expected_hunks,
1137        );
1138    }
1139
1140    #[gpui::test]
1141    async fn test_buffer_diff_range(cx: &mut TestAppContext) {
1142        let diff_base = Arc::new(
1143            "
1144            one
1145            two
1146            three
1147            four
1148            five
1149            six
1150            seven
1151            eight
1152            nine
1153            ten
1154        "
1155            .unindent(),
1156        );
1157
1158        let buffer_text = "
1159            A
1160            one
1161            B
1162            two
1163            C
1164            three
1165            HELLO
1166            four
1167            five
1168            SIXTEEN
1169            seven
1170            eight
1171            WORLD
1172            nine
1173
1174            ten
1175
1176        "
1177        .unindent();
1178
1179        let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1180        let diff = cx
1181            .update(|cx| {
1182                BufferDiff::build(buffer.snapshot(), Some(diff_base.clone()), None, None, cx)
1183            })
1184            .await;
1185        assert_eq!(
1186            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None)
1187                .count(),
1188            8
1189        );
1190
1191        assert_hunks(
1192            diff.hunks_intersecting_range(
1193                buffer.anchor_before(Point::new(7, 0))..buffer.anchor_before(Point::new(12, 0)),
1194                &buffer,
1195                None,
1196            ),
1197            &buffer,
1198            &diff_base,
1199            &[
1200                (6..7, "", "HELLO\n", DiffHunkStatus::added()),
1201                (9..10, "six\n", "SIXTEEN\n", DiffHunkStatus::modified()),
1202                (12..13, "", "WORLD\n", DiffHunkStatus::added()),
1203            ],
1204        );
1205    }
1206
1207    #[gpui::test]
1208    async fn test_buffer_diff_compare(cx: &mut TestAppContext) {
1209        let base_text = "
1210            zero
1211            one
1212            two
1213            three
1214            four
1215            five
1216            six
1217            seven
1218            eight
1219            nine
1220        "
1221        .unindent();
1222
1223        let buffer_text_1 = "
1224            one
1225            three
1226            four
1227            five
1228            SIX
1229            seven
1230            eight
1231            NINE
1232        "
1233        .unindent();
1234
1235        let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text_1);
1236
1237        let empty_diff = BufferDiff::build_empty(&buffer);
1238        let diff_1 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1239        let range = diff_1.compare(&empty_diff, &buffer).unwrap();
1240        assert_eq!(range.to_point(&buffer), Point::new(0, 0)..Point::new(8, 0));
1241
1242        // Edit does not affect the diff.
1243        buffer.edit_via_marked_text(
1244            &"
1245                one
1246                three
1247                four
1248                five
1249                «SIX.5»
1250                seven
1251                eight
1252                NINE
1253            "
1254            .unindent(),
1255        );
1256        let diff_2 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1257        assert_eq!(None, diff_2.compare(&diff_1, &buffer));
1258
1259        // Edit turns a deletion hunk into a modification.
1260        buffer.edit_via_marked_text(
1261            &"
1262                one
1263                «THREE»
1264                four
1265                five
1266                SIX.5
1267                seven
1268                eight
1269                NINE
1270            "
1271            .unindent(),
1272        );
1273        let diff_3 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1274        let range = diff_3.compare(&diff_2, &buffer).unwrap();
1275        assert_eq!(range.to_point(&buffer), Point::new(1, 0)..Point::new(2, 0));
1276
1277        // Edit turns a modification hunk into a deletion.
1278        buffer.edit_via_marked_text(
1279            &"
1280                one
1281                THREE
1282                four
1283                five«»
1284                seven
1285                eight
1286                NINE
1287            "
1288            .unindent(),
1289        );
1290        let diff_4 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1291        let range = diff_4.compare(&diff_3, &buffer).unwrap();
1292        assert_eq!(range.to_point(&buffer), Point::new(3, 4)..Point::new(4, 0));
1293
1294        // Edit introduces a new insertion hunk.
1295        buffer.edit_via_marked_text(
1296            &"
1297                one
1298                THREE
1299                four«
1300                FOUR.5
1301                »five
1302                seven
1303                eight
1304                NINE
1305            "
1306            .unindent(),
1307        );
1308        let diff_5 = BufferDiff::build_sync(buffer.snapshot(), base_text.clone(), cx);
1309        let range = diff_5.compare(&diff_4, &buffer).unwrap();
1310        assert_eq!(range.to_point(&buffer), Point::new(3, 0)..Point::new(4, 0));
1311
1312        // Edit removes a hunk.
1313        buffer.edit_via_marked_text(
1314            &"
1315                one
1316                THREE
1317                four
1318                FOUR.5
1319                five
1320                seven
1321                eight
1322                «nine»
1323            "
1324            .unindent(),
1325        );
1326        let diff_6 = BufferDiff::build_sync(buffer.snapshot(), base_text, cx);
1327        let range = diff_6.compare(&diff_5, &buffer).unwrap();
1328        assert_eq!(range.to_point(&buffer), Point::new(7, 0)..Point::new(8, 0));
1329    }
1330
1331    #[gpui::test(iterations = 100)]
1332    async fn test_secondary_edits_for_stage_unstage(cx: &mut TestAppContext, mut rng: StdRng) {
1333        fn gen_line(rng: &mut StdRng) -> String {
1334            if rng.gen_bool(0.2) {
1335                "\n".to_owned()
1336            } else {
1337                let c = rng.gen_range('A'..='Z');
1338                format!("{c}{c}{c}\n")
1339            }
1340        }
1341
1342        fn gen_working_copy(rng: &mut StdRng, head: &str) -> String {
1343            let mut old_lines = {
1344                let mut old_lines = Vec::new();
1345                let mut old_lines_iter = head.lines();
1346                while let Some(line) = old_lines_iter.next() {
1347                    assert!(!line.ends_with("\n"));
1348                    old_lines.push(line.to_owned());
1349                }
1350                if old_lines.last().is_some_and(|line| line.is_empty()) {
1351                    old_lines.pop();
1352                }
1353                old_lines.into_iter()
1354            };
1355            let mut result = String::new();
1356            let unchanged_count = rng.gen_range(0..=old_lines.len());
1357            result +=
1358                &old_lines
1359                    .by_ref()
1360                    .take(unchanged_count)
1361                    .fold(String::new(), |mut s, line| {
1362                        writeln!(&mut s, "{line}").unwrap();
1363                        s
1364                    });
1365            while old_lines.len() > 0 {
1366                let deleted_count = rng.gen_range(0..=old_lines.len());
1367                let _advance = old_lines
1368                    .by_ref()
1369                    .take(deleted_count)
1370                    .map(|line| line.len() + 1)
1371                    .sum::<usize>();
1372                let minimum_added = if deleted_count == 0 { 1 } else { 0 };
1373                let added_count = rng.gen_range(minimum_added..=5);
1374                let addition = (0..added_count).map(|_| gen_line(rng)).collect::<String>();
1375                result += &addition;
1376
1377                if old_lines.len() > 0 {
1378                    let blank_lines = old_lines.clone().take_while(|line| line.is_empty()).count();
1379                    if blank_lines == old_lines.len() {
1380                        break;
1381                    };
1382                    let unchanged_count = rng.gen_range((blank_lines + 1).max(1)..=old_lines.len());
1383                    result += &old_lines.by_ref().take(unchanged_count).fold(
1384                        String::new(),
1385                        |mut s, line| {
1386                            writeln!(&mut s, "{line}").unwrap();
1387                            s
1388                        },
1389                    );
1390                }
1391            }
1392            result
1393        }
1394
1395        fn uncommitted_diff(
1396            working_copy: &language::BufferSnapshot,
1397            index_text: &Entity<language::Buffer>,
1398            head_text: String,
1399            cx: &mut TestAppContext,
1400        ) -> BufferDiff {
1401            let inner = BufferDiff::build_sync(working_copy.text.clone(), head_text, cx);
1402            let secondary = BufferDiff {
1403                buffer_id: working_copy.remote_id(),
1404                inner: BufferDiff::build_sync(
1405                    working_copy.text.clone(),
1406                    index_text.read_with(cx, |index_text, _| index_text.text()),
1407                    cx,
1408                ),
1409                secondary_diff: None,
1410            };
1411            let secondary = cx.new(|_| secondary);
1412            BufferDiff {
1413                buffer_id: working_copy.remote_id(),
1414                inner,
1415                secondary_diff: Some(secondary),
1416            }
1417        }
1418
1419        let operations = std::env::var("OPERATIONS")
1420            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1421            .unwrap_or(10);
1422
1423        let rng = &mut rng;
1424        let head_text = ('a'..='z').fold(String::new(), |mut s, c| {
1425            writeln!(&mut s, "{c}{c}{c}").unwrap();
1426            s
1427        });
1428        let working_copy = gen_working_copy(rng, &head_text);
1429        let working_copy = cx.new(|cx| {
1430            language::Buffer::local_normalized(
1431                Rope::from(working_copy.as_str()),
1432                text::LineEnding::default(),
1433                cx,
1434            )
1435        });
1436        let working_copy = working_copy.read_with(cx, |working_copy, _| working_copy.snapshot());
1437        let index_text = cx.new(|cx| {
1438            language::Buffer::local_normalized(
1439                if rng.gen() {
1440                    Rope::from(head_text.as_str())
1441                } else {
1442                    working_copy.as_rope().clone()
1443                },
1444                text::LineEnding::default(),
1445                cx,
1446            )
1447        });
1448
1449        let mut diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
1450        let mut hunks = cx.update(|cx| {
1451            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
1452                .collect::<Vec<_>>()
1453        });
1454        if hunks.len() == 0 {
1455            return;
1456        }
1457
1458        for _ in 0..operations {
1459            let i = rng.gen_range(0..hunks.len());
1460            let hunk = &mut hunks[i];
1461            let hunk_fields = (
1462                hunk.diff_base_byte_range.clone(),
1463                hunk.secondary_diff_base_byte_range.clone(),
1464                hunk.buffer_range.clone(),
1465            );
1466            let stage = match (
1467                hunk.secondary_status,
1468                hunk.secondary_diff_base_byte_range.clone(),
1469            ) {
1470                (DiffHunkSecondaryStatus::HasSecondaryHunk, Some(_)) => {
1471                    hunk.secondary_status = DiffHunkSecondaryStatus::None;
1472                    hunk.secondary_diff_base_byte_range = None;
1473                    true
1474                }
1475                (DiffHunkSecondaryStatus::None, None) => {
1476                    hunk.secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
1477                    // We don't look at this, just notice whether it's Some or not.
1478                    hunk.secondary_diff_base_byte_range = Some(17..17);
1479                    false
1480                }
1481                _ => unreachable!(),
1482            };
1483
1484            let snapshot = cx.update(|cx| diff.snapshot(cx));
1485            let edits = snapshot.secondary_edits_for_stage_or_unstage(
1486                stage,
1487                [hunk_fields].into_iter(),
1488                &working_copy,
1489            );
1490            index_text.update(cx, |index_text, cx| {
1491                index_text.edit(edits, None, cx);
1492            });
1493
1494            diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
1495            let found_hunks = cx.update(|cx| {
1496                diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
1497                    .collect::<Vec<_>>()
1498            });
1499            assert_eq!(hunks.len(), found_hunks.len());
1500            for (expected_hunk, found_hunk) in hunks.iter().zip(&found_hunks) {
1501                assert_eq!(
1502                    expected_hunk.buffer_range.to_point(&working_copy),
1503                    found_hunk.buffer_range.to_point(&working_copy)
1504                );
1505                assert_eq!(
1506                    expected_hunk.diff_base_byte_range,
1507                    found_hunk.diff_base_byte_range
1508                );
1509                assert_eq!(expected_hunk.secondary_status, found_hunk.secondary_status);
1510                assert_eq!(
1511                    expected_hunk.secondary_diff_base_byte_range.is_some(),
1512                    found_hunk.secondary_diff_base_byte_range.is_some()
1513                )
1514            }
1515            hunks = found_hunks;
1516        }
1517    }
1518}