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