buffer_diff.rs

   1use futures::{channel::oneshot, future::OptionFuture};
   2use git2::{DiffLineType as GitDiffLineType, DiffOptions as GitOptions, Patch as GitPatch};
   3use gpui::{App, 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
 619            .background_executor()
 620            .spawn(OptionFuture::from(base_text_snapshot));
 621
 622        let hunks = cx.background_executor().spawn({
 623            let buffer = buffer.clone();
 624            async move { compute_hunks(diff_base, buffer) }
 625        });
 626
 627        async move {
 628            let (base_text, hunks) = futures::join!(base_text_snapshot, hunks);
 629            BufferDiffInner { base_text, hunks }
 630        }
 631    }
 632
 633    fn build_with_base_buffer(
 634        buffer: text::BufferSnapshot,
 635        diff_base: Option<Arc<String>>,
 636        diff_base_buffer: Option<language::BufferSnapshot>,
 637        cx: &App,
 638    ) -> impl Future<Output = BufferDiffInner> {
 639        let diff_base = diff_base.clone().zip(
 640            diff_base_buffer
 641                .clone()
 642                .map(|buffer| buffer.as_rope().clone()),
 643        );
 644        cx.background_executor().spawn(async move {
 645            BufferDiffInner {
 646                hunks: compute_hunks(diff_base, buffer),
 647                base_text: diff_base_buffer,
 648            }
 649        })
 650    }
 651
 652    fn build_empty(buffer: &text::BufferSnapshot) -> BufferDiffInner {
 653        BufferDiffInner {
 654            hunks: SumTree::new(buffer),
 655            base_text: None,
 656        }
 657    }
 658
 659    pub fn build_with_single_insertion(
 660        insertion_present_in_secondary_diff: bool,
 661        buffer: language::BufferSnapshot,
 662        cx: &mut App,
 663    ) -> BufferDiffSnapshot {
 664        let base_text = language::Buffer::build_empty_snapshot(cx);
 665        let hunks = SumTree::from_item(
 666            InternalDiffHunk {
 667                buffer_range: Anchor::MIN..Anchor::MAX,
 668                diff_base_byte_range: 0..0,
 669            },
 670            &base_text,
 671        );
 672        BufferDiffSnapshot {
 673            inner: BufferDiffInner {
 674                hunks: hunks.clone(),
 675                base_text: Some(base_text.clone()),
 676            },
 677            secondary_diff: Some(Box::new(BufferDiffSnapshot {
 678                inner: BufferDiffInner {
 679                    hunks: if insertion_present_in_secondary_diff {
 680                        hunks
 681                    } else {
 682                        SumTree::new(&buffer.text)
 683                    },
 684                    base_text: Some(if insertion_present_in_secondary_diff {
 685                        base_text
 686                    } else {
 687                        buffer
 688                    }),
 689                },
 690                secondary_diff: None,
 691                is_single_insertion: true,
 692            })),
 693            is_single_insertion: true,
 694        }
 695    }
 696
 697    pub fn set_secondary_diff(&mut self, diff: Entity<BufferDiff>) {
 698        self.secondary_diff = Some(diff);
 699    }
 700
 701    pub fn secondary_diff(&self) -> Option<Entity<BufferDiff>> {
 702        Some(self.secondary_diff.as_ref()?.clone())
 703    }
 704
 705    pub fn range_to_hunk_range(
 706        &self,
 707        range: Range<Anchor>,
 708        buffer: &text::BufferSnapshot,
 709        cx: &App,
 710    ) -> Option<Range<Anchor>> {
 711        let start = self
 712            .hunks_intersecting_range(range.clone(), &buffer, cx)
 713            .next()?
 714            .buffer_range
 715            .start;
 716        let end = self
 717            .hunks_intersecting_range_rev(range.clone(), &buffer)
 718            .next()?
 719            .buffer_range
 720            .end;
 721        Some(start..end)
 722    }
 723
 724    pub async fn update_diff(
 725        this: Entity<BufferDiff>,
 726        buffer: text::BufferSnapshot,
 727        base_text: Option<Arc<String>>,
 728        base_text_changed: bool,
 729        language_changed: bool,
 730        language: Option<Arc<Language>>,
 731        language_registry: Option<Arc<LanguageRegistry>>,
 732        cx: &mut AsyncApp,
 733    ) -> anyhow::Result<Option<Range<Anchor>>> {
 734        let snapshot = if base_text_changed || language_changed {
 735            cx.update(|cx| {
 736                Self::build(
 737                    buffer.clone(),
 738                    base_text,
 739                    language.clone(),
 740                    language_registry.clone(),
 741                    cx,
 742                )
 743            })?
 744            .await
 745        } else {
 746            this.read_with(cx, |this, cx| {
 747                Self::build_with_base_buffer(
 748                    buffer.clone(),
 749                    base_text,
 750                    this.base_text().cloned(),
 751                    cx,
 752                )
 753            })?
 754            .await
 755        };
 756
 757        this.update(cx, |this, _| this.set_state(snapshot, &buffer))
 758    }
 759
 760    pub fn update_diff_from(
 761        &mut self,
 762        buffer: &text::BufferSnapshot,
 763        other: &Entity<Self>,
 764        cx: &mut Context<Self>,
 765    ) -> Option<Range<Anchor>> {
 766        let other = other.read(cx).inner.clone();
 767        self.set_state(other, buffer)
 768    }
 769
 770    fn set_state(
 771        &mut self,
 772        inner: BufferDiffInner,
 773        buffer: &text::BufferSnapshot,
 774    ) -> Option<Range<Anchor>> {
 775        let changed_range = match (self.inner.base_text.as_ref(), inner.base_text.as_ref()) {
 776            (None, None) => None,
 777            (Some(old), Some(new)) if old.remote_id() == new.remote_id() => {
 778                inner.compare(&self.inner, buffer)
 779            }
 780            _ => Some(text::Anchor::MIN..text::Anchor::MAX),
 781        };
 782        self.inner = inner;
 783        changed_range
 784    }
 785
 786    pub fn base_text(&self) -> Option<&language::BufferSnapshot> {
 787        self.inner.base_text.as_ref()
 788    }
 789
 790    pub fn snapshot(&self, cx: &App) -> BufferDiffSnapshot {
 791        BufferDiffSnapshot {
 792            inner: self.inner.clone(),
 793            secondary_diff: self
 794                .secondary_diff
 795                .as_ref()
 796                .map(|diff| Box::new(diff.read(cx).snapshot(cx))),
 797            is_single_insertion: false,
 798        }
 799    }
 800
 801    pub fn hunks_intersecting_range<'a>(
 802        &'a self,
 803        range: Range<text::Anchor>,
 804        buffer_snapshot: &'a text::BufferSnapshot,
 805        cx: &'a App,
 806    ) -> impl 'a + Iterator<Item = DiffHunk> {
 807        let unstaged_counterpart = self
 808            .secondary_diff
 809            .as_ref()
 810            .map(|diff| &diff.read(cx).inner);
 811        self.inner
 812            .hunks_intersecting_range(range, buffer_snapshot, unstaged_counterpart)
 813    }
 814
 815    pub fn hunks_intersecting_range_rev<'a>(
 816        &'a self,
 817        range: Range<text::Anchor>,
 818        buffer_snapshot: &'a text::BufferSnapshot,
 819    ) -> impl 'a + Iterator<Item = DiffHunk> {
 820        self.inner
 821            .hunks_intersecting_range_rev(range, buffer_snapshot)
 822    }
 823
 824    pub fn hunks_in_row_range<'a>(
 825        &'a self,
 826        range: Range<u32>,
 827        buffer: &'a text::BufferSnapshot,
 828        cx: &'a App,
 829    ) -> impl 'a + Iterator<Item = DiffHunk> {
 830        let start = buffer.anchor_before(Point::new(range.start, 0));
 831        let end = buffer.anchor_after(Point::new(range.end, 0));
 832        self.hunks_intersecting_range(start..end, buffer, cx)
 833    }
 834
 835    /// Used in cases where the change set isn't derived from git.
 836    pub fn set_base_text(
 837        &mut self,
 838        base_buffer: Entity<language::Buffer>,
 839        buffer: text::BufferSnapshot,
 840        cx: &mut Context<Self>,
 841    ) -> oneshot::Receiver<()> {
 842        let (tx, rx) = oneshot::channel();
 843        let this = cx.weak_entity();
 844        let base_buffer = base_buffer.read(cx);
 845        let language_registry = base_buffer.language_registry();
 846        let base_buffer = base_buffer.snapshot();
 847        let base_text = Arc::new(base_buffer.text());
 848
 849        let snapshot = BufferDiff::build(
 850            buffer.clone(),
 851            Some(base_text),
 852            base_buffer.language().cloned(),
 853            language_registry,
 854            cx,
 855        );
 856        let complete_on_drop = util::defer(|| {
 857            tx.send(()).ok();
 858        });
 859        cx.spawn(|_, mut cx| async move {
 860            let snapshot = snapshot.await;
 861            let Some(this) = this.upgrade() else {
 862                return;
 863            };
 864            this.update(&mut cx, |this, _| {
 865                this.set_state(snapshot, &buffer);
 866            })
 867            .log_err();
 868            drop(complete_on_drop)
 869        })
 870        .detach();
 871        rx
 872    }
 873
 874    #[cfg(any(test, feature = "test-support"))]
 875    pub fn base_text_string(&self) -> Option<String> {
 876        self.inner.base_text.as_ref().map(|buffer| buffer.text())
 877    }
 878
 879    pub fn new(buffer: &text::BufferSnapshot) -> Self {
 880        BufferDiff {
 881            buffer_id: buffer.remote_id(),
 882            inner: BufferDiff::build_empty(buffer),
 883            secondary_diff: None,
 884        }
 885    }
 886
 887    #[cfg(any(test, feature = "test-support"))]
 888    pub fn new_with_base_text(
 889        base_text: &str,
 890        buffer: &Entity<language::Buffer>,
 891        cx: &mut App,
 892    ) -> Self {
 893        let mut base_text = base_text.to_owned();
 894        text::LineEnding::normalize(&mut base_text);
 895        let snapshot = BufferDiff::build(
 896            buffer.read(cx).text_snapshot(),
 897            Some(base_text.into()),
 898            None,
 899            None,
 900            cx,
 901        );
 902        let snapshot = cx.background_executor().block(snapshot);
 903        BufferDiff {
 904            buffer_id: buffer.read(cx).remote_id(),
 905            inner: snapshot,
 906            secondary_diff: None,
 907        }
 908    }
 909
 910    #[cfg(any(test, feature = "test-support"))]
 911    pub fn recalculate_diff_sync(&mut self, buffer: text::BufferSnapshot, cx: &mut Context<Self>) {
 912        let base_text = self
 913            .inner
 914            .base_text
 915            .as_ref()
 916            .map(|base_text| base_text.text());
 917        let snapshot = BufferDiff::build_with_base_buffer(
 918            buffer.clone(),
 919            base_text.clone().map(Arc::new),
 920            self.inner.base_text.clone(),
 921            cx,
 922        );
 923        let snapshot = cx.background_executor().block(snapshot);
 924        let changed_range = self.set_state(snapshot, &buffer);
 925        cx.emit(BufferDiffEvent::DiffChanged { changed_range });
 926    }
 927}
 928
 929impl DiffHunk {
 930    pub fn status(&self) -> DiffHunkStatus {
 931        if self.buffer_range.start == self.buffer_range.end {
 932            DiffHunkStatus::Removed(self.secondary_status)
 933        } else if self.diff_base_byte_range.is_empty() {
 934            DiffHunkStatus::Added(self.secondary_status)
 935        } else {
 936            DiffHunkStatus::Modified(self.secondary_status)
 937        }
 938    }
 939}
 940
 941impl DiffHunkStatus {
 942    pub fn is_removed(&self) -> bool {
 943        matches!(self, DiffHunkStatus::Removed(_))
 944    }
 945
 946    #[cfg(any(test, feature = "test-support"))]
 947    pub fn removed() -> Self {
 948        DiffHunkStatus::Removed(DiffHunkSecondaryStatus::None)
 949    }
 950
 951    #[cfg(any(test, feature = "test-support"))]
 952    pub fn added() -> Self {
 953        DiffHunkStatus::Added(DiffHunkSecondaryStatus::None)
 954    }
 955
 956    #[cfg(any(test, feature = "test-support"))]
 957    pub fn modified() -> Self {
 958        DiffHunkStatus::Modified(DiffHunkSecondaryStatus::None)
 959    }
 960}
 961
 962/// Range (crossing new lines), old, new
 963#[cfg(any(test, feature = "test-support"))]
 964#[track_caller]
 965pub fn assert_hunks<Iter>(
 966    diff_hunks: Iter,
 967    buffer: &text::BufferSnapshot,
 968    diff_base: &str,
 969    expected_hunks: &[(Range<u32>, &str, &str, DiffHunkStatus)],
 970) where
 971    Iter: Iterator<Item = DiffHunk>,
 972{
 973    let actual_hunks = diff_hunks
 974        .map(|hunk| {
 975            (
 976                hunk.row_range.clone(),
 977                &diff_base[hunk.diff_base_byte_range.clone()],
 978                buffer
 979                    .text_for_range(
 980                        Point::new(hunk.row_range.start, 0)..Point::new(hunk.row_range.end, 0),
 981                    )
 982                    .collect::<String>(),
 983                hunk.status(),
 984            )
 985        })
 986        .collect::<Vec<_>>();
 987
 988    let expected_hunks: Vec<_> = expected_hunks
 989        .iter()
 990        .map(|(r, s, h, status)| (r.clone(), *s, h.to_string(), *status))
 991        .collect();
 992
 993    assert_eq!(actual_hunks, expected_hunks);
 994}
 995
 996#[cfg(test)]
 997mod tests {
 998    use std::fmt::Write as _;
 999
1000    use super::*;
1001    use gpui::{AppContext as _, TestAppContext};
1002    use rand::{rngs::StdRng, Rng as _};
1003    use text::{Buffer, BufferId, Rope};
1004    use unindent::Unindent as _;
1005
1006    #[ctor::ctor]
1007    fn init_logger() {
1008        if std::env::var("RUST_LOG").is_ok() {
1009            env_logger::init();
1010        }
1011    }
1012
1013    #[gpui::test]
1014    async fn test_buffer_diff_simple(cx: &mut gpui::TestAppContext) {
1015        let diff_base = "
1016            one
1017            two
1018            three
1019        "
1020        .unindent();
1021
1022        let buffer_text = "
1023            one
1024            HELLO
1025            three
1026        "
1027        .unindent();
1028
1029        let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1030        let mut diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1031        assert_hunks(
1032            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1033            &buffer,
1034            &diff_base,
1035            &[(1..2, "two\n", "HELLO\n", DiffHunkStatus::modified())],
1036        );
1037
1038        buffer.edit([(0..0, "point five\n")]);
1039        diff = BufferDiff::build_sync(buffer.clone(), diff_base.clone(), cx);
1040        assert_hunks(
1041            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1042            &buffer,
1043            &diff_base,
1044            &[
1045                (0..1, "", "point five\n", DiffHunkStatus::added()),
1046                (2..3, "two\n", "HELLO\n", DiffHunkStatus::modified()),
1047            ],
1048        );
1049
1050        diff = BufferDiff::build_empty(&buffer);
1051        assert_hunks(
1052            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None),
1053            &buffer,
1054            &diff_base,
1055            &[],
1056        );
1057    }
1058
1059    #[gpui::test]
1060    async fn test_buffer_diff_with_secondary(cx: &mut gpui::TestAppContext) {
1061        let head_text = "
1062            zero
1063            one
1064            two
1065            three
1066            four
1067            five
1068            six
1069            seven
1070            eight
1071            nine
1072        "
1073        .unindent();
1074
1075        let index_text = "
1076            zero
1077            one
1078            TWO
1079            three
1080            FOUR
1081            five
1082            six
1083            seven
1084            eight
1085            NINE
1086        "
1087        .unindent();
1088
1089        let buffer_text = "
1090            zero
1091            one
1092            TWO
1093            three
1094            FOUR
1095            FIVE
1096            six
1097            SEVEN
1098            eight
1099            nine
1100        "
1101        .unindent();
1102
1103        let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1104        let unstaged_diff = BufferDiff::build_sync(buffer.clone(), index_text.clone(), cx);
1105
1106        let uncommitted_diff = BufferDiff::build_sync(buffer.clone(), head_text.clone(), cx);
1107
1108        let expected_hunks = vec![
1109            (
1110                2..3,
1111                "two\n",
1112                "TWO\n",
1113                DiffHunkStatus::Modified(DiffHunkSecondaryStatus::None),
1114            ),
1115            (
1116                4..6,
1117                "four\nfive\n",
1118                "FOUR\nFIVE\n",
1119                DiffHunkStatus::Modified(DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk),
1120            ),
1121            (
1122                7..8,
1123                "seven\n",
1124                "SEVEN\n",
1125                DiffHunkStatus::Modified(DiffHunkSecondaryStatus::HasSecondaryHunk),
1126            ),
1127        ];
1128
1129        assert_hunks(
1130            uncommitted_diff.hunks_intersecting_range(
1131                Anchor::MIN..Anchor::MAX,
1132                &buffer,
1133                Some(&unstaged_diff),
1134            ),
1135            &buffer,
1136            &head_text,
1137            &expected_hunks,
1138        );
1139    }
1140
1141    #[gpui::test]
1142    async fn test_buffer_diff_range(cx: &mut TestAppContext) {
1143        let diff_base = Arc::new(
1144            "
1145            one
1146            two
1147            three
1148            four
1149            five
1150            six
1151            seven
1152            eight
1153            nine
1154            ten
1155        "
1156            .unindent(),
1157        );
1158
1159        let buffer_text = "
1160            A
1161            one
1162            B
1163            two
1164            C
1165            three
1166            HELLO
1167            four
1168            five
1169            SIXTEEN
1170            seven
1171            eight
1172            WORLD
1173            nine
1174
1175            ten
1176
1177        "
1178        .unindent();
1179
1180        let buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text);
1181        let diff = cx
1182            .update(|cx| {
1183                BufferDiff::build(buffer.snapshot(), Some(diff_base.clone()), None, None, cx)
1184            })
1185            .await;
1186        assert_eq!(
1187            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, None)
1188                .count(),
1189            8
1190        );
1191
1192        assert_hunks(
1193            diff.hunks_intersecting_range(
1194                buffer.anchor_before(Point::new(7, 0))..buffer.anchor_before(Point::new(12, 0)),
1195                &buffer,
1196                None,
1197            ),
1198            &buffer,
1199            &diff_base,
1200            &[
1201                (6..7, "", "HELLO\n", DiffHunkStatus::added()),
1202                (9..10, "six\n", "SIXTEEN\n", DiffHunkStatus::modified()),
1203                (12..13, "", "WORLD\n", DiffHunkStatus::added()),
1204            ],
1205        );
1206    }
1207
1208    #[gpui::test]
1209    async fn test_buffer_diff_compare(cx: &mut TestAppContext) {
1210        let base_text = "
1211            zero
1212            one
1213            two
1214            three
1215            four
1216            five
1217            six
1218            seven
1219            eight
1220            nine
1221        "
1222        .unindent();
1223
1224        let buffer_text_1 = "
1225            one
1226            three
1227            four
1228            five
1229            SIX
1230            seven
1231            eight
1232            NINE
1233        "
1234        .unindent();
1235
1236        let mut buffer = Buffer::new(0, BufferId::new(1).unwrap(), buffer_text_1);
1237
1238        let empty_diff = BufferDiff::build_empty(&buffer);
1239        let diff_1 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1240        let range = diff_1.compare(&empty_diff, &buffer).unwrap();
1241        assert_eq!(range.to_point(&buffer), Point::new(0, 0)..Point::new(8, 0));
1242
1243        // Edit does not affect the diff.
1244        buffer.edit_via_marked_text(
1245            &"
1246                one
1247                three
1248                four
1249                five
1250                «SIX.5»
1251                seven
1252                eight
1253                NINE
1254            "
1255            .unindent(),
1256        );
1257        let diff_2 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1258        assert_eq!(None, diff_2.compare(&diff_1, &buffer));
1259
1260        // Edit turns a deletion hunk into a modification.
1261        buffer.edit_via_marked_text(
1262            &"
1263                one
1264                «THREE»
1265                four
1266                five
1267                SIX.5
1268                seven
1269                eight
1270                NINE
1271            "
1272            .unindent(),
1273        );
1274        let diff_3 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1275        let range = diff_3.compare(&diff_2, &buffer).unwrap();
1276        assert_eq!(range.to_point(&buffer), Point::new(1, 0)..Point::new(2, 0));
1277
1278        // Edit turns a modification hunk into a deletion.
1279        buffer.edit_via_marked_text(
1280            &"
1281                one
1282                THREE
1283                four
1284                five«»
1285                seven
1286                eight
1287                NINE
1288            "
1289            .unindent(),
1290        );
1291        let diff_4 = BufferDiff::build_sync(buffer.clone(), base_text.clone(), cx);
1292        let range = diff_4.compare(&diff_3, &buffer).unwrap();
1293        assert_eq!(range.to_point(&buffer), Point::new(3, 4)..Point::new(4, 0));
1294
1295        // Edit introduces a new insertion hunk.
1296        buffer.edit_via_marked_text(
1297            &"
1298                one
1299                THREE
1300                four«
1301                FOUR.5
1302                »five
1303                seven
1304                eight
1305                NINE
1306            "
1307            .unindent(),
1308        );
1309        let diff_5 = BufferDiff::build_sync(buffer.snapshot(), base_text.clone(), cx);
1310        let range = diff_5.compare(&diff_4, &buffer).unwrap();
1311        assert_eq!(range.to_point(&buffer), Point::new(3, 0)..Point::new(4, 0));
1312
1313        // Edit removes a hunk.
1314        buffer.edit_via_marked_text(
1315            &"
1316                one
1317                THREE
1318                four
1319                FOUR.5
1320                five
1321                seven
1322                eight
1323                «nine»
1324            "
1325            .unindent(),
1326        );
1327        let diff_6 = BufferDiff::build_sync(buffer.snapshot(), base_text, cx);
1328        let range = diff_6.compare(&diff_5, &buffer).unwrap();
1329        assert_eq!(range.to_point(&buffer), Point::new(7, 0)..Point::new(8, 0));
1330    }
1331
1332    #[gpui::test(iterations = 100)]
1333    async fn test_secondary_edits_for_stage_unstage(cx: &mut TestAppContext, mut rng: StdRng) {
1334        fn gen_line(rng: &mut StdRng) -> String {
1335            if rng.gen_bool(0.2) {
1336                "\n".to_owned()
1337            } else {
1338                let c = rng.gen_range('A'..='Z');
1339                format!("{c}{c}{c}\n")
1340            }
1341        }
1342
1343        fn gen_working_copy(rng: &mut StdRng, head: &str) -> String {
1344            let mut old_lines = {
1345                let mut old_lines = Vec::new();
1346                let mut old_lines_iter = head.lines();
1347                while let Some(line) = old_lines_iter.next() {
1348                    assert!(!line.ends_with("\n"));
1349                    old_lines.push(line.to_owned());
1350                }
1351                if old_lines.last().is_some_and(|line| line.is_empty()) {
1352                    old_lines.pop();
1353                }
1354                old_lines.into_iter()
1355            };
1356            let mut result = String::new();
1357            let unchanged_count = rng.gen_range(0..=old_lines.len());
1358            result +=
1359                &old_lines
1360                    .by_ref()
1361                    .take(unchanged_count)
1362                    .fold(String::new(), |mut s, line| {
1363                        writeln!(&mut s, "{line}").unwrap();
1364                        s
1365                    });
1366            while old_lines.len() > 0 {
1367                let deleted_count = rng.gen_range(0..=old_lines.len());
1368                let _advance = old_lines
1369                    .by_ref()
1370                    .take(deleted_count)
1371                    .map(|line| line.len() + 1)
1372                    .sum::<usize>();
1373                let minimum_added = if deleted_count == 0 { 1 } else { 0 };
1374                let added_count = rng.gen_range(minimum_added..=5);
1375                let addition = (0..added_count).map(|_| gen_line(rng)).collect::<String>();
1376                result += &addition;
1377
1378                if old_lines.len() > 0 {
1379                    let blank_lines = old_lines.clone().take_while(|line| line.is_empty()).count();
1380                    if blank_lines == old_lines.len() {
1381                        break;
1382                    };
1383                    let unchanged_count = rng.gen_range((blank_lines + 1).max(1)..=old_lines.len());
1384                    result += &old_lines.by_ref().take(unchanged_count).fold(
1385                        String::new(),
1386                        |mut s, line| {
1387                            writeln!(&mut s, "{line}").unwrap();
1388                            s
1389                        },
1390                    );
1391                }
1392            }
1393            result
1394        }
1395
1396        fn uncommitted_diff(
1397            working_copy: &language::BufferSnapshot,
1398            index_text: &Entity<language::Buffer>,
1399            head_text: String,
1400            cx: &mut TestAppContext,
1401        ) -> BufferDiff {
1402            let inner = BufferDiff::build_sync(working_copy.text.clone(), head_text, cx);
1403            let secondary = BufferDiff {
1404                buffer_id: working_copy.remote_id(),
1405                inner: BufferDiff::build_sync(
1406                    working_copy.text.clone(),
1407                    index_text.read_with(cx, |index_text, _| index_text.text()),
1408                    cx,
1409                ),
1410                secondary_diff: None,
1411            };
1412            let secondary = cx.new(|_| secondary);
1413            BufferDiff {
1414                buffer_id: working_copy.remote_id(),
1415                inner,
1416                secondary_diff: Some(secondary),
1417            }
1418        }
1419
1420        let operations = std::env::var("OPERATIONS")
1421            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1422            .unwrap_or(10);
1423
1424        let rng = &mut rng;
1425        let head_text = ('a'..='z').fold(String::new(), |mut s, c| {
1426            writeln!(&mut s, "{c}{c}{c}").unwrap();
1427            s
1428        });
1429        let working_copy = gen_working_copy(rng, &head_text);
1430        let working_copy = cx.new(|cx| {
1431            language::Buffer::local_normalized(
1432                Rope::from(working_copy.as_str()),
1433                text::LineEnding::default(),
1434                cx,
1435            )
1436        });
1437        let working_copy = working_copy.read_with(cx, |working_copy, _| working_copy.snapshot());
1438        let index_text = cx.new(|cx| {
1439            language::Buffer::local_normalized(
1440                if rng.gen() {
1441                    Rope::from(head_text.as_str())
1442                } else {
1443                    working_copy.as_rope().clone()
1444                },
1445                text::LineEnding::default(),
1446                cx,
1447            )
1448        });
1449
1450        let mut diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
1451        let mut hunks = cx.update(|cx| {
1452            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
1453                .collect::<Vec<_>>()
1454        });
1455        if hunks.len() == 0 {
1456            return;
1457        }
1458
1459        for _ in 0..operations {
1460            let i = rng.gen_range(0..hunks.len());
1461            let hunk = &mut hunks[i];
1462            let hunk_fields = (
1463                hunk.diff_base_byte_range.clone(),
1464                hunk.secondary_diff_base_byte_range.clone(),
1465                hunk.buffer_range.clone(),
1466            );
1467            let stage = match (
1468                hunk.secondary_status,
1469                hunk.secondary_diff_base_byte_range.clone(),
1470            ) {
1471                (DiffHunkSecondaryStatus::HasSecondaryHunk, Some(_)) => {
1472                    hunk.secondary_status = DiffHunkSecondaryStatus::None;
1473                    hunk.secondary_diff_base_byte_range = None;
1474                    true
1475                }
1476                (DiffHunkSecondaryStatus::None, None) => {
1477                    hunk.secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
1478                    // We don't look at this, just notice whether it's Some or not.
1479                    hunk.secondary_diff_base_byte_range = Some(17..17);
1480                    false
1481                }
1482                _ => unreachable!(),
1483            };
1484
1485            let snapshot = cx.update(|cx| diff.snapshot(cx));
1486            let edits = snapshot.secondary_edits_for_stage_or_unstage(
1487                stage,
1488                [hunk_fields].into_iter(),
1489                &working_copy,
1490            );
1491            index_text.update(cx, |index_text, cx| {
1492                index_text.edit(edits, None, cx);
1493            });
1494
1495            diff = uncommitted_diff(&working_copy, &index_text, head_text.clone(), cx);
1496            let found_hunks = cx.update(|cx| {
1497                diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &working_copy, cx)
1498                    .collect::<Vec<_>>()
1499            });
1500            assert_eq!(hunks.len(), found_hunks.len());
1501            for (expected_hunk, found_hunk) in hunks.iter().zip(&found_hunks) {
1502                assert_eq!(
1503                    expected_hunk.buffer_range.to_point(&working_copy),
1504                    found_hunk.buffer_range.to_point(&working_copy)
1505                );
1506                assert_eq!(
1507                    expected_hunk.diff_base_byte_range,
1508                    found_hunk.diff_base_byte_range
1509                );
1510                assert_eq!(expected_hunk.secondary_status, found_hunk.secondary_status);
1511                assert_eq!(
1512                    expected_hunk.secondary_diff_base_byte_range.is_some(),
1513                    found_hunk.secondary_diff_base_byte_range.is_some()
1514                )
1515            }
1516            hunks = found_hunks;
1517        }
1518    }
1519}