project_diff.rs

   1use crate::{
   2    conflict_view::ConflictAddon,
   3    git_panel::{GitPanel, GitPanelAddon, GitStatusEntry},
   4    git_panel_settings::GitPanelSettings,
   5    remote_button::{render_publish_button, render_push_button},
   6};
   7use anyhow::{Context as _, Result, anyhow};
   8use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
   9use collections::{HashMap, HashSet};
  10use editor::{
  11    Addon, Editor, EditorEvent, SelectionEffects, SplittableEditor,
  12    actions::{GoToHunk, GoToPreviousHunk},
  13    multibuffer_context_lines,
  14    scroll::Autoscroll,
  15};
  16use git::{
  17    Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll, UnstageAndNext,
  18    repository::{Branch, RepoPath, Upstream, UpstreamTracking, UpstreamTrackingStatus},
  19    status::FileStatus,
  20};
  21use gpui::{
  22    Action, AnyElement, App, AppContext as _, AsyncWindowContext, Entity, EventEmitter,
  23    FocusHandle, Focusable, Render, Subscription, Task, WeakEntity, actions,
  24};
  25use language::{Anchor, Buffer, Capability, OffsetRangeExt};
  26use multi_buffer::{MultiBuffer, PathKey};
  27use project::{
  28    Project, ProjectPath,
  29    git_store::{
  30        Repository,
  31        branch_diff::{self, BranchDiffEvent, DiffBase},
  32    },
  33};
  34use settings::{Settings, SettingsStore};
  35use smol::future::yield_now;
  36use std::any::{Any, TypeId};
  37use std::sync::Arc;
  38use theme::ActiveTheme;
  39use ui::{KeyBinding, Tooltip, prelude::*, vertical_divider};
  40use util::{ResultExt as _, rel_path::RelPath};
  41use workspace::{
  42    CloseActiveItem, ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation,
  43    ToolbarItemView, Workspace,
  44    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},
  45    notifications::NotifyTaskExt,
  46    searchable::SearchableItemHandle,
  47};
  48use ztracing::instrument;
  49
  50actions!(
  51    git,
  52    [
  53        /// Shows the diff between the working directory and the index.
  54        Diff,
  55        /// Adds files to the git staging area.
  56        Add,
  57        /// Shows the diff between the working directory and your default
  58        /// branch (typically main or master).
  59        BranchDiff,
  60        LeaderAndFollower,
  61    ]
  62);
  63
  64pub struct ProjectDiff {
  65    project: Entity<Project>,
  66    multibuffer: Entity<MultiBuffer>,
  67    branch_diff: Entity<branch_diff::BranchDiff>,
  68    editor: Entity<SplittableEditor>,
  69    buffer_diff_subscriptions: HashMap<Arc<RelPath>, (Entity<BufferDiff>, Subscription)>,
  70    workspace: WeakEntity<Workspace>,
  71    focus_handle: FocusHandle,
  72    pending_scroll: Option<PathKey>,
  73    _task: Task<Result<()>>,
  74    _subscription: Subscription,
  75}
  76
  77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
  78pub enum RefreshReason {
  79    DiffChanged,
  80    StatusesChanged,
  81    EditorSaved,
  82}
  83
  84const CONFLICT_SORT_PREFIX: u64 = 1;
  85const TRACKED_SORT_PREFIX: u64 = 2;
  86const NEW_SORT_PREFIX: u64 = 3;
  87
  88impl ProjectDiff {
  89    pub(crate) fn register(workspace: &mut Workspace, cx: &mut Context<Workspace>) {
  90        workspace.register_action(Self::deploy);
  91        workspace.register_action(Self::deploy_branch_diff);
  92        workspace.register_action(|workspace, _: &Add, window, cx| {
  93            Self::deploy(workspace, &Diff, window, cx);
  94        });
  95        workspace::register_serializable_item::<ProjectDiff>(cx);
  96    }
  97
  98    fn deploy(
  99        workspace: &mut Workspace,
 100        _: &Diff,
 101        window: &mut Window,
 102        cx: &mut Context<Workspace>,
 103    ) {
 104        Self::deploy_at(workspace, None, window, cx)
 105    }
 106
 107    fn deploy_branch_diff(
 108        workspace: &mut Workspace,
 109        _: &BranchDiff,
 110        window: &mut Window,
 111        cx: &mut Context<Workspace>,
 112    ) {
 113        telemetry::event!("Git Branch Diff Opened");
 114        let project = workspace.project().clone();
 115
 116        let existing = workspace
 117            .items_of_type::<Self>(cx)
 118            .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Merge { .. }));
 119        if let Some(existing) = existing {
 120            workspace.activate_item(&existing, true, true, window, cx);
 121            return;
 122        }
 123        let workspace = cx.entity();
 124        window
 125            .spawn(cx, async move |cx| {
 126                let this = cx
 127                    .update(|window, cx| {
 128                        Self::new_with_default_branch(project, workspace.clone(), window, cx)
 129                    })?
 130                    .await?;
 131                workspace
 132                    .update_in(cx, |workspace, window, cx| {
 133                        workspace.add_item_to_active_pane(Box::new(this), None, true, window, cx);
 134                    })
 135                    .ok();
 136                anyhow::Ok(())
 137            })
 138            .detach_and_notify_err(window, cx);
 139    }
 140
 141    pub fn deploy_at(
 142        workspace: &mut Workspace,
 143        entry: Option<GitStatusEntry>,
 144        window: &mut Window,
 145        cx: &mut Context<Workspace>,
 146    ) {
 147        telemetry::event!(
 148            "Git Diff Opened",
 149            source = if entry.is_some() {
 150                "Git Panel"
 151            } else {
 152                "Action"
 153            }
 154        );
 155        let existing = workspace
 156            .items_of_type::<Self>(cx)
 157            .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Head));
 158        let project_diff = if let Some(existing) = existing {
 159            existing.update(cx, |project_diff, cx| {
 160                project_diff.move_to_beginning(window, cx);
 161            });
 162
 163            workspace.activate_item(&existing, true, true, window, cx);
 164            existing
 165        } else {
 166            let workspace_handle = cx.entity();
 167            let project_diff =
 168                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
 169            workspace.add_item_to_active_pane(
 170                Box::new(project_diff.clone()),
 171                None,
 172                true,
 173                window,
 174                cx,
 175            );
 176            project_diff
 177        };
 178        if let Some(entry) = entry {
 179            project_diff.update(cx, |project_diff, cx| {
 180                project_diff.move_to_entry(entry, window, cx);
 181            })
 182        }
 183    }
 184
 185    pub fn autoscroll(&self, cx: &mut Context<Self>) {
 186        self.editor.update(cx, |editor, cx| {
 187            editor.primary_editor().update(cx, |editor, cx| {
 188                editor.request_autoscroll(Autoscroll::fit(), cx);
 189            })
 190        })
 191    }
 192
 193    fn new_with_default_branch(
 194        project: Entity<Project>,
 195        workspace: Entity<Workspace>,
 196        window: &mut Window,
 197        cx: &mut App,
 198    ) -> Task<Result<Entity<Self>>> {
 199        let Some(repo) = project.read(cx).git_store().read(cx).active_repository() else {
 200            return Task::ready(Err(anyhow!("No active repository")));
 201        };
 202        let main_branch = repo.update(cx, |repo, _| repo.default_branch());
 203        window.spawn(cx, async move |cx| {
 204            let main_branch = main_branch
 205                .await??
 206                .context("Could not determine default branch")?;
 207
 208            let branch_diff = cx.new_window_entity(|window, cx| {
 209                branch_diff::BranchDiff::new(
 210                    DiffBase::Merge {
 211                        base_ref: main_branch,
 212                    },
 213                    project.clone(),
 214                    window,
 215                    cx,
 216                )
 217            })?;
 218            cx.new_window_entity(|window, cx| {
 219                Self::new_impl(branch_diff, project, workspace, window, cx)
 220            })
 221        })
 222    }
 223
 224    fn new(
 225        project: Entity<Project>,
 226        workspace: Entity<Workspace>,
 227        window: &mut Window,
 228        cx: &mut Context<Self>,
 229    ) -> Self {
 230        let branch_diff =
 231            cx.new(|cx| branch_diff::BranchDiff::new(DiffBase::Head, project.clone(), window, cx));
 232        Self::new_impl(branch_diff, project, workspace, window, cx)
 233    }
 234
 235    fn new_impl(
 236        branch_diff: Entity<branch_diff::BranchDiff>,
 237        project: Entity<Project>,
 238        workspace: Entity<Workspace>,
 239        window: &mut Window,
 240        cx: &mut Context<Self>,
 241    ) -> Self {
 242        let focus_handle = cx.focus_handle();
 243        let multibuffer = cx.new(|cx| {
 244            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
 245            multibuffer.set_all_diff_hunks_expanded(cx);
 246            multibuffer
 247        });
 248
 249        let editor = cx.new(|cx| {
 250            let diff_display_editor = SplittableEditor::new_unsplit(
 251                multibuffer.clone(),
 252                project.clone(),
 253                workspace.clone(),
 254                window,
 255                cx,
 256            );
 257            diff_display_editor
 258                .primary_editor()
 259                .update(cx, |editor, cx| {
 260                    editor.disable_diagnostics(cx);
 261
 262                    match branch_diff.read(cx).diff_base() {
 263                        DiffBase::Head => {
 264                            editor.register_addon(GitPanelAddon {
 265                                workspace: workspace.downgrade(),
 266                            });
 267                        }
 268                        DiffBase::Merge { .. } => {
 269                            editor.register_addon(BranchDiffAddon {
 270                                branch_diff: branch_diff.clone(),
 271                            });
 272                            editor.start_temporary_diff_override();
 273                            editor.set_render_diff_hunk_controls(
 274                                Arc::new(|_, _, _, _, _, _, _, _| gpui::Empty.into_any_element()),
 275                                cx,
 276                            );
 277                        }
 278                    }
 279                });
 280            diff_display_editor
 281        });
 282        cx.subscribe_in(&editor, window, Self::handle_editor_event)
 283            .detach();
 284
 285        let branch_diff_subscription = cx.subscribe_in(
 286            &branch_diff,
 287            window,
 288            move |this, _git_store, event, window, cx| match event {
 289                BranchDiffEvent::FileListChanged => {
 290                    this._task = window.spawn(cx, {
 291                        let this = cx.weak_entity();
 292                        async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
 293                    })
 294                }
 295            },
 296        );
 297
 298        let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
 299        let mut was_collapse_untracked_diff =
 300            GitPanelSettings::get_global(cx).collapse_untracked_diff;
 301        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
 302            let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
 303            let is_collapse_untracked_diff =
 304                GitPanelSettings::get_global(cx).collapse_untracked_diff;
 305            if is_sort_by_path != was_sort_by_path
 306                || is_collapse_untracked_diff != was_collapse_untracked_diff
 307            {
 308                this._task = {
 309                    window.spawn(cx, {
 310                        let this = cx.weak_entity();
 311                        async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
 312                    })
 313                }
 314            }
 315            was_sort_by_path = is_sort_by_path;
 316            was_collapse_untracked_diff = is_collapse_untracked_diff;
 317        })
 318        .detach();
 319
 320        let task = window.spawn(cx, {
 321            let this = cx.weak_entity();
 322            async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
 323        });
 324
 325        Self {
 326            project,
 327            workspace: workspace.downgrade(),
 328            branch_diff,
 329            focus_handle,
 330            editor,
 331            multibuffer,
 332            buffer_diff_subscriptions: Default::default(),
 333            pending_scroll: None,
 334            _task: task,
 335            _subscription: branch_diff_subscription,
 336        }
 337    }
 338
 339    pub fn diff_base<'a>(&'a self, cx: &'a App) -> &'a DiffBase {
 340        self.branch_diff.read(cx).diff_base()
 341    }
 342
 343    pub fn move_to_entry(
 344        &mut self,
 345        entry: GitStatusEntry,
 346        window: &mut Window,
 347        cx: &mut Context<Self>,
 348    ) {
 349        let Some(git_repo) = self.branch_diff.read(cx).repo() else {
 350            return;
 351        };
 352        let repo = git_repo.read(cx);
 353        let sort_prefix = sort_prefix(repo, &entry.repo_path, entry.status, cx);
 354        let path_key = PathKey::with_sort_prefix(sort_prefix, entry.repo_path.as_ref().clone());
 355
 356        self.move_to_path(path_key, window, cx)
 357    }
 358
 359    pub fn active_path(&self, cx: &App) -> Option<ProjectPath> {
 360        let editor = self.editor.read(cx).last_selected_editor().read(cx);
 361        let position = editor.selections.newest_anchor().head();
 362        let multi_buffer = editor.buffer().read(cx);
 363        let (_, buffer, _) = multi_buffer.excerpt_containing(position, cx)?;
 364
 365        let file = buffer.read(cx).file()?;
 366        Some(ProjectPath {
 367            worktree_id: file.worktree_id(cx),
 368            path: file.path().clone(),
 369        })
 370    }
 371
 372    fn move_to_beginning(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 373        self.editor.update(cx, |editor, cx| {
 374            editor.primary_editor().update(cx, |editor, cx| {
 375                editor.move_to_beginning(&Default::default(), window, cx);
 376            });
 377        });
 378    }
 379
 380    fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
 381        if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
 382            self.editor.update(cx, |editor, cx| {
 383                editor.primary_editor().update(cx, |editor, cx| {
 384                    editor.change_selections(
 385                        SelectionEffects::scroll(Autoscroll::focused()),
 386                        window,
 387                        cx,
 388                        |s| {
 389                            s.select_ranges([position..position]);
 390                        },
 391                    )
 392                })
 393            });
 394        } else {
 395            self.pending_scroll = Some(path_key);
 396        }
 397    }
 398
 399    fn button_states(&self, cx: &App) -> ButtonStates {
 400        let editor = self.editor.read(cx).primary_editor().read(cx);
 401        let snapshot = self.multibuffer.read(cx).snapshot(cx);
 402        let prev_next = snapshot.diff_hunks().nth(1).is_some();
 403        let mut selection = true;
 404
 405        let mut ranges = editor
 406            .selections
 407            .disjoint_anchor_ranges()
 408            .collect::<Vec<_>>();
 409        if !ranges.iter().any(|range| range.start != range.end) {
 410            selection = false;
 411            if let Some((excerpt_id, _, range)) = self
 412                .editor
 413                .read(cx)
 414                .primary_editor()
 415                .read(cx)
 416                .active_excerpt(cx)
 417            {
 418                ranges = vec![multi_buffer::Anchor::range_in_buffer(excerpt_id, range)];
 419            } else {
 420                ranges = Vec::default();
 421            }
 422        }
 423        let mut has_staged_hunks = false;
 424        let mut has_unstaged_hunks = false;
 425        for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
 426            match hunk.secondary_status {
 427                DiffHunkSecondaryStatus::HasSecondaryHunk
 428                | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending => {
 429                    has_unstaged_hunks = true;
 430                }
 431                DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
 432                    has_staged_hunks = true;
 433                    has_unstaged_hunks = true;
 434                }
 435                DiffHunkSecondaryStatus::NoSecondaryHunk
 436                | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending => {
 437                    has_staged_hunks = true;
 438                }
 439            }
 440        }
 441        let mut stage_all = false;
 442        let mut unstage_all = false;
 443        self.workspace
 444            .read_with(cx, |workspace, cx| {
 445                if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
 446                    let git_panel = git_panel.read(cx);
 447                    stage_all = git_panel.can_stage_all();
 448                    unstage_all = git_panel.can_unstage_all();
 449                }
 450            })
 451            .ok();
 452
 453        ButtonStates {
 454            stage: has_unstaged_hunks,
 455            unstage: has_staged_hunks,
 456            prev_next,
 457            selection,
 458            stage_all,
 459            unstage_all,
 460        }
 461    }
 462
 463    fn handle_editor_event(
 464        &mut self,
 465        editor: &Entity<SplittableEditor>,
 466        event: &EditorEvent,
 467        window: &mut Window,
 468        cx: &mut Context<Self>,
 469    ) {
 470        match event {
 471            EditorEvent::SelectionsChanged { local: true } => {
 472                let Some(project_path) = self.active_path(cx) else {
 473                    return;
 474                };
 475                self.workspace
 476                    .update(cx, |workspace, cx| {
 477                        if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
 478                            git_panel.update(cx, |git_panel, cx| {
 479                                git_panel.select_entry_by_path(project_path, window, cx)
 480                            })
 481                        }
 482                    })
 483                    .ok();
 484            }
 485            EditorEvent::Saved => {
 486                self._task = cx.spawn_in(window, async move |this, cx| {
 487                    Self::refresh(this, RefreshReason::EditorSaved, cx).await
 488                });
 489            }
 490            _ => {}
 491        }
 492        if editor.focus_handle(cx).contains_focused(window, cx)
 493            && self.multibuffer.read(cx).is_empty()
 494        {
 495            self.focus_handle.focus(window)
 496        }
 497    }
 498
 499    #[instrument(skip_all)]
 500    fn register_buffer(
 501        &mut self,
 502        path_key: PathKey,
 503        file_status: FileStatus,
 504        buffer: Entity<Buffer>,
 505        diff: Entity<BufferDiff>,
 506        window: &mut Window,
 507        cx: &mut Context<Self>,
 508    ) {
 509        let subscription = cx.subscribe_in(&diff, window, move |this, _, _, window, cx| {
 510            this._task = window.spawn(cx, {
 511                let this = cx.weak_entity();
 512                async |cx| Self::refresh(this, RefreshReason::DiffChanged, cx).await
 513            })
 514        });
 515        self.buffer_diff_subscriptions
 516            .insert(path_key.path.clone(), (diff.clone(), subscription));
 517
 518        // TODO(split-diff) we shouldn't have a conflict addon when split
 519        let conflict_addon = self
 520            .editor
 521            .read(cx)
 522            .primary_editor()
 523            .read(cx)
 524            .addon::<ConflictAddon>()
 525            .expect("project diff editor should have a conflict addon");
 526
 527        let snapshot = buffer.read(cx).snapshot();
 528        let diff_read = diff.read(cx);
 529
 530        let excerpt_ranges = {
 531            let diff_hunk_ranges = diff_read
 532                .hunks_intersecting_range(
 533                    Anchor::min_max_range_for_buffer(diff_read.buffer_id),
 534                    &snapshot,
 535                    cx,
 536                )
 537                .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot));
 538            let conflicts = conflict_addon
 539                .conflict_set(snapshot.remote_id())
 540                .map(|conflict_set| conflict_set.read(cx).snapshot().conflicts)
 541                .unwrap_or_default();
 542            let mut conflicts = conflicts
 543                .iter()
 544                .map(|conflict| conflict.range.to_point(&snapshot))
 545                .peekable();
 546
 547            if conflicts.peek().is_some() {
 548                conflicts.collect::<Vec<_>>()
 549            } else {
 550                diff_hunk_ranges.collect()
 551            }
 552        };
 553
 554        let (was_empty, is_excerpt_newly_added) = self.multibuffer.update(cx, |multibuffer, cx| {
 555            let was_empty = multibuffer.is_empty();
 556            let (_, is_newly_added) = multibuffer.set_excerpts_for_path(
 557                path_key.clone(),
 558                buffer,
 559                excerpt_ranges,
 560                multibuffer_context_lines(cx),
 561                cx,
 562            );
 563            if self.branch_diff.read(cx).diff_base().is_merge_base() {
 564                multibuffer.add_diff(diff.clone(), cx);
 565            }
 566            (was_empty, is_newly_added)
 567        });
 568
 569        self.editor.update(cx, |editor, cx| {
 570            editor.primary_editor().update(cx, |editor, cx| {
 571                if was_empty {
 572                    editor.change_selections(
 573                        SelectionEffects::no_scroll(),
 574                        window,
 575                        cx,
 576                        |selections| {
 577                            selections.select_ranges([
 578                                multi_buffer::Anchor::min()..multi_buffer::Anchor::min()
 579                            ])
 580                        },
 581                    );
 582                }
 583                if is_excerpt_newly_added
 584                    && (file_status.is_deleted()
 585                        || (file_status.is_untracked()
 586                            && GitPanelSettings::get_global(cx).collapse_untracked_diff))
 587                {
 588                    editor.fold_buffer(snapshot.text.remote_id(), cx)
 589                }
 590            })
 591        });
 592
 593        if self.multibuffer.read(cx).is_empty()
 594            && self
 595                .editor
 596                .read(cx)
 597                .focus_handle(cx)
 598                .contains_focused(window, cx)
 599        {
 600            self.focus_handle.focus(window);
 601        } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
 602            self.editor.update(cx, |editor, cx| {
 603                editor.focus_handle(cx).focus(window);
 604            });
 605        }
 606        if self.pending_scroll.as_ref() == Some(&path_key) {
 607            self.move_to_path(path_key, window, cx);
 608        }
 609    }
 610
 611    pub async fn refresh(
 612        this: WeakEntity<Self>,
 613        reason: RefreshReason,
 614        cx: &mut AsyncWindowContext,
 615    ) -> Result<()> {
 616        let mut path_keys = Vec::new();
 617        let buffers_to_load = this.update(cx, |this, cx| {
 618            let (repo, buffers_to_load) = this.branch_diff.update(cx, |branch_diff, cx| {
 619                let load_buffers = branch_diff.load_buffers(cx);
 620                (branch_diff.repo().cloned(), load_buffers)
 621            });
 622            let mut previous_paths = this
 623                .multibuffer
 624                .read(cx)
 625                .paths()
 626                .cloned()
 627                .collect::<HashSet<_>>();
 628
 629            if let Some(repo) = repo {
 630                let repo = repo.read(cx);
 631
 632                path_keys = Vec::with_capacity(buffers_to_load.len());
 633                for entry in buffers_to_load.iter() {
 634                    let sort_prefix = sort_prefix(&repo, &entry.repo_path, entry.file_status, cx);
 635                    let path_key =
 636                        PathKey::with_sort_prefix(sort_prefix, entry.repo_path.as_ref().clone());
 637                    previous_paths.remove(&path_key);
 638                    path_keys.push(path_key)
 639                }
 640            }
 641
 642            this.multibuffer.update(cx, |multibuffer, cx| {
 643                for path in previous_paths {
 644                    if let Some(buffer) = multibuffer.buffer_for_path(&path, cx) {
 645                        let skip = match reason {
 646                            RefreshReason::DiffChanged | RefreshReason::EditorSaved => {
 647                                buffer.read(cx).is_dirty()
 648                            }
 649                            RefreshReason::StatusesChanged => false,
 650                        };
 651                        if skip {
 652                            continue;
 653                        }
 654                    }
 655
 656                    this.buffer_diff_subscriptions.remove(&path.path);
 657                    multibuffer.remove_excerpts_for_path(path.clone(), cx);
 658                }
 659            });
 660            buffers_to_load
 661        })?;
 662
 663        for (entry, path_key) in buffers_to_load.into_iter().zip(path_keys.into_iter()) {
 664            if let Some((buffer, diff)) = entry.load.await.log_err() {
 665                // We might be lagging behind enough that all future entry.load futures are no longer pending.
 666                // If that is the case, this task will never yield, starving the foreground thread of execution time.
 667                yield_now().await;
 668                cx.update(|window, cx| {
 669                    this.update(cx, |this, cx| {
 670                        let multibuffer = this.multibuffer.read(cx);
 671                        let skip = multibuffer.buffer(buffer.read(cx).remote_id()).is_some()
 672                            && multibuffer
 673                                .diff_for(buffer.read(cx).remote_id())
 674                                .is_some_and(|prev_diff| prev_diff.entity_id() == diff.entity_id())
 675                            && match reason {
 676                                RefreshReason::DiffChanged | RefreshReason::EditorSaved => {
 677                                    buffer.read(cx).is_dirty()
 678                                }
 679                                RefreshReason::StatusesChanged => false,
 680                            };
 681                        if !skip {
 682                            this.register_buffer(
 683                                path_key,
 684                                entry.file_status,
 685                                buffer,
 686                                diff,
 687                                window,
 688                                cx,
 689                            )
 690                        }
 691                    })
 692                    .ok();
 693                })?;
 694            }
 695        }
 696        this.update(cx, |this, cx| {
 697            this.pending_scroll.take();
 698            cx.notify();
 699        })?;
 700
 701        Ok(())
 702    }
 703
 704    #[cfg(any(test, feature = "test-support"))]
 705    pub fn excerpt_paths(&self, cx: &App) -> Vec<std::sync::Arc<util::rel_path::RelPath>> {
 706        self.multibuffer
 707            .read(cx)
 708            .paths()
 709            .map(|key| key.path.clone())
 710            .collect()
 711    }
 712}
 713
 714fn sort_prefix(repo: &Repository, repo_path: &RepoPath, status: FileStatus, cx: &App) -> u64 {
 715    let settings = GitPanelSettings::get_global(cx);
 716
 717    // Tree view can only sort by path
 718    if settings.sort_by_path || settings.tree_view {
 719        TRACKED_SORT_PREFIX
 720    } else if repo.had_conflict_on_last_merge_head_change(repo_path) {
 721        CONFLICT_SORT_PREFIX
 722    } else if status.is_created() {
 723        NEW_SORT_PREFIX
 724    } else {
 725        TRACKED_SORT_PREFIX
 726    }
 727}
 728
 729impl EventEmitter<EditorEvent> for ProjectDiff {}
 730
 731impl Focusable for ProjectDiff {
 732    fn focus_handle(&self, cx: &App) -> FocusHandle {
 733        if self.multibuffer.read(cx).is_empty() {
 734            self.focus_handle.clone()
 735        } else {
 736            self.editor.focus_handle(cx)
 737        }
 738    }
 739}
 740
 741impl Item for ProjectDiff {
 742    type Event = EditorEvent;
 743
 744    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 745        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
 746    }
 747
 748    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 749        Editor::to_item_events(event, f)
 750    }
 751
 752    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 753        self.editor.update(cx, |editor, cx| {
 754            editor.primary_editor().update(cx, |primary_editor, cx| {
 755                primary_editor.deactivated(window, cx);
 756            })
 757        });
 758    }
 759
 760    fn navigate(
 761        &mut self,
 762        data: Box<dyn Any>,
 763        window: &mut Window,
 764        cx: &mut Context<Self>,
 765    ) -> bool {
 766        self.editor.update(cx, |editor, cx| {
 767            editor.primary_editor().update(cx, |primary_editor, cx| {
 768                primary_editor.navigate(data, window, cx)
 769            })
 770        })
 771    }
 772
 773    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 774        Some("Project Diff".into())
 775    }
 776
 777    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
 778        Label::new(self.tab_content_text(0, cx))
 779            .color(if params.selected {
 780                Color::Default
 781            } else {
 782                Color::Muted
 783            })
 784            .into_any_element()
 785    }
 786
 787    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
 788        match self.branch_diff.read(cx).diff_base() {
 789            DiffBase::Head => "Uncommitted Changes".into(),
 790            DiffBase::Merge { base_ref } => format!("Changes since {}", base_ref).into(),
 791        }
 792    }
 793
 794    fn telemetry_event_text(&self) -> Option<&'static str> {
 795        Some("Project Diff Opened")
 796    }
 797
 798    fn as_searchable(&self, _: &Entity<Self>, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
 799        // TODO(split-diff) SplitEditor should be searchable
 800        Some(Box::new(self.editor.read(cx).primary_editor().clone()))
 801    }
 802
 803    fn for_each_project_item(
 804        &self,
 805        cx: &App,
 806        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 807    ) {
 808        self.editor
 809            .read(cx)
 810            .primary_editor()
 811            .read(cx)
 812            .for_each_project_item(cx, f)
 813    }
 814
 815    fn set_nav_history(
 816        &mut self,
 817        nav_history: ItemNavHistory,
 818        _: &mut Window,
 819        cx: &mut Context<Self>,
 820    ) {
 821        self.editor.update(cx, |editor, cx| {
 822            editor.primary_editor().update(cx, |primary_editor, _| {
 823                primary_editor.set_nav_history(Some(nav_history));
 824            })
 825        });
 826    }
 827
 828    fn can_split(&self) -> bool {
 829        true
 830    }
 831
 832    fn clone_on_split(
 833        &self,
 834        _workspace_id: Option<workspace::WorkspaceId>,
 835        window: &mut Window,
 836        cx: &mut Context<Self>,
 837    ) -> Task<Option<Entity<Self>>>
 838    where
 839        Self: Sized,
 840    {
 841        let Some(workspace) = self.workspace.upgrade() else {
 842            return Task::ready(None);
 843        };
 844        Task::ready(Some(cx.new(|cx| {
 845            ProjectDiff::new(self.project.clone(), workspace, window, cx)
 846        })))
 847    }
 848
 849    fn is_dirty(&self, cx: &App) -> bool {
 850        self.multibuffer.read(cx).is_dirty(cx)
 851    }
 852
 853    fn has_conflict(&self, cx: &App) -> bool {
 854        self.multibuffer.read(cx).has_conflict(cx)
 855    }
 856
 857    fn can_save(&self, _: &App) -> bool {
 858        true
 859    }
 860
 861    fn save(
 862        &mut self,
 863        options: SaveOptions,
 864        project: Entity<Project>,
 865        window: &mut Window,
 866        cx: &mut Context<Self>,
 867    ) -> Task<Result<()>> {
 868        self.editor.update(cx, |editor, cx| {
 869            editor.primary_editor().update(cx, |primary_editor, cx| {
 870                primary_editor.save(options, project, window, cx)
 871            })
 872        })
 873    }
 874
 875    fn save_as(
 876        &mut self,
 877        _: Entity<Project>,
 878        _: ProjectPath,
 879        _window: &mut Window,
 880        _: &mut Context<Self>,
 881    ) -> Task<Result<()>> {
 882        unreachable!()
 883    }
 884
 885    fn reload(
 886        &mut self,
 887        project: Entity<Project>,
 888        window: &mut Window,
 889        cx: &mut Context<Self>,
 890    ) -> Task<Result<()>> {
 891        self.editor.update(cx, |editor, cx| {
 892            editor.primary_editor().update(cx, |primary_editor, cx| {
 893                primary_editor.reload(project, window, cx)
 894            })
 895        })
 896    }
 897
 898    fn act_as_type<'a>(
 899        &'a self,
 900        type_id: TypeId,
 901        self_handle: &'a Entity<Self>,
 902        cx: &'a App,
 903    ) -> Option<gpui::AnyEntity> {
 904        if type_id == TypeId::of::<Self>() {
 905            Some(self_handle.clone().into())
 906        } else if type_id == TypeId::of::<Editor>() {
 907            Some(self.editor.read(cx).primary_editor().clone().into())
 908        } else {
 909            None
 910        }
 911    }
 912
 913    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 914        ToolbarItemLocation::PrimaryLeft
 915    }
 916
 917    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 918        self.editor
 919            .read(cx)
 920            .last_selected_editor()
 921            .read(cx)
 922            .breadcrumbs(theme, cx)
 923    }
 924
 925    fn added_to_workspace(
 926        &mut self,
 927        workspace: &mut Workspace,
 928        window: &mut Window,
 929        cx: &mut Context<Self>,
 930    ) {
 931        self.editor.update(cx, |editor, cx| {
 932            editor.added_to_workspace(workspace, window, cx)
 933        });
 934    }
 935}
 936
 937impl Render for ProjectDiff {
 938    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 939        let is_empty = self.multibuffer.read(cx).is_empty();
 940
 941        div()
 942            .track_focus(&self.focus_handle)
 943            .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
 944            .bg(cx.theme().colors().editor_background)
 945            .flex()
 946            .items_center()
 947            .justify_center()
 948            .size_full()
 949            .when(is_empty, |el| {
 950                let remote_button = if let Some(panel) = self
 951                    .workspace
 952                    .upgrade()
 953                    .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
 954                {
 955                    panel.update(cx, |panel, cx| panel.render_remote_button(cx))
 956                } else {
 957                    None
 958                };
 959                let keybinding_focus_handle = self.focus_handle(cx);
 960                el.child(
 961                    v_flex()
 962                        .gap_1()
 963                        .child(
 964                            h_flex()
 965                                .justify_around()
 966                                .child(Label::new("No uncommitted changes")),
 967                        )
 968                        .map(|el| match remote_button {
 969                            Some(button) => el.child(h_flex().justify_around().child(button)),
 970                            None => el.child(
 971                                h_flex()
 972                                    .justify_around()
 973                                    .child(Label::new("Remote up to date")),
 974                            ),
 975                        })
 976                        .child(
 977                            h_flex().justify_around().mt_1().child(
 978                                Button::new("project-diff-close-button", "Close")
 979                                    // .style(ButtonStyle::Transparent)
 980                                    .key_binding(KeyBinding::for_action_in(
 981                                        &CloseActiveItem::default(),
 982                                        &keybinding_focus_handle,
 983                                        cx,
 984                                    ))
 985                                    .on_click(move |_, window, cx| {
 986                                        window.focus(&keybinding_focus_handle);
 987                                        window.dispatch_action(
 988                                            Box::new(CloseActiveItem::default()),
 989                                            cx,
 990                                        );
 991                                    }),
 992                            ),
 993                        ),
 994                )
 995            })
 996            .when(!is_empty, |el| el.child(self.editor.clone()))
 997    }
 998}
 999
1000impl SerializableItem for ProjectDiff {
1001    fn serialized_item_kind() -> &'static str {
1002        "ProjectDiff"
1003    }
1004
1005    fn cleanup(
1006        _: workspace::WorkspaceId,
1007        _: Vec<workspace::ItemId>,
1008        _: &mut Window,
1009        _: &mut App,
1010    ) -> Task<Result<()>> {
1011        Task::ready(Ok(()))
1012    }
1013
1014    fn deserialize(
1015        project: Entity<Project>,
1016        workspace: WeakEntity<Workspace>,
1017        workspace_id: workspace::WorkspaceId,
1018        item_id: workspace::ItemId,
1019        window: &mut Window,
1020        cx: &mut App,
1021    ) -> Task<Result<Entity<Self>>> {
1022        window.spawn(cx, async move |cx| {
1023            let diff_base = persistence::PROJECT_DIFF_DB.get_diff_base(item_id, workspace_id)?;
1024
1025            let diff = cx.update(|window, cx| {
1026                let branch_diff = cx
1027                    .new(|cx| branch_diff::BranchDiff::new(diff_base, project.clone(), window, cx));
1028                let workspace = workspace.upgrade().context("workspace gone")?;
1029                anyhow::Ok(
1030                    cx.new(|cx| ProjectDiff::new_impl(branch_diff, project, workspace, window, cx)),
1031                )
1032            })??;
1033
1034            Ok(diff)
1035        })
1036    }
1037
1038    fn serialize(
1039        &mut self,
1040        workspace: &mut Workspace,
1041        item_id: workspace::ItemId,
1042        _closing: bool,
1043        _window: &mut Window,
1044        cx: &mut Context<Self>,
1045    ) -> Option<Task<Result<()>>> {
1046        let workspace_id = workspace.database_id()?;
1047        let diff_base = self.diff_base(cx).clone();
1048
1049        Some(cx.background_spawn({
1050            async move {
1051                persistence::PROJECT_DIFF_DB
1052                    .save_diff_base(item_id, workspace_id, diff_base.clone())
1053                    .await
1054            }
1055        }))
1056    }
1057
1058    fn should_serialize(&self, _: &Self::Event) -> bool {
1059        false
1060    }
1061}
1062
1063mod persistence {
1064
1065    use anyhow::Context as _;
1066    use db::{
1067        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
1068        sqlez_macros::sql,
1069    };
1070    use project::git_store::branch_diff::DiffBase;
1071    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
1072
1073    pub struct ProjectDiffDb(ThreadSafeConnection);
1074
1075    impl Domain for ProjectDiffDb {
1076        const NAME: &str = stringify!(ProjectDiffDb);
1077
1078        const MIGRATIONS: &[&str] = &[sql!(
1079                CREATE TABLE project_diffs(
1080                    workspace_id INTEGER,
1081                    item_id INTEGER UNIQUE,
1082
1083                    diff_base TEXT,
1084
1085                    PRIMARY KEY(workspace_id, item_id),
1086                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
1087                    ON DELETE CASCADE
1088                ) STRICT;
1089        )];
1090    }
1091
1092    db::static_connection!(PROJECT_DIFF_DB, ProjectDiffDb, [WorkspaceDb]);
1093
1094    impl ProjectDiffDb {
1095        pub async fn save_diff_base(
1096            &self,
1097            item_id: ItemId,
1098            workspace_id: WorkspaceId,
1099            diff_base: DiffBase,
1100        ) -> anyhow::Result<()> {
1101            self.write(move |connection| {
1102                let sql_stmt = sql!(
1103                    INSERT OR REPLACE INTO project_diffs(item_id, workspace_id, diff_base) VALUES (?, ?, ?)
1104                );
1105                let diff_base_str = serde_json::to_string(&diff_base)?;
1106                let mut query = connection.exec_bound::<(ItemId, WorkspaceId, String)>(sql_stmt)?;
1107                query((item_id, workspace_id, diff_base_str)).context(format!(
1108                    "exec_bound failed to execute or parse for: {}",
1109                    sql_stmt
1110                ))
1111            })
1112            .await
1113        }
1114
1115        pub fn get_diff_base(
1116            &self,
1117            item_id: ItemId,
1118            workspace_id: WorkspaceId,
1119        ) -> anyhow::Result<DiffBase> {
1120            let sql_stmt =
1121                sql!(SELECT diff_base FROM project_diffs WHERE item_id =  ?AND workspace_id =  ?);
1122            let diff_base_str = self.select_row_bound::<(ItemId, WorkspaceId), String>(sql_stmt)?(
1123                (item_id, workspace_id),
1124            )
1125            .context(::std::format!(
1126                "Error in get_diff_base, select_row_bound failed to execute or parse for: {}",
1127                sql_stmt
1128            ))?;
1129            let Some(diff_base_str) = diff_base_str else {
1130                return Ok(DiffBase::Head);
1131            };
1132            serde_json::from_str(&diff_base_str).context("deserializing diff base")
1133        }
1134    }
1135}
1136
1137pub struct ProjectDiffToolbar {
1138    project_diff: Option<WeakEntity<ProjectDiff>>,
1139    workspace: WeakEntity<Workspace>,
1140}
1141
1142impl ProjectDiffToolbar {
1143    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
1144        Self {
1145            project_diff: None,
1146            workspace: workspace.weak_handle(),
1147        }
1148    }
1149
1150    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
1151        self.project_diff.as_ref()?.upgrade()
1152    }
1153
1154    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
1155        if let Some(project_diff) = self.project_diff(cx) {
1156            project_diff.focus_handle(cx).focus(window);
1157        }
1158        let action = action.boxed_clone();
1159        cx.defer(move |cx| {
1160            cx.dispatch_action(action.as_ref());
1161        })
1162    }
1163
1164    fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1165        self.workspace
1166            .update(cx, |workspace, cx| {
1167                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
1168                    panel.update(cx, |panel, cx| {
1169                        panel.stage_all(&Default::default(), window, cx);
1170                    });
1171                }
1172            })
1173            .ok();
1174    }
1175
1176    fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1177        self.workspace
1178            .update(cx, |workspace, cx| {
1179                let Some(panel) = workspace.panel::<GitPanel>(cx) else {
1180                    return;
1181                };
1182                panel.update(cx, |panel, cx| {
1183                    panel.unstage_all(&Default::default(), window, cx);
1184                });
1185            })
1186            .ok();
1187    }
1188}
1189
1190impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
1191
1192impl ToolbarItemView for ProjectDiffToolbar {
1193    fn set_active_pane_item(
1194        &mut self,
1195        active_pane_item: Option<&dyn ItemHandle>,
1196        _: &mut Window,
1197        cx: &mut Context<Self>,
1198    ) -> ToolbarItemLocation {
1199        self.project_diff = active_pane_item
1200            .and_then(|item| item.act_as::<ProjectDiff>(cx))
1201            .filter(|item| item.read(cx).diff_base(cx) == &DiffBase::Head)
1202            .map(|entity| entity.downgrade());
1203        if self.project_diff.is_some() {
1204            ToolbarItemLocation::PrimaryRight
1205        } else {
1206            ToolbarItemLocation::Hidden
1207        }
1208    }
1209
1210    fn pane_focus_update(
1211        &mut self,
1212        _pane_focused: bool,
1213        _window: &mut Window,
1214        _cx: &mut Context<Self>,
1215    ) {
1216    }
1217}
1218
1219struct ButtonStates {
1220    stage: bool,
1221    unstage: bool,
1222    prev_next: bool,
1223    selection: bool,
1224    stage_all: bool,
1225    unstage_all: bool,
1226}
1227
1228impl Render for ProjectDiffToolbar {
1229    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1230        let Some(project_diff) = self.project_diff(cx) else {
1231            return div();
1232        };
1233        let focus_handle = project_diff.focus_handle(cx);
1234        let button_states = project_diff.read(cx).button_states(cx);
1235
1236        h_group_xl()
1237            .my_neg_1()
1238            .py_1()
1239            .items_center()
1240            .flex_wrap()
1241            .justify_between()
1242            .child(
1243                h_group_sm()
1244                    .when(button_states.selection, |el| {
1245                        el.child(
1246                            Button::new("stage", "Toggle Staged")
1247                                .tooltip(Tooltip::for_action_title_in(
1248                                    "Toggle Staged",
1249                                    &ToggleStaged,
1250                                    &focus_handle,
1251                                ))
1252                                .disabled(!button_states.stage && !button_states.unstage)
1253                                .on_click(cx.listener(|this, _, window, cx| {
1254                                    this.dispatch_action(&ToggleStaged, window, cx)
1255                                })),
1256                        )
1257                    })
1258                    .when(!button_states.selection, |el| {
1259                        el.child(
1260                            Button::new("stage", "Stage")
1261                                .tooltip(Tooltip::for_action_title_in(
1262                                    "Stage and go to next hunk",
1263                                    &StageAndNext,
1264                                    &focus_handle,
1265                                ))
1266                                .disabled(
1267                                    !button_states.prev_next
1268                                        && !button_states.stage_all
1269                                        && !button_states.unstage_all,
1270                                )
1271                                .on_click(cx.listener(|this, _, window, cx| {
1272                                    this.dispatch_action(&StageAndNext, window, cx)
1273                                })),
1274                        )
1275                        .child(
1276                            Button::new("unstage", "Unstage")
1277                                .tooltip(Tooltip::for_action_title_in(
1278                                    "Unstage and go to next hunk",
1279                                    &UnstageAndNext,
1280                                    &focus_handle,
1281                                ))
1282                                .disabled(
1283                                    !button_states.prev_next
1284                                        && !button_states.stage_all
1285                                        && !button_states.unstage_all,
1286                                )
1287                                .on_click(cx.listener(|this, _, window, cx| {
1288                                    this.dispatch_action(&UnstageAndNext, window, cx)
1289                                })),
1290                        )
1291                    }),
1292            )
1293            // n.b. the only reason these arrows are here is because we don't
1294            // support "undo" for staging so we need a way to go back.
1295            .child(
1296                h_group_sm()
1297                    .child(
1298                        IconButton::new("up", IconName::ArrowUp)
1299                            .shape(ui::IconButtonShape::Square)
1300                            .tooltip(Tooltip::for_action_title_in(
1301                                "Go to previous hunk",
1302                                &GoToPreviousHunk,
1303                                &focus_handle,
1304                            ))
1305                            .disabled(!button_states.prev_next)
1306                            .on_click(cx.listener(|this, _, window, cx| {
1307                                this.dispatch_action(&GoToPreviousHunk, window, cx)
1308                            })),
1309                    )
1310                    .child(
1311                        IconButton::new("down", IconName::ArrowDown)
1312                            .shape(ui::IconButtonShape::Square)
1313                            .tooltip(Tooltip::for_action_title_in(
1314                                "Go to next hunk",
1315                                &GoToHunk,
1316                                &focus_handle,
1317                            ))
1318                            .disabled(!button_states.prev_next)
1319                            .on_click(cx.listener(|this, _, window, cx| {
1320                                this.dispatch_action(&GoToHunk, window, cx)
1321                            })),
1322                    ),
1323            )
1324            .child(vertical_divider())
1325            .child(
1326                h_group_sm()
1327                    .when(
1328                        button_states.unstage_all && !button_states.stage_all,
1329                        |el| {
1330                            el.child(
1331                                Button::new("unstage-all", "Unstage All")
1332                                    .tooltip(Tooltip::for_action_title_in(
1333                                        "Unstage all changes",
1334                                        &UnstageAll,
1335                                        &focus_handle,
1336                                    ))
1337                                    .on_click(cx.listener(|this, _, window, cx| {
1338                                        this.unstage_all(window, cx)
1339                                    })),
1340                            )
1341                        },
1342                    )
1343                    .when(
1344                        !button_states.unstage_all || button_states.stage_all,
1345                        |el| {
1346                            el.child(
1347                                // todo make it so that changing to say "Unstaged"
1348                                // doesn't change the position.
1349                                div().child(
1350                                    Button::new("stage-all", "Stage All")
1351                                        .disabled(!button_states.stage_all)
1352                                        .tooltip(Tooltip::for_action_title_in(
1353                                            "Stage all changes",
1354                                            &StageAll,
1355                                            &focus_handle,
1356                                        ))
1357                                        .on_click(cx.listener(|this, _, window, cx| {
1358                                            this.stage_all(window, cx)
1359                                        })),
1360                                ),
1361                            )
1362                        },
1363                    )
1364                    .child(
1365                        Button::new("commit", "Commit")
1366                            .tooltip(Tooltip::for_action_title_in(
1367                                "Commit",
1368                                &Commit,
1369                                &focus_handle,
1370                            ))
1371                            .on_click(cx.listener(|this, _, window, cx| {
1372                                this.dispatch_action(&Commit, window, cx);
1373                            })),
1374                    ),
1375            )
1376    }
1377}
1378
1379#[derive(IntoElement, RegisterComponent)]
1380pub struct ProjectDiffEmptyState {
1381    pub no_repo: bool,
1382    pub can_push_and_pull: bool,
1383    pub focus_handle: Option<FocusHandle>,
1384    pub current_branch: Option<Branch>,
1385    // has_pending_commits: bool,
1386    // ahead_of_remote: bool,
1387    // no_git_repository: bool,
1388}
1389
1390impl RenderOnce for ProjectDiffEmptyState {
1391    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1392        let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1393            matches!(self.current_branch, Some(Branch {
1394                    upstream:
1395                        Some(Upstream {
1396                            tracking:
1397                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1398                                    ahead, behind, ..
1399                                }),
1400                            ..
1401                        }),
1402                    ..
1403                }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1404        };
1405
1406        let change_count = |current_branch: &Branch| -> (usize, usize) {
1407            match current_branch {
1408                Branch {
1409                    upstream:
1410                        Some(Upstream {
1411                            tracking:
1412                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1413                                    ahead, behind, ..
1414                                }),
1415                            ..
1416                        }),
1417                    ..
1418                } => (*ahead as usize, *behind as usize),
1419                _ => (0, 0),
1420            }
1421        };
1422
1423        let not_ahead_or_behind = status_against_remote(0, 0);
1424        let ahead_of_remote = status_against_remote(1, 0);
1425        let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1426            branch.upstream.is_none()
1427        } else {
1428            false
1429        };
1430
1431        let has_branch_container = |branch: &Branch| {
1432            h_flex()
1433                .max_w(px(420.))
1434                .bg(cx.theme().colors().text.opacity(0.05))
1435                .border_1()
1436                .border_color(cx.theme().colors().border)
1437                .rounded_sm()
1438                .gap_8()
1439                .px_6()
1440                .py_4()
1441                .map(|this| {
1442                    if ahead_of_remote {
1443                        let ahead_count = change_count(branch).0;
1444                        let ahead_string = format!("{} Commits Ahead", ahead_count);
1445                        this.child(
1446                            v_flex()
1447                                .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1448                                .child(
1449                                    Label::new(format!("Push your changes to {}", branch.name()))
1450                                        .color(Color::Muted),
1451                                ),
1452                        )
1453                        .child(div().child(render_push_button(
1454                            self.focus_handle,
1455                            "push".into(),
1456                            ahead_count as u32,
1457                        )))
1458                    } else if branch_not_on_remote {
1459                        this.child(
1460                            v_flex()
1461                                .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1462                                .child(
1463                                    Label::new(format!("Create {} on remote", branch.name()))
1464                                        .color(Color::Muted),
1465                                ),
1466                        )
1467                        .child(
1468                            div().child(render_publish_button(self.focus_handle, "publish".into())),
1469                        )
1470                    } else {
1471                        this.child(Label::new("Remote status unknown").color(Color::Muted))
1472                    }
1473                })
1474        };
1475
1476        v_flex().size_full().items_center().justify_center().child(
1477            v_flex()
1478                .gap_1()
1479                .when(self.no_repo, |this| {
1480                    // TODO: add git init
1481                    this.text_center()
1482                        .child(Label::new("No Repository").color(Color::Muted))
1483                })
1484                .map(|this| {
1485                    if not_ahead_or_behind && self.current_branch.is_some() {
1486                        this.text_center()
1487                            .child(Label::new("No Changes").color(Color::Muted))
1488                    } else {
1489                        this.when_some(self.current_branch.as_ref(), |this, branch| {
1490                            this.child(has_branch_container(branch))
1491                        })
1492                    }
1493                }),
1494        )
1495    }
1496}
1497
1498mod preview {
1499    use git::repository::{
1500        Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1501    };
1502    use ui::prelude::*;
1503
1504    use super::ProjectDiffEmptyState;
1505
1506    // View this component preview using `workspace: open component-preview`
1507    impl Component for ProjectDiffEmptyState {
1508        fn scope() -> ComponentScope {
1509            ComponentScope::VersionControl
1510        }
1511
1512        fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1513            let unknown_upstream: Option<UpstreamTracking> = None;
1514            let ahead_of_upstream: Option<UpstreamTracking> = Some(
1515                UpstreamTrackingStatus {
1516                    ahead: 2,
1517                    behind: 0,
1518                }
1519                .into(),
1520            );
1521
1522            let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1523                UpstreamTrackingStatus {
1524                    ahead: 0,
1525                    behind: 0,
1526                }
1527                .into(),
1528            );
1529
1530            fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1531                Branch {
1532                    is_head: true,
1533                    ref_name: "some-branch".into(),
1534                    upstream: upstream.map(|tracking| Upstream {
1535                        ref_name: "origin/some-branch".into(),
1536                        tracking,
1537                    }),
1538                    most_recent_commit: Some(CommitSummary {
1539                        sha: "abc123".into(),
1540                        subject: "Modify stuff".into(),
1541                        commit_timestamp: 1710932954,
1542                        author_name: "John Doe".into(),
1543                        has_parent: true,
1544                    }),
1545                }
1546            }
1547
1548            let no_repo_state = ProjectDiffEmptyState {
1549                no_repo: true,
1550                can_push_and_pull: false,
1551                focus_handle: None,
1552                current_branch: None,
1553            };
1554
1555            let no_changes_state = ProjectDiffEmptyState {
1556                no_repo: false,
1557                can_push_and_pull: true,
1558                focus_handle: None,
1559                current_branch: Some(branch(not_ahead_or_behind_upstream)),
1560            };
1561
1562            let ahead_of_upstream_state = ProjectDiffEmptyState {
1563                no_repo: false,
1564                can_push_and_pull: true,
1565                focus_handle: None,
1566                current_branch: Some(branch(ahead_of_upstream)),
1567            };
1568
1569            let unknown_upstream_state = ProjectDiffEmptyState {
1570                no_repo: false,
1571                can_push_and_pull: true,
1572                focus_handle: None,
1573                current_branch: Some(branch(unknown_upstream)),
1574            };
1575
1576            let (width, height) = (px(480.), px(320.));
1577
1578            Some(
1579                v_flex()
1580                    .gap_6()
1581                    .children(vec![
1582                        example_group(vec![
1583                            single_example(
1584                                "No Repo",
1585                                div()
1586                                    .w(width)
1587                                    .h(height)
1588                                    .child(no_repo_state)
1589                                    .into_any_element(),
1590                            ),
1591                            single_example(
1592                                "No Changes",
1593                                div()
1594                                    .w(width)
1595                                    .h(height)
1596                                    .child(no_changes_state)
1597                                    .into_any_element(),
1598                            ),
1599                            single_example(
1600                                "Unknown Upstream",
1601                                div()
1602                                    .w(width)
1603                                    .h(height)
1604                                    .child(unknown_upstream_state)
1605                                    .into_any_element(),
1606                            ),
1607                            single_example(
1608                                "Ahead of Remote",
1609                                div()
1610                                    .w(width)
1611                                    .h(height)
1612                                    .child(ahead_of_upstream_state)
1613                                    .into_any_element(),
1614                            ),
1615                        ])
1616                        .vertical(),
1617                    ])
1618                    .into_any_element(),
1619            )
1620        }
1621    }
1622}
1623
1624struct BranchDiffAddon {
1625    branch_diff: Entity<branch_diff::BranchDiff>,
1626}
1627
1628impl Addon for BranchDiffAddon {
1629    fn to_any(&self) -> &dyn std::any::Any {
1630        self
1631    }
1632
1633    fn override_status_for_buffer_id(
1634        &self,
1635        buffer_id: language::BufferId,
1636        cx: &App,
1637    ) -> Option<FileStatus> {
1638        self.branch_diff
1639            .read(cx)
1640            .status_for_buffer_id(buffer_id, cx)
1641    }
1642}
1643
1644#[cfg(test)]
1645mod tests {
1646    use collections::HashMap;
1647    use db::indoc;
1648    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1649    use git::status::{TrackedStatus, UnmergedStatus, UnmergedStatusCode};
1650    use gpui::TestAppContext;
1651    use project::FakeFs;
1652    use serde_json::json;
1653    use settings::SettingsStore;
1654    use std::path::Path;
1655    use unindent::Unindent as _;
1656    use util::{
1657        path,
1658        rel_path::{RelPath, rel_path},
1659    };
1660
1661    use super::*;
1662
1663    #[ctor::ctor]
1664    fn init_logger() {
1665        zlog::init_test();
1666    }
1667
1668    fn init_test(cx: &mut TestAppContext) {
1669        cx.update(|cx| {
1670            let store = SettingsStore::test(cx);
1671            cx.set_global(store);
1672            theme::init(theme::LoadThemes::JustBase, cx);
1673            editor::init(cx);
1674            crate::init(cx);
1675        });
1676    }
1677
1678    #[gpui::test]
1679    async fn test_save_after_restore(cx: &mut TestAppContext) {
1680        init_test(cx);
1681
1682        let fs = FakeFs::new(cx.executor());
1683        fs.insert_tree(
1684            path!("/project"),
1685            json!({
1686                ".git": {},
1687                "foo.txt": "FOO\n",
1688            }),
1689        )
1690        .await;
1691        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1692        let (workspace, cx) =
1693            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1694        let diff = cx.new_window_entity(|window, cx| {
1695            ProjectDiff::new(project.clone(), workspace, window, cx)
1696        });
1697        cx.run_until_parked();
1698
1699        fs.set_head_for_repo(
1700            path!("/project/.git").as_ref(),
1701            &[("foo.txt", "foo\n".into())],
1702            "deadbeef",
1703        );
1704        fs.set_index_for_repo(
1705            path!("/project/.git").as_ref(),
1706            &[("foo.txt", "foo\n".into())],
1707        );
1708        cx.run_until_parked();
1709
1710        let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
1711        assert_state_with_diff(
1712            &editor,
1713            cx,
1714            &"
1715                - foo
1716                + ˇFOO
1717            "
1718            .unindent(),
1719        );
1720
1721        editor
1722            .update_in(cx, |editor, window, cx| {
1723                editor.git_restore(&Default::default(), window, cx);
1724                editor.save(SaveOptions::default(), project.clone(), window, cx)
1725            })
1726            .await
1727            .unwrap();
1728        cx.run_until_parked();
1729
1730        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1731
1732        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1733        assert_eq!(text, "foo\n");
1734    }
1735
1736    #[gpui::test]
1737    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1738        init_test(cx);
1739
1740        let fs = FakeFs::new(cx.executor());
1741        fs.insert_tree(
1742            path!("/project"),
1743            json!({
1744                ".git": {},
1745                "bar": "BAR\n",
1746                "foo": "FOO\n",
1747            }),
1748        )
1749        .await;
1750        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1751        let (workspace, cx) =
1752            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1753        let diff = cx.new_window_entity(|window, cx| {
1754            ProjectDiff::new(project.clone(), workspace, window, cx)
1755        });
1756        cx.run_until_parked();
1757
1758        fs.set_head_and_index_for_repo(
1759            path!("/project/.git").as_ref(),
1760            &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1761        );
1762        cx.run_until_parked();
1763
1764        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1765            diff.move_to_path(
1766                PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("foo").into_arc()),
1767                window,
1768                cx,
1769            );
1770            diff.editor.read(cx).primary_editor().clone()
1771        });
1772        assert_state_with_diff(
1773            &editor,
1774            cx,
1775            &"
1776                - bar
1777                + BAR
1778
1779                - ˇfoo
1780                + FOO
1781            "
1782            .unindent(),
1783        );
1784
1785        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1786            diff.move_to_path(
1787                PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("bar").into_arc()),
1788                window,
1789                cx,
1790            );
1791            diff.editor.read(cx).primary_editor().clone()
1792        });
1793        assert_state_with_diff(
1794            &editor,
1795            cx,
1796            &"
1797                - ˇbar
1798                + BAR
1799
1800                - foo
1801                + FOO
1802            "
1803            .unindent(),
1804        );
1805    }
1806
1807    #[gpui::test]
1808    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1809        init_test(cx);
1810
1811        let fs = FakeFs::new(cx.executor());
1812        fs.insert_tree(
1813            path!("/project"),
1814            json!({
1815                ".git": {},
1816                "foo": "modified\n",
1817            }),
1818        )
1819        .await;
1820        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1821        let (workspace, cx) =
1822            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1823        let buffer = project
1824            .update(cx, |project, cx| {
1825                project.open_local_buffer(path!("/project/foo"), cx)
1826            })
1827            .await
1828            .unwrap();
1829        let buffer_editor = cx.new_window_entity(|window, cx| {
1830            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1831        });
1832        let diff = cx.new_window_entity(|window, cx| {
1833            ProjectDiff::new(project.clone(), workspace, window, cx)
1834        });
1835        cx.run_until_parked();
1836
1837        fs.set_head_for_repo(
1838            path!("/project/.git").as_ref(),
1839            &[("foo", "original\n".into())],
1840            "deadbeef",
1841        );
1842        cx.run_until_parked();
1843
1844        let diff_editor =
1845            diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
1846
1847        assert_state_with_diff(
1848            &diff_editor,
1849            cx,
1850            &"
1851                - original
1852                + ˇmodified
1853            "
1854            .unindent(),
1855        );
1856
1857        let prev_buffer_hunks =
1858            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1859                let snapshot = buffer_editor.snapshot(window, cx);
1860                let snapshot = &snapshot.buffer_snapshot();
1861                let prev_buffer_hunks = buffer_editor
1862                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1863                    .collect::<Vec<_>>();
1864                buffer_editor.git_restore(&Default::default(), window, cx);
1865                prev_buffer_hunks
1866            });
1867        assert_eq!(prev_buffer_hunks.len(), 1);
1868        cx.run_until_parked();
1869
1870        let new_buffer_hunks =
1871            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1872                let snapshot = buffer_editor.snapshot(window, cx);
1873                let snapshot = &snapshot.buffer_snapshot();
1874                buffer_editor
1875                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1876                    .collect::<Vec<_>>()
1877            });
1878        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1879
1880        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1881            buffer_editor.set_text("different\n", window, cx);
1882            buffer_editor.save(
1883                SaveOptions {
1884                    format: false,
1885                    autosave: false,
1886                },
1887                project.clone(),
1888                window,
1889                cx,
1890            )
1891        })
1892        .await
1893        .unwrap();
1894
1895        cx.run_until_parked();
1896
1897        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1898            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1899        });
1900
1901        assert_state_with_diff(
1902            &buffer_editor,
1903            cx,
1904            &"
1905                - original
1906                + different
1907                  ˇ"
1908            .unindent(),
1909        );
1910
1911        assert_state_with_diff(
1912            &diff_editor,
1913            cx,
1914            &"
1915                - original
1916                + different
1917                  ˇ"
1918            .unindent(),
1919        );
1920    }
1921
1922    use crate::{
1923        conflict_view::resolve_conflict,
1924        project_diff::{self, ProjectDiff},
1925    };
1926
1927    #[gpui::test]
1928    async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1929        init_test(cx);
1930
1931        let fs = FakeFs::new(cx.executor());
1932        fs.insert_tree(
1933            path!("/a"),
1934            json!({
1935                ".git": {},
1936                "a.txt": "created\n",
1937                "b.txt": "really changed\n",
1938                "c.txt": "unchanged\n"
1939            }),
1940        )
1941        .await;
1942
1943        fs.set_head_and_index_for_repo(
1944            Path::new(path!("/a/.git")),
1945            &[
1946                ("b.txt", "before\n".to_string()),
1947                ("c.txt", "unchanged\n".to_string()),
1948                ("d.txt", "deleted\n".to_string()),
1949            ],
1950        );
1951
1952        let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1953        let (workspace, cx) =
1954            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1955
1956        cx.run_until_parked();
1957
1958        cx.focus(&workspace);
1959        cx.update(|window, cx| {
1960            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1961        });
1962
1963        cx.run_until_parked();
1964
1965        let item = workspace.update(cx, |workspace, cx| {
1966            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1967        });
1968        cx.focus(&item);
1969        let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
1970
1971        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1972
1973        cx.assert_excerpts_with_selections(indoc!(
1974            "
1975            [EXCERPT]
1976            before
1977            really changed
1978            [EXCERPT]
1979            [FOLDED]
1980            [EXCERPT]
1981            ˇcreated
1982        "
1983        ));
1984
1985        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1986
1987        cx.assert_excerpts_with_selections(indoc!(
1988            "
1989            [EXCERPT]
1990            before
1991            really changed
1992            [EXCERPT]
1993            ˇ[FOLDED]
1994            [EXCERPT]
1995            created
1996        "
1997        ));
1998
1999        cx.dispatch_action(editor::actions::GoToPreviousHunk);
2000
2001        cx.assert_excerpts_with_selections(indoc!(
2002            "
2003            [EXCERPT]
2004            ˇbefore
2005            really changed
2006            [EXCERPT]
2007            [FOLDED]
2008            [EXCERPT]
2009            created
2010        "
2011        ));
2012    }
2013
2014    #[gpui::test]
2015    async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
2016        init_test(cx);
2017
2018        let git_contents = indoc! {r#"
2019            #[rustfmt::skip]
2020            fn main() {
2021                let x = 0.0; // this line will be removed
2022                // 1
2023                // 2
2024                // 3
2025                let y = 0.0; // this line will be removed
2026                // 1
2027                // 2
2028                // 3
2029                let arr = [
2030                    0.0, // this line will be removed
2031                    0.0, // this line will be removed
2032                    0.0, // this line will be removed
2033                    0.0, // this line will be removed
2034                ];
2035            }
2036        "#};
2037        let buffer_contents = indoc! {"
2038            #[rustfmt::skip]
2039            fn main() {
2040                // 1
2041                // 2
2042                // 3
2043                // 1
2044                // 2
2045                // 3
2046                let arr = [
2047                ];
2048            }
2049        "};
2050
2051        let fs = FakeFs::new(cx.executor());
2052        fs.insert_tree(
2053            path!("/a"),
2054            json!({
2055                ".git": {},
2056                "main.rs": buffer_contents,
2057            }),
2058        )
2059        .await;
2060
2061        fs.set_head_and_index_for_repo(
2062            Path::new(path!("/a/.git")),
2063            &[("main.rs", git_contents.to_owned())],
2064        );
2065
2066        let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2067        let (workspace, cx) =
2068            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2069
2070        cx.run_until_parked();
2071
2072        cx.focus(&workspace);
2073        cx.update(|window, cx| {
2074            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2075        });
2076
2077        cx.run_until_parked();
2078
2079        let item = workspace.update(cx, |workspace, cx| {
2080            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2081        });
2082        cx.focus(&item);
2083        let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2084
2085        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2086
2087        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2088
2089        cx.dispatch_action(editor::actions::GoToHunk);
2090        cx.dispatch_action(editor::actions::GoToHunk);
2091        cx.dispatch_action(git::Restore);
2092        cx.dispatch_action(editor::actions::MoveToBeginning);
2093
2094        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2095    }
2096
2097    #[gpui::test]
2098    async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
2099        init_test(cx);
2100
2101        let fs = FakeFs::new(cx.executor());
2102        fs.insert_tree(
2103            path!("/project"),
2104            json!({
2105                ".git": {},
2106                "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
2107            }),
2108        )
2109        .await;
2110        fs.set_status_for_repo(
2111            Path::new(path!("/project/.git")),
2112            &[(
2113                "foo",
2114                UnmergedStatus {
2115                    first_head: UnmergedStatusCode::Updated,
2116                    second_head: UnmergedStatusCode::Updated,
2117                }
2118                .into(),
2119            )],
2120        );
2121        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2122        let (workspace, cx) =
2123            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2124        let diff = cx.new_window_entity(|window, cx| {
2125            ProjectDiff::new(project.clone(), workspace, window, cx)
2126        });
2127        cx.run_until_parked();
2128
2129        cx.update(|window, cx| {
2130            let editor = diff.read(cx).editor.read(cx).primary_editor().clone();
2131            let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
2132            assert_eq!(excerpt_ids.len(), 1);
2133            let excerpt_id = excerpt_ids[0];
2134            let buffer = editor
2135                .read(cx)
2136                .buffer()
2137                .read(cx)
2138                .all_buffers()
2139                .into_iter()
2140                .next()
2141                .unwrap();
2142            let buffer_id = buffer.read(cx).remote_id();
2143            let conflict_set = diff
2144                .read(cx)
2145                .editor
2146                .read(cx)
2147                .primary_editor()
2148                .read(cx)
2149                .addon::<ConflictAddon>()
2150                .unwrap()
2151                .conflict_set(buffer_id)
2152                .unwrap();
2153            assert!(conflict_set.read(cx).has_conflict);
2154            let snapshot = conflict_set.read(cx).snapshot();
2155            assert_eq!(snapshot.conflicts.len(), 1);
2156
2157            let ours_range = snapshot.conflicts[0].ours.clone();
2158
2159            resolve_conflict(
2160                editor.downgrade(),
2161                excerpt_id,
2162                snapshot.conflicts[0].clone(),
2163                vec![ours_range],
2164                window,
2165                cx,
2166            )
2167        })
2168        .await;
2169
2170        let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
2171        let contents = String::from_utf8(contents).unwrap();
2172        assert_eq!(contents, "ours\n");
2173    }
2174
2175    #[gpui::test]
2176    async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
2177        init_test(cx);
2178
2179        let fs = FakeFs::new(cx.executor());
2180        fs.insert_tree(
2181            path!("/project"),
2182            json!({
2183                ".git": {},
2184                "foo.txt": "
2185                    one
2186                    two
2187                    three
2188                    four
2189                    five
2190                    six
2191                    seven
2192                    eight
2193                    nine
2194                    ten
2195                    ELEVEN
2196                    twelve
2197                ".unindent()
2198            }),
2199        )
2200        .await;
2201        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2202        let (workspace, cx) =
2203            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2204        let diff = cx.new_window_entity(|window, cx| {
2205            ProjectDiff::new(project.clone(), workspace, window, cx)
2206        });
2207        cx.run_until_parked();
2208
2209        fs.set_head_and_index_for_repo(
2210            Path::new(path!("/project/.git")),
2211            &[(
2212                "foo.txt",
2213                "
2214                    one
2215                    two
2216                    three
2217                    four
2218                    five
2219                    six
2220                    seven
2221                    eight
2222                    nine
2223                    ten
2224                    eleven
2225                    twelve
2226                "
2227                .unindent(),
2228            )],
2229        );
2230        cx.run_until_parked();
2231
2232        let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2233
2234        assert_state_with_diff(
2235            &editor,
2236            cx,
2237            &"
2238                  ˇnine
2239                  ten
2240                - eleven
2241                + ELEVEN
2242                  twelve
2243            "
2244            .unindent(),
2245        );
2246
2247        // The project diff updates its excerpts when a new hunk appears in a buffer that already has a diff.
2248        let buffer = project
2249            .update(cx, |project, cx| {
2250                project.open_local_buffer(path!("/project/foo.txt"), cx)
2251            })
2252            .await
2253            .unwrap();
2254        buffer.update(cx, |buffer, cx| {
2255            buffer.edit_via_marked_text(
2256                &"
2257                    one
2258                    «TWO»
2259                    three
2260                    four
2261                    five
2262                    six
2263                    seven
2264                    eight
2265                    nine
2266                    ten
2267                    ELEVEN
2268                    twelve
2269                "
2270                .unindent(),
2271                None,
2272                cx,
2273            );
2274        });
2275        project
2276            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
2277            .await
2278            .unwrap();
2279        cx.run_until_parked();
2280
2281        assert_state_with_diff(
2282            &editor,
2283            cx,
2284            &"
2285                  one
2286                - two
2287                + TWO
2288                  three
2289                  four
2290                  five
2291                  ˇnine
2292                  ten
2293                - eleven
2294                + ELEVEN
2295                  twelve
2296            "
2297            .unindent(),
2298        );
2299    }
2300
2301    #[gpui::test]
2302    async fn test_branch_diff(cx: &mut TestAppContext) {
2303        init_test(cx);
2304
2305        let fs = FakeFs::new(cx.executor());
2306        fs.insert_tree(
2307            path!("/project"),
2308            json!({
2309                ".git": {},
2310                "a.txt": "C",
2311                "b.txt": "new",
2312                "c.txt": "in-merge-base-and-work-tree",
2313                "d.txt": "created-in-head",
2314            }),
2315        )
2316        .await;
2317        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2318        let (workspace, cx) =
2319            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2320        let diff = cx
2321            .update(|window, cx| {
2322                ProjectDiff::new_with_default_branch(project.clone(), workspace, window, cx)
2323            })
2324            .await
2325            .unwrap();
2326        cx.run_until_parked();
2327
2328        fs.set_head_for_repo(
2329            Path::new(path!("/project/.git")),
2330            &[("a.txt", "B".into()), ("d.txt", "created-in-head".into())],
2331            "sha",
2332        );
2333        // fs.set_index_for_repo(dot_git, index_state);
2334        fs.set_merge_base_content_for_repo(
2335            Path::new(path!("/project/.git")),
2336            &[
2337                ("a.txt", "A".into()),
2338                ("c.txt", "in-merge-base-and-work-tree".into()),
2339            ],
2340        );
2341        cx.run_until_parked();
2342
2343        let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2344
2345        assert_state_with_diff(
2346            &editor,
2347            cx,
2348            &"
2349                - A
2350                + ˇC
2351                + new
2352                + created-in-head"
2353                .unindent(),
2354        );
2355
2356        let statuses: HashMap<Arc<RelPath>, Option<FileStatus>> =
2357            editor.update(cx, |editor, cx| {
2358                editor
2359                    .buffer()
2360                    .read(cx)
2361                    .all_buffers()
2362                    .iter()
2363                    .map(|buffer| {
2364                        (
2365                            buffer.read(cx).file().unwrap().path().clone(),
2366                            editor.status_for_buffer_id(buffer.read(cx).remote_id(), cx),
2367                        )
2368                    })
2369                    .collect()
2370            });
2371
2372        assert_eq!(
2373            statuses,
2374            HashMap::from_iter([
2375                (
2376                    rel_path("a.txt").into_arc(),
2377                    Some(FileStatus::Tracked(TrackedStatus {
2378                        index_status: git::status::StatusCode::Modified,
2379                        worktree_status: git::status::StatusCode::Modified
2380                    }))
2381                ),
2382                (rel_path("b.txt").into_arc(), Some(FileStatus::Untracked)),
2383                (
2384                    rel_path("d.txt").into_arc(),
2385                    Some(FileStatus::Tracked(TrackedStatus {
2386                        index_status: git::status::StatusCode::Added,
2387                        worktree_status: git::status::StatusCode::Added
2388                    }))
2389                )
2390            ])
2391        );
2392    }
2393
2394    #[gpui::test]
2395    async fn test_update_on_uncommit(cx: &mut TestAppContext) {
2396        init_test(cx);
2397
2398        let fs = FakeFs::new(cx.executor());
2399        fs.insert_tree(
2400            path!("/project"),
2401            json!({
2402                ".git": {},
2403                "README.md": "# My cool project\n".to_owned()
2404            }),
2405        )
2406        .await;
2407        fs.set_head_and_index_for_repo(
2408            Path::new(path!("/project/.git")),
2409            &[("README.md", "# My cool project\n".to_owned())],
2410        );
2411        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
2412        let worktree_id = project.read_with(cx, |project, cx| {
2413            project.worktrees(cx).next().unwrap().read(cx).id()
2414        });
2415        let (workspace, cx) =
2416            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2417        cx.run_until_parked();
2418
2419        let _editor = workspace
2420            .update_in(cx, |workspace, window, cx| {
2421                workspace.open_path((worktree_id, rel_path("README.md")), None, true, window, cx)
2422            })
2423            .await
2424            .unwrap()
2425            .downcast::<Editor>()
2426            .unwrap();
2427
2428        cx.focus(&workspace);
2429        cx.update(|window, cx| {
2430            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2431        });
2432        cx.run_until_parked();
2433        let item = workspace.update(cx, |workspace, cx| {
2434            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2435        });
2436        cx.focus(&item);
2437        let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2438
2439        fs.set_head_and_index_for_repo(
2440            Path::new(path!("/project/.git")),
2441            &[(
2442                "README.md",
2443                "# My cool project\nDetails to come.\n".to_owned(),
2444            )],
2445        );
2446        cx.run_until_parked();
2447
2448        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2449
2450        cx.assert_excerpts_with_selections("[EXCERPT]\nˇ# My cool project\nDetails to come.\n");
2451    }
2452}