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