buffer_diff.rs

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