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    if settings.sort_by_path && !settings.tree_view {
 718        TRACKED_SORT_PREFIX
 719    } else if repo.had_conflict_on_last_merge_head_change(repo_path) {
 720        CONFLICT_SORT_PREFIX
 721    } else if status.is_created() {
 722        NEW_SORT_PREFIX
 723    } else {
 724        TRACKED_SORT_PREFIX
 725    }
 726}
 727
 728impl EventEmitter<EditorEvent> for ProjectDiff {}
 729
 730impl Focusable for ProjectDiff {
 731    fn focus_handle(&self, cx: &App) -> FocusHandle {
 732        if self.multibuffer.read(cx).is_empty() {
 733            self.focus_handle.clone()
 734        } else {
 735            self.editor.focus_handle(cx)
 736        }
 737    }
 738}
 739
 740impl Item for ProjectDiff {
 741    type Event = EditorEvent;
 742
 743    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 744        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
 745    }
 746
 747    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 748        Editor::to_item_events(event, f)
 749    }
 750
 751    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 752        self.editor.update(cx, |editor, cx| {
 753            editor.primary_editor().update(cx, |primary_editor, cx| {
 754                primary_editor.deactivated(window, cx);
 755            })
 756        });
 757    }
 758
 759    fn navigate(
 760        &mut self,
 761        data: Box<dyn Any>,
 762        window: &mut Window,
 763        cx: &mut Context<Self>,
 764    ) -> bool {
 765        self.editor.update(cx, |editor, cx| {
 766            editor.primary_editor().update(cx, |primary_editor, cx| {
 767                primary_editor.navigate(data, window, cx)
 768            })
 769        })
 770    }
 771
 772    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 773        Some("Project Diff".into())
 774    }
 775
 776    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
 777        Label::new(self.tab_content_text(0, cx))
 778            .color(if params.selected {
 779                Color::Default
 780            } else {
 781                Color::Muted
 782            })
 783            .into_any_element()
 784    }
 785
 786    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
 787        match self.branch_diff.read(cx).diff_base() {
 788            DiffBase::Head => "Uncommitted Changes".into(),
 789            DiffBase::Merge { base_ref } => format!("Changes since {}", base_ref).into(),
 790        }
 791    }
 792
 793    fn telemetry_event_text(&self) -> Option<&'static str> {
 794        Some("Project Diff Opened")
 795    }
 796
 797    fn as_searchable(&self, _: &Entity<Self>, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
 798        // TODO(split-diff) SplitEditor should be searchable
 799        Some(Box::new(self.editor.read(cx).primary_editor().clone()))
 800    }
 801
 802    fn for_each_project_item(
 803        &self,
 804        cx: &App,
 805        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 806    ) {
 807        self.editor
 808            .read(cx)
 809            .primary_editor()
 810            .read(cx)
 811            .for_each_project_item(cx, f)
 812    }
 813
 814    fn set_nav_history(
 815        &mut self,
 816        nav_history: ItemNavHistory,
 817        _: &mut Window,
 818        cx: &mut Context<Self>,
 819    ) {
 820        self.editor.update(cx, |editor, cx| {
 821            editor.primary_editor().update(cx, |primary_editor, _| {
 822                primary_editor.set_nav_history(Some(nav_history));
 823            })
 824        });
 825    }
 826
 827    fn can_split(&self) -> bool {
 828        true
 829    }
 830
 831    fn clone_on_split(
 832        &self,
 833        _workspace_id: Option<workspace::WorkspaceId>,
 834        window: &mut Window,
 835        cx: &mut Context<Self>,
 836    ) -> Task<Option<Entity<Self>>>
 837    where
 838        Self: Sized,
 839    {
 840        let Some(workspace) = self.workspace.upgrade() else {
 841            return Task::ready(None);
 842        };
 843        Task::ready(Some(cx.new(|cx| {
 844            ProjectDiff::new(self.project.clone(), workspace, window, cx)
 845        })))
 846    }
 847
 848    fn is_dirty(&self, cx: &App) -> bool {
 849        self.multibuffer.read(cx).is_dirty(cx)
 850    }
 851
 852    fn has_conflict(&self, cx: &App) -> bool {
 853        self.multibuffer.read(cx).has_conflict(cx)
 854    }
 855
 856    fn can_save(&self, _: &App) -> bool {
 857        true
 858    }
 859
 860    fn save(
 861        &mut self,
 862        options: SaveOptions,
 863        project: Entity<Project>,
 864        window: &mut Window,
 865        cx: &mut Context<Self>,
 866    ) -> Task<Result<()>> {
 867        self.editor.update(cx, |editor, cx| {
 868            editor.primary_editor().update(cx, |primary_editor, cx| {
 869                primary_editor.save(options, project, window, cx)
 870            })
 871        })
 872    }
 873
 874    fn save_as(
 875        &mut self,
 876        _: Entity<Project>,
 877        _: ProjectPath,
 878        _window: &mut Window,
 879        _: &mut Context<Self>,
 880    ) -> Task<Result<()>> {
 881        unreachable!()
 882    }
 883
 884    fn reload(
 885        &mut self,
 886        project: Entity<Project>,
 887        window: &mut Window,
 888        cx: &mut Context<Self>,
 889    ) -> Task<Result<()>> {
 890        self.editor.update(cx, |editor, cx| {
 891            editor.primary_editor().update(cx, |primary_editor, cx| {
 892                primary_editor.reload(project, window, cx)
 893            })
 894        })
 895    }
 896
 897    fn act_as_type<'a>(
 898        &'a self,
 899        type_id: TypeId,
 900        self_handle: &'a Entity<Self>,
 901        cx: &'a App,
 902    ) -> Option<gpui::AnyEntity> {
 903        if type_id == TypeId::of::<Self>() {
 904            Some(self_handle.clone().into())
 905        } else if type_id == TypeId::of::<Editor>() {
 906            Some(self.editor.read(cx).primary_editor().clone().into())
 907        } else {
 908            None
 909        }
 910    }
 911
 912    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 913        ToolbarItemLocation::PrimaryLeft
 914    }
 915
 916    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 917        self.editor
 918            .read(cx)
 919            .last_selected_editor()
 920            .read(cx)
 921            .breadcrumbs(theme, cx)
 922    }
 923
 924    fn added_to_workspace(
 925        &mut self,
 926        workspace: &mut Workspace,
 927        window: &mut Window,
 928        cx: &mut Context<Self>,
 929    ) {
 930        self.editor.update(cx, |editor, cx| {
 931            editor.added_to_workspace(workspace, window, cx)
 932        });
 933    }
 934}
 935
 936impl Render for ProjectDiff {
 937    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 938        let is_empty = self.multibuffer.read(cx).is_empty();
 939
 940        div()
 941            .track_focus(&self.focus_handle)
 942            .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
 943            .bg(cx.theme().colors().editor_background)
 944            .flex()
 945            .items_center()
 946            .justify_center()
 947            .size_full()
 948            .when(is_empty, |el| {
 949                let remote_button = if let Some(panel) = self
 950                    .workspace
 951                    .upgrade()
 952                    .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
 953                {
 954                    panel.update(cx, |panel, cx| panel.render_remote_button(cx))
 955                } else {
 956                    None
 957                };
 958                let keybinding_focus_handle = self.focus_handle(cx);
 959                el.child(
 960                    v_flex()
 961                        .gap_1()
 962                        .child(
 963                            h_flex()
 964                                .justify_around()
 965                                .child(Label::new("No uncommitted changes")),
 966                        )
 967                        .map(|el| match remote_button {
 968                            Some(button) => el.child(h_flex().justify_around().child(button)),
 969                            None => el.child(
 970                                h_flex()
 971                                    .justify_around()
 972                                    .child(Label::new("Remote up to date")),
 973                            ),
 974                        })
 975                        .child(
 976                            h_flex().justify_around().mt_1().child(
 977                                Button::new("project-diff-close-button", "Close")
 978                                    // .style(ButtonStyle::Transparent)
 979                                    .key_binding(KeyBinding::for_action_in(
 980                                        &CloseActiveItem::default(),
 981                                        &keybinding_focus_handle,
 982                                        cx,
 983                                    ))
 984                                    .on_click(move |_, window, cx| {
 985                                        window.focus(&keybinding_focus_handle);
 986                                        window.dispatch_action(
 987                                            Box::new(CloseActiveItem::default()),
 988                                            cx,
 989                                        );
 990                                    }),
 991                            ),
 992                        ),
 993                )
 994            })
 995            .when(!is_empty, |el| el.child(self.editor.clone()))
 996    }
 997}
 998
 999impl SerializableItem for ProjectDiff {
1000    fn serialized_item_kind() -> &'static str {
1001        "ProjectDiff"
1002    }
1003
1004    fn cleanup(
1005        _: workspace::WorkspaceId,
1006        _: Vec<workspace::ItemId>,
1007        _: &mut Window,
1008        _: &mut App,
1009    ) -> Task<Result<()>> {
1010        Task::ready(Ok(()))
1011    }
1012
1013    fn deserialize(
1014        project: Entity<Project>,
1015        workspace: WeakEntity<Workspace>,
1016        workspace_id: workspace::WorkspaceId,
1017        item_id: workspace::ItemId,
1018        window: &mut Window,
1019        cx: &mut App,
1020    ) -> Task<Result<Entity<Self>>> {
1021        window.spawn(cx, async move |cx| {
1022            let diff_base = persistence::PROJECT_DIFF_DB.get_diff_base(item_id, workspace_id)?;
1023
1024            let diff = cx.update(|window, cx| {
1025                let branch_diff = cx
1026                    .new(|cx| branch_diff::BranchDiff::new(diff_base, project.clone(), window, cx));
1027                let workspace = workspace.upgrade().context("workspace gone")?;
1028                anyhow::Ok(
1029                    cx.new(|cx| ProjectDiff::new_impl(branch_diff, project, workspace, window, cx)),
1030                )
1031            })??;
1032
1033            Ok(diff)
1034        })
1035    }
1036
1037    fn serialize(
1038        &mut self,
1039        workspace: &mut Workspace,
1040        item_id: workspace::ItemId,
1041        _closing: bool,
1042        _window: &mut Window,
1043        cx: &mut Context<Self>,
1044    ) -> Option<Task<Result<()>>> {
1045        let workspace_id = workspace.database_id()?;
1046        let diff_base = self.diff_base(cx).clone();
1047
1048        Some(cx.background_spawn({
1049            async move {
1050                persistence::PROJECT_DIFF_DB
1051                    .save_diff_base(item_id, workspace_id, diff_base.clone())
1052                    .await
1053            }
1054        }))
1055    }
1056
1057    fn should_serialize(&self, _: &Self::Event) -> bool {
1058        false
1059    }
1060}
1061
1062mod persistence {
1063
1064    use anyhow::Context as _;
1065    use db::{
1066        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
1067        sqlez_macros::sql,
1068    };
1069    use project::git_store::branch_diff::DiffBase;
1070    use workspace::{ItemId, WorkspaceDb, WorkspaceId};
1071
1072    pub struct ProjectDiffDb(ThreadSafeConnection);
1073
1074    impl Domain for ProjectDiffDb {
1075        const NAME: &str = stringify!(ProjectDiffDb);
1076
1077        const MIGRATIONS: &[&str] = &[sql!(
1078                CREATE TABLE project_diffs(
1079                    workspace_id INTEGER,
1080                    item_id INTEGER UNIQUE,
1081
1082                    diff_base TEXT,
1083
1084                    PRIMARY KEY(workspace_id, item_id),
1085                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
1086                    ON DELETE CASCADE
1087                ) STRICT;
1088        )];
1089    }
1090
1091    db::static_connection!(PROJECT_DIFF_DB, ProjectDiffDb, [WorkspaceDb]);
1092
1093    impl ProjectDiffDb {
1094        pub async fn save_diff_base(
1095            &self,
1096            item_id: ItemId,
1097            workspace_id: WorkspaceId,
1098            diff_base: DiffBase,
1099        ) -> anyhow::Result<()> {
1100            self.write(move |connection| {
1101                let sql_stmt = sql!(
1102                    INSERT OR REPLACE INTO project_diffs(item_id, workspace_id, diff_base) VALUES (?, ?, ?)
1103                );
1104                let diff_base_str = serde_json::to_string(&diff_base)?;
1105                let mut query = connection.exec_bound::<(ItemId, WorkspaceId, String)>(sql_stmt)?;
1106                query((item_id, workspace_id, diff_base_str)).context(format!(
1107                    "exec_bound failed to execute or parse for: {}",
1108                    sql_stmt
1109                ))
1110            })
1111            .await
1112        }
1113
1114        pub fn get_diff_base(
1115            &self,
1116            item_id: ItemId,
1117            workspace_id: WorkspaceId,
1118        ) -> anyhow::Result<DiffBase> {
1119            let sql_stmt =
1120                sql!(SELECT diff_base FROM project_diffs WHERE item_id =  ?AND workspace_id =  ?);
1121            let diff_base_str = self.select_row_bound::<(ItemId, WorkspaceId), String>(sql_stmt)?(
1122                (item_id, workspace_id),
1123            )
1124            .context(::std::format!(
1125                "Error in get_diff_base, select_row_bound failed to execute or parse for: {}",
1126                sql_stmt
1127            ))?;
1128            let Some(diff_base_str) = diff_base_str else {
1129                return Ok(DiffBase::Head);
1130            };
1131            serde_json::from_str(&diff_base_str).context("deserializing diff base")
1132        }
1133    }
1134}
1135
1136pub struct ProjectDiffToolbar {
1137    project_diff: Option<WeakEntity<ProjectDiff>>,
1138    workspace: WeakEntity<Workspace>,
1139}
1140
1141impl ProjectDiffToolbar {
1142    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
1143        Self {
1144            project_diff: None,
1145            workspace: workspace.weak_handle(),
1146        }
1147    }
1148
1149    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
1150        self.project_diff.as_ref()?.upgrade()
1151    }
1152
1153    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
1154        if let Some(project_diff) = self.project_diff(cx) {
1155            project_diff.focus_handle(cx).focus(window);
1156        }
1157        let action = action.boxed_clone();
1158        cx.defer(move |cx| {
1159            cx.dispatch_action(action.as_ref());
1160        })
1161    }
1162
1163    fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1164        self.workspace
1165            .update(cx, |workspace, cx| {
1166                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
1167                    panel.update(cx, |panel, cx| {
1168                        panel.stage_all(&Default::default(), window, cx);
1169                    });
1170                }
1171            })
1172            .ok();
1173    }
1174
1175    fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1176        self.workspace
1177            .update(cx, |workspace, cx| {
1178                let Some(panel) = workspace.panel::<GitPanel>(cx) else {
1179                    return;
1180                };
1181                panel.update(cx, |panel, cx| {
1182                    panel.unstage_all(&Default::default(), window, cx);
1183                });
1184            })
1185            .ok();
1186    }
1187}
1188
1189impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
1190
1191impl ToolbarItemView for ProjectDiffToolbar {
1192    fn set_active_pane_item(
1193        &mut self,
1194        active_pane_item: Option<&dyn ItemHandle>,
1195        _: &mut Window,
1196        cx: &mut Context<Self>,
1197    ) -> ToolbarItemLocation {
1198        self.project_diff = active_pane_item
1199            .and_then(|item| item.act_as::<ProjectDiff>(cx))
1200            .filter(|item| item.read(cx).diff_base(cx) == &DiffBase::Head)
1201            .map(|entity| entity.downgrade());
1202        if self.project_diff.is_some() {
1203            ToolbarItemLocation::PrimaryRight
1204        } else {
1205            ToolbarItemLocation::Hidden
1206        }
1207    }
1208
1209    fn pane_focus_update(
1210        &mut self,
1211        _pane_focused: bool,
1212        _window: &mut Window,
1213        _cx: &mut Context<Self>,
1214    ) {
1215    }
1216}
1217
1218struct ButtonStates {
1219    stage: bool,
1220    unstage: bool,
1221    prev_next: bool,
1222    selection: bool,
1223    stage_all: bool,
1224    unstage_all: bool,
1225}
1226
1227impl Render for ProjectDiffToolbar {
1228    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1229        let Some(project_diff) = self.project_diff(cx) else {
1230            return div();
1231        };
1232        let focus_handle = project_diff.focus_handle(cx);
1233        let button_states = project_diff.read(cx).button_states(cx);
1234
1235        h_group_xl()
1236            .my_neg_1()
1237            .py_1()
1238            .items_center()
1239            .flex_wrap()
1240            .justify_between()
1241            .child(
1242                h_group_sm()
1243                    .when(button_states.selection, |el| {
1244                        el.child(
1245                            Button::new("stage", "Toggle Staged")
1246                                .tooltip(Tooltip::for_action_title_in(
1247                                    "Toggle Staged",
1248                                    &ToggleStaged,
1249                                    &focus_handle,
1250                                ))
1251                                .disabled(!button_states.stage && !button_states.unstage)
1252                                .on_click(cx.listener(|this, _, window, cx| {
1253                                    this.dispatch_action(&ToggleStaged, window, cx)
1254                                })),
1255                        )
1256                    })
1257                    .when(!button_states.selection, |el| {
1258                        el.child(
1259                            Button::new("stage", "Stage")
1260                                .tooltip(Tooltip::for_action_title_in(
1261                                    "Stage and go to next hunk",
1262                                    &StageAndNext,
1263                                    &focus_handle,
1264                                ))
1265                                .disabled(
1266                                    !button_states.prev_next
1267                                        && !button_states.stage_all
1268                                        && !button_states.unstage_all,
1269                                )
1270                                .on_click(cx.listener(|this, _, window, cx| {
1271                                    this.dispatch_action(&StageAndNext, window, cx)
1272                                })),
1273                        )
1274                        .child(
1275                            Button::new("unstage", "Unstage")
1276                                .tooltip(Tooltip::for_action_title_in(
1277                                    "Unstage and go to next hunk",
1278                                    &UnstageAndNext,
1279                                    &focus_handle,
1280                                ))
1281                                .disabled(
1282                                    !button_states.prev_next
1283                                        && !button_states.stage_all
1284                                        && !button_states.unstage_all,
1285                                )
1286                                .on_click(cx.listener(|this, _, window, cx| {
1287                                    this.dispatch_action(&UnstageAndNext, window, cx)
1288                                })),
1289                        )
1290                    }),
1291            )
1292            // n.b. the only reason these arrows are here is because we don't
1293            // support "undo" for staging so we need a way to go back.
1294            .child(
1295                h_group_sm()
1296                    .child(
1297                        IconButton::new("up", IconName::ArrowUp)
1298                            .shape(ui::IconButtonShape::Square)
1299                            .tooltip(Tooltip::for_action_title_in(
1300                                "Go to previous hunk",
1301                                &GoToPreviousHunk,
1302                                &focus_handle,
1303                            ))
1304                            .disabled(!button_states.prev_next)
1305                            .on_click(cx.listener(|this, _, window, cx| {
1306                                this.dispatch_action(&GoToPreviousHunk, window, cx)
1307                            })),
1308                    )
1309                    .child(
1310                        IconButton::new("down", IconName::ArrowDown)
1311                            .shape(ui::IconButtonShape::Square)
1312                            .tooltip(Tooltip::for_action_title_in(
1313                                "Go to next hunk",
1314                                &GoToHunk,
1315                                &focus_handle,
1316                            ))
1317                            .disabled(!button_states.prev_next)
1318                            .on_click(cx.listener(|this, _, window, cx| {
1319                                this.dispatch_action(&GoToHunk, window, cx)
1320                            })),
1321                    ),
1322            )
1323            .child(vertical_divider())
1324            .child(
1325                h_group_sm()
1326                    .when(
1327                        button_states.unstage_all && !button_states.stage_all,
1328                        |el| {
1329                            el.child(
1330                                Button::new("unstage-all", "Unstage All")
1331                                    .tooltip(Tooltip::for_action_title_in(
1332                                        "Unstage all changes",
1333                                        &UnstageAll,
1334                                        &focus_handle,
1335                                    ))
1336                                    .on_click(cx.listener(|this, _, window, cx| {
1337                                        this.unstage_all(window, cx)
1338                                    })),
1339                            )
1340                        },
1341                    )
1342                    .when(
1343                        !button_states.unstage_all || button_states.stage_all,
1344                        |el| {
1345                            el.child(
1346                                // todo make it so that changing to say "Unstaged"
1347                                // doesn't change the position.
1348                                div().child(
1349                                    Button::new("stage-all", "Stage All")
1350                                        .disabled(!button_states.stage_all)
1351                                        .tooltip(Tooltip::for_action_title_in(
1352                                            "Stage all changes",
1353                                            &StageAll,
1354                                            &focus_handle,
1355                                        ))
1356                                        .on_click(cx.listener(|this, _, window, cx| {
1357                                            this.stage_all(window, cx)
1358                                        })),
1359                                ),
1360                            )
1361                        },
1362                    )
1363                    .child(
1364                        Button::new("commit", "Commit")
1365                            .tooltip(Tooltip::for_action_title_in(
1366                                "Commit",
1367                                &Commit,
1368                                &focus_handle,
1369                            ))
1370                            .on_click(cx.listener(|this, _, window, cx| {
1371                                this.dispatch_action(&Commit, window, cx);
1372                            })),
1373                    ),
1374            )
1375    }
1376}
1377
1378#[derive(IntoElement, RegisterComponent)]
1379pub struct ProjectDiffEmptyState {
1380    pub no_repo: bool,
1381    pub can_push_and_pull: bool,
1382    pub focus_handle: Option<FocusHandle>,
1383    pub current_branch: Option<Branch>,
1384    // has_pending_commits: bool,
1385    // ahead_of_remote: bool,
1386    // no_git_repository: bool,
1387}
1388
1389impl RenderOnce for ProjectDiffEmptyState {
1390    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1391        let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1392            matches!(self.current_branch, Some(Branch {
1393                    upstream:
1394                        Some(Upstream {
1395                            tracking:
1396                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1397                                    ahead, behind, ..
1398                                }),
1399                            ..
1400                        }),
1401                    ..
1402                }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1403        };
1404
1405        let change_count = |current_branch: &Branch| -> (usize, usize) {
1406            match current_branch {
1407                Branch {
1408                    upstream:
1409                        Some(Upstream {
1410                            tracking:
1411                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1412                                    ahead, behind, ..
1413                                }),
1414                            ..
1415                        }),
1416                    ..
1417                } => (*ahead as usize, *behind as usize),
1418                _ => (0, 0),
1419            }
1420        };
1421
1422        let not_ahead_or_behind = status_against_remote(0, 0);
1423        let ahead_of_remote = status_against_remote(1, 0);
1424        let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1425            branch.upstream.is_none()
1426        } else {
1427            false
1428        };
1429
1430        let has_branch_container = |branch: &Branch| {
1431            h_flex()
1432                .max_w(px(420.))
1433                .bg(cx.theme().colors().text.opacity(0.05))
1434                .border_1()
1435                .border_color(cx.theme().colors().border)
1436                .rounded_sm()
1437                .gap_8()
1438                .px_6()
1439                .py_4()
1440                .map(|this| {
1441                    if ahead_of_remote {
1442                        let ahead_count = change_count(branch).0;
1443                        let ahead_string = format!("{} Commits Ahead", ahead_count);
1444                        this.child(
1445                            v_flex()
1446                                .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1447                                .child(
1448                                    Label::new(format!("Push your changes to {}", branch.name()))
1449                                        .color(Color::Muted),
1450                                ),
1451                        )
1452                        .child(div().child(render_push_button(
1453                            self.focus_handle,
1454                            "push".into(),
1455                            ahead_count as u32,
1456                        )))
1457                    } else if branch_not_on_remote {
1458                        this.child(
1459                            v_flex()
1460                                .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1461                                .child(
1462                                    Label::new(format!("Create {} on remote", branch.name()))
1463                                        .color(Color::Muted),
1464                                ),
1465                        )
1466                        .child(
1467                            div().child(render_publish_button(self.focus_handle, "publish".into())),
1468                        )
1469                    } else {
1470                        this.child(Label::new("Remote status unknown").color(Color::Muted))
1471                    }
1472                })
1473        };
1474
1475        v_flex().size_full().items_center().justify_center().child(
1476            v_flex()
1477                .gap_1()
1478                .when(self.no_repo, |this| {
1479                    // TODO: add git init
1480                    this.text_center()
1481                        .child(Label::new("No Repository").color(Color::Muted))
1482                })
1483                .map(|this| {
1484                    if not_ahead_or_behind && self.current_branch.is_some() {
1485                        this.text_center()
1486                            .child(Label::new("No Changes").color(Color::Muted))
1487                    } else {
1488                        this.when_some(self.current_branch.as_ref(), |this, branch| {
1489                            this.child(has_branch_container(branch))
1490                        })
1491                    }
1492                }),
1493        )
1494    }
1495}
1496
1497mod preview {
1498    use git::repository::{
1499        Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1500    };
1501    use ui::prelude::*;
1502
1503    use super::ProjectDiffEmptyState;
1504
1505    // View this component preview using `workspace: open component-preview`
1506    impl Component for ProjectDiffEmptyState {
1507        fn scope() -> ComponentScope {
1508            ComponentScope::VersionControl
1509        }
1510
1511        fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1512            let unknown_upstream: Option<UpstreamTracking> = None;
1513            let ahead_of_upstream: Option<UpstreamTracking> = Some(
1514                UpstreamTrackingStatus {
1515                    ahead: 2,
1516                    behind: 0,
1517                }
1518                .into(),
1519            );
1520
1521            let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1522                UpstreamTrackingStatus {
1523                    ahead: 0,
1524                    behind: 0,
1525                }
1526                .into(),
1527            );
1528
1529            fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1530                Branch {
1531                    is_head: true,
1532                    ref_name: "some-branch".into(),
1533                    upstream: upstream.map(|tracking| Upstream {
1534                        ref_name: "origin/some-branch".into(),
1535                        tracking,
1536                    }),
1537                    most_recent_commit: Some(CommitSummary {
1538                        sha: "abc123".into(),
1539                        subject: "Modify stuff".into(),
1540                        commit_timestamp: 1710932954,
1541                        author_name: "John Doe".into(),
1542                        has_parent: true,
1543                    }),
1544                }
1545            }
1546
1547            let no_repo_state = ProjectDiffEmptyState {
1548                no_repo: true,
1549                can_push_and_pull: false,
1550                focus_handle: None,
1551                current_branch: None,
1552            };
1553
1554            let no_changes_state = ProjectDiffEmptyState {
1555                no_repo: false,
1556                can_push_and_pull: true,
1557                focus_handle: None,
1558                current_branch: Some(branch(not_ahead_or_behind_upstream)),
1559            };
1560
1561            let ahead_of_upstream_state = ProjectDiffEmptyState {
1562                no_repo: false,
1563                can_push_and_pull: true,
1564                focus_handle: None,
1565                current_branch: Some(branch(ahead_of_upstream)),
1566            };
1567
1568            let unknown_upstream_state = ProjectDiffEmptyState {
1569                no_repo: false,
1570                can_push_and_pull: true,
1571                focus_handle: None,
1572                current_branch: Some(branch(unknown_upstream)),
1573            };
1574
1575            let (width, height) = (px(480.), px(320.));
1576
1577            Some(
1578                v_flex()
1579                    .gap_6()
1580                    .children(vec![
1581                        example_group(vec![
1582                            single_example(
1583                                "No Repo",
1584                                div()
1585                                    .w(width)
1586                                    .h(height)
1587                                    .child(no_repo_state)
1588                                    .into_any_element(),
1589                            ),
1590                            single_example(
1591                                "No Changes",
1592                                div()
1593                                    .w(width)
1594                                    .h(height)
1595                                    .child(no_changes_state)
1596                                    .into_any_element(),
1597                            ),
1598                            single_example(
1599                                "Unknown Upstream",
1600                                div()
1601                                    .w(width)
1602                                    .h(height)
1603                                    .child(unknown_upstream_state)
1604                                    .into_any_element(),
1605                            ),
1606                            single_example(
1607                                "Ahead of Remote",
1608                                div()
1609                                    .w(width)
1610                                    .h(height)
1611                                    .child(ahead_of_upstream_state)
1612                                    .into_any_element(),
1613                            ),
1614                        ])
1615                        .vertical(),
1616                    ])
1617                    .into_any_element(),
1618            )
1619        }
1620    }
1621}
1622
1623struct BranchDiffAddon {
1624    branch_diff: Entity<branch_diff::BranchDiff>,
1625}
1626
1627impl Addon for BranchDiffAddon {
1628    fn to_any(&self) -> &dyn std::any::Any {
1629        self
1630    }
1631
1632    fn override_status_for_buffer_id(
1633        &self,
1634        buffer_id: language::BufferId,
1635        cx: &App,
1636    ) -> Option<FileStatus> {
1637        self.branch_diff
1638            .read(cx)
1639            .status_for_buffer_id(buffer_id, cx)
1640    }
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645    use collections::HashMap;
1646    use db::indoc;
1647    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1648    use git::status::{TrackedStatus, UnmergedStatus, UnmergedStatusCode};
1649    use gpui::TestAppContext;
1650    use project::FakeFs;
1651    use serde_json::json;
1652    use settings::SettingsStore;
1653    use std::path::Path;
1654    use unindent::Unindent as _;
1655    use util::{
1656        path,
1657        rel_path::{RelPath, rel_path},
1658    };
1659
1660    use super::*;
1661
1662    #[ctor::ctor]
1663    fn init_logger() {
1664        zlog::init_test();
1665    }
1666
1667    fn init_test(cx: &mut TestAppContext) {
1668        cx.update(|cx| {
1669            let store = SettingsStore::test(cx);
1670            cx.set_global(store);
1671            theme::init(theme::LoadThemes::JustBase, cx);
1672            editor::init(cx);
1673            crate::init(cx);
1674        });
1675    }
1676
1677    #[gpui::test]
1678    async fn test_save_after_restore(cx: &mut TestAppContext) {
1679        init_test(cx);
1680
1681        let fs = FakeFs::new(cx.executor());
1682        fs.insert_tree(
1683            path!("/project"),
1684            json!({
1685                ".git": {},
1686                "foo.txt": "FOO\n",
1687            }),
1688        )
1689        .await;
1690        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1691        let (workspace, cx) =
1692            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1693        let diff = cx.new_window_entity(|window, cx| {
1694            ProjectDiff::new(project.clone(), workspace, window, cx)
1695        });
1696        cx.run_until_parked();
1697
1698        fs.set_head_for_repo(
1699            path!("/project/.git").as_ref(),
1700            &[("foo.txt", "foo\n".into())],
1701            "deadbeef",
1702        );
1703        fs.set_index_for_repo(
1704            path!("/project/.git").as_ref(),
1705            &[("foo.txt", "foo\n".into())],
1706        );
1707        cx.run_until_parked();
1708
1709        let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
1710        assert_state_with_diff(
1711            &editor,
1712            cx,
1713            &"
1714                - foo
1715                + ˇFOO
1716            "
1717            .unindent(),
1718        );
1719
1720        editor
1721            .update_in(cx, |editor, window, cx| {
1722                editor.git_restore(&Default::default(), window, cx);
1723                editor.save(SaveOptions::default(), project.clone(), window, cx)
1724            })
1725            .await
1726            .unwrap();
1727        cx.run_until_parked();
1728
1729        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1730
1731        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1732        assert_eq!(text, "foo\n");
1733    }
1734
1735    #[gpui::test]
1736    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1737        init_test(cx);
1738
1739        let fs = FakeFs::new(cx.executor());
1740        fs.insert_tree(
1741            path!("/project"),
1742            json!({
1743                ".git": {},
1744                "bar": "BAR\n",
1745                "foo": "FOO\n",
1746            }),
1747        )
1748        .await;
1749        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1750        let (workspace, cx) =
1751            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1752        let diff = cx.new_window_entity(|window, cx| {
1753            ProjectDiff::new(project.clone(), workspace, window, cx)
1754        });
1755        cx.run_until_parked();
1756
1757        fs.set_head_and_index_for_repo(
1758            path!("/project/.git").as_ref(),
1759            &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1760        );
1761        cx.run_until_parked();
1762
1763        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1764            diff.move_to_path(
1765                PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("foo").into_arc()),
1766                window,
1767                cx,
1768            );
1769            diff.editor.read(cx).primary_editor().clone()
1770        });
1771        assert_state_with_diff(
1772            &editor,
1773            cx,
1774            &"
1775                - bar
1776                + BAR
1777
1778                - ˇfoo
1779                + FOO
1780            "
1781            .unindent(),
1782        );
1783
1784        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1785            diff.move_to_path(
1786                PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("bar").into_arc()),
1787                window,
1788                cx,
1789            );
1790            diff.editor.read(cx).primary_editor().clone()
1791        });
1792        assert_state_with_diff(
1793            &editor,
1794            cx,
1795            &"
1796                - ˇbar
1797                + BAR
1798
1799                - foo
1800                + FOO
1801            "
1802            .unindent(),
1803        );
1804    }
1805
1806    #[gpui::test]
1807    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1808        init_test(cx);
1809
1810        let fs = FakeFs::new(cx.executor());
1811        fs.insert_tree(
1812            path!("/project"),
1813            json!({
1814                ".git": {},
1815                "foo": "modified\n",
1816            }),
1817        )
1818        .await;
1819        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1820        let (workspace, cx) =
1821            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1822        let buffer = project
1823            .update(cx, |project, cx| {
1824                project.open_local_buffer(path!("/project/foo"), cx)
1825            })
1826            .await
1827            .unwrap();
1828        let buffer_editor = cx.new_window_entity(|window, cx| {
1829            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1830        });
1831        let diff = cx.new_window_entity(|window, cx| {
1832            ProjectDiff::new(project.clone(), workspace, window, cx)
1833        });
1834        cx.run_until_parked();
1835
1836        fs.set_head_for_repo(
1837            path!("/project/.git").as_ref(),
1838            &[("foo", "original\n".into())],
1839            "deadbeef",
1840        );
1841        cx.run_until_parked();
1842
1843        let diff_editor =
1844            diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
1845
1846        assert_state_with_diff(
1847            &diff_editor,
1848            cx,
1849            &"
1850                - original
1851                + ˇmodified
1852            "
1853            .unindent(),
1854        );
1855
1856        let prev_buffer_hunks =
1857            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1858                let snapshot = buffer_editor.snapshot(window, cx);
1859                let snapshot = &snapshot.buffer_snapshot();
1860                let prev_buffer_hunks = buffer_editor
1861                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1862                    .collect::<Vec<_>>();
1863                buffer_editor.git_restore(&Default::default(), window, cx);
1864                prev_buffer_hunks
1865            });
1866        assert_eq!(prev_buffer_hunks.len(), 1);
1867        cx.run_until_parked();
1868
1869        let new_buffer_hunks =
1870            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1871                let snapshot = buffer_editor.snapshot(window, cx);
1872                let snapshot = &snapshot.buffer_snapshot();
1873                buffer_editor
1874                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1875                    .collect::<Vec<_>>()
1876            });
1877        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1878
1879        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1880            buffer_editor.set_text("different\n", window, cx);
1881            buffer_editor.save(
1882                SaveOptions {
1883                    format: false,
1884                    autosave: false,
1885                },
1886                project.clone(),
1887                window,
1888                cx,
1889            )
1890        })
1891        .await
1892        .unwrap();
1893
1894        cx.run_until_parked();
1895
1896        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1897            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1898        });
1899
1900        assert_state_with_diff(
1901            &buffer_editor,
1902            cx,
1903            &"
1904                - original
1905                + different
1906                  ˇ"
1907            .unindent(),
1908        );
1909
1910        assert_state_with_diff(
1911            &diff_editor,
1912            cx,
1913            &"
1914                - original
1915                + different
1916                  ˇ"
1917            .unindent(),
1918        );
1919    }
1920
1921    use crate::{
1922        conflict_view::resolve_conflict,
1923        project_diff::{self, ProjectDiff},
1924    };
1925
1926    #[gpui::test]
1927    async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1928        init_test(cx);
1929
1930        let fs = FakeFs::new(cx.executor());
1931        fs.insert_tree(
1932            path!("/a"),
1933            json!({
1934                ".git": {},
1935                "a.txt": "created\n",
1936                "b.txt": "really changed\n",
1937                "c.txt": "unchanged\n"
1938            }),
1939        )
1940        .await;
1941
1942        fs.set_head_and_index_for_repo(
1943            Path::new(path!("/a/.git")),
1944            &[
1945                ("b.txt", "before\n".to_string()),
1946                ("c.txt", "unchanged\n".to_string()),
1947                ("d.txt", "deleted\n".to_string()),
1948            ],
1949        );
1950
1951        let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1952        let (workspace, cx) =
1953            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1954
1955        cx.run_until_parked();
1956
1957        cx.focus(&workspace);
1958        cx.update(|window, cx| {
1959            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1960        });
1961
1962        cx.run_until_parked();
1963
1964        let item = workspace.update(cx, |workspace, cx| {
1965            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1966        });
1967        cx.focus(&item);
1968        let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
1969
1970        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1971
1972        cx.assert_excerpts_with_selections(indoc!(
1973            "
1974            [EXCERPT]
1975            before
1976            really changed
1977            [EXCERPT]
1978            [FOLDED]
1979            [EXCERPT]
1980            ˇcreated
1981        "
1982        ));
1983
1984        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1985
1986        cx.assert_excerpts_with_selections(indoc!(
1987            "
1988            [EXCERPT]
1989            before
1990            really changed
1991            [EXCERPT]
1992            ˇ[FOLDED]
1993            [EXCERPT]
1994            created
1995        "
1996        ));
1997
1998        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1999
2000        cx.assert_excerpts_with_selections(indoc!(
2001            "
2002            [EXCERPT]
2003            ˇbefore
2004            really changed
2005            [EXCERPT]
2006            [FOLDED]
2007            [EXCERPT]
2008            created
2009        "
2010        ));
2011    }
2012
2013    #[gpui::test]
2014    async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
2015        init_test(cx);
2016
2017        let git_contents = indoc! {r#"
2018            #[rustfmt::skip]
2019            fn main() {
2020                let x = 0.0; // this line will be removed
2021                // 1
2022                // 2
2023                // 3
2024                let y = 0.0; // this line will be removed
2025                // 1
2026                // 2
2027                // 3
2028                let arr = [
2029                    0.0, // this line will be removed
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                ];
2034            }
2035        "#};
2036        let buffer_contents = indoc! {"
2037            #[rustfmt::skip]
2038            fn main() {
2039                // 1
2040                // 2
2041                // 3
2042                // 1
2043                // 2
2044                // 3
2045                let arr = [
2046                ];
2047            }
2048        "};
2049
2050        let fs = FakeFs::new(cx.executor());
2051        fs.insert_tree(
2052            path!("/a"),
2053            json!({
2054                ".git": {},
2055                "main.rs": buffer_contents,
2056            }),
2057        )
2058        .await;
2059
2060        fs.set_head_and_index_for_repo(
2061            Path::new(path!("/a/.git")),
2062            &[("main.rs", git_contents.to_owned())],
2063        );
2064
2065        let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2066        let (workspace, cx) =
2067            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2068
2069        cx.run_until_parked();
2070
2071        cx.focus(&workspace);
2072        cx.update(|window, cx| {
2073            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2074        });
2075
2076        cx.run_until_parked();
2077
2078        let item = workspace.update(cx, |workspace, cx| {
2079            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2080        });
2081        cx.focus(&item);
2082        let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2083
2084        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2085
2086        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2087
2088        cx.dispatch_action(editor::actions::GoToHunk);
2089        cx.dispatch_action(editor::actions::GoToHunk);
2090        cx.dispatch_action(git::Restore);
2091        cx.dispatch_action(editor::actions::MoveToBeginning);
2092
2093        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2094    }
2095
2096    #[gpui::test]
2097    async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
2098        init_test(cx);
2099
2100        let fs = FakeFs::new(cx.executor());
2101        fs.insert_tree(
2102            path!("/project"),
2103            json!({
2104                ".git": {},
2105                "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
2106            }),
2107        )
2108        .await;
2109        fs.set_status_for_repo(
2110            Path::new(path!("/project/.git")),
2111            &[(
2112                "foo",
2113                UnmergedStatus {
2114                    first_head: UnmergedStatusCode::Updated,
2115                    second_head: UnmergedStatusCode::Updated,
2116                }
2117                .into(),
2118            )],
2119        );
2120        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2121        let (workspace, cx) =
2122            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2123        let diff = cx.new_window_entity(|window, cx| {
2124            ProjectDiff::new(project.clone(), workspace, window, cx)
2125        });
2126        cx.run_until_parked();
2127
2128        cx.update(|window, cx| {
2129            let editor = diff.read(cx).editor.read(cx).primary_editor().clone();
2130            let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
2131            assert_eq!(excerpt_ids.len(), 1);
2132            let excerpt_id = excerpt_ids[0];
2133            let buffer = editor
2134                .read(cx)
2135                .buffer()
2136                .read(cx)
2137                .all_buffers()
2138                .into_iter()
2139                .next()
2140                .unwrap();
2141            let buffer_id = buffer.read(cx).remote_id();
2142            let conflict_set = diff
2143                .read(cx)
2144                .editor
2145                .read(cx)
2146                .primary_editor()
2147                .read(cx)
2148                .addon::<ConflictAddon>()
2149                .unwrap()
2150                .conflict_set(buffer_id)
2151                .unwrap();
2152            assert!(conflict_set.read(cx).has_conflict);
2153            let snapshot = conflict_set.read(cx).snapshot();
2154            assert_eq!(snapshot.conflicts.len(), 1);
2155
2156            let ours_range = snapshot.conflicts[0].ours.clone();
2157
2158            resolve_conflict(
2159                editor.downgrade(),
2160                excerpt_id,
2161                snapshot.conflicts[0].clone(),
2162                vec![ours_range],
2163                window,
2164                cx,
2165            )
2166        })
2167        .await;
2168
2169        let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
2170        let contents = String::from_utf8(contents).unwrap();
2171        assert_eq!(contents, "ours\n");
2172    }
2173
2174    #[gpui::test]
2175    async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
2176        init_test(cx);
2177
2178        let fs = FakeFs::new(cx.executor());
2179        fs.insert_tree(
2180            path!("/project"),
2181            json!({
2182                ".git": {},
2183                "foo.txt": "
2184                    one
2185                    two
2186                    three
2187                    four
2188                    five
2189                    six
2190                    seven
2191                    eight
2192                    nine
2193                    ten
2194                    ELEVEN
2195                    twelve
2196                ".unindent()
2197            }),
2198        )
2199        .await;
2200        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2201        let (workspace, cx) =
2202            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2203        let diff = cx.new_window_entity(|window, cx| {
2204            ProjectDiff::new(project.clone(), workspace, window, cx)
2205        });
2206        cx.run_until_parked();
2207
2208        fs.set_head_and_index_for_repo(
2209            Path::new(path!("/project/.git")),
2210            &[(
2211                "foo.txt",
2212                "
2213                    one
2214                    two
2215                    three
2216                    four
2217                    five
2218                    six
2219                    seven
2220                    eight
2221                    nine
2222                    ten
2223                    eleven
2224                    twelve
2225                "
2226                .unindent(),
2227            )],
2228        );
2229        cx.run_until_parked();
2230
2231        let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2232
2233        assert_state_with_diff(
2234            &editor,
2235            cx,
2236            &"
2237                  ˇnine
2238                  ten
2239                - eleven
2240                + ELEVEN
2241                  twelve
2242            "
2243            .unindent(),
2244        );
2245
2246        // The project diff updates its excerpts when a new hunk appears in a buffer that already has a diff.
2247        let buffer = project
2248            .update(cx, |project, cx| {
2249                project.open_local_buffer(path!("/project/foo.txt"), cx)
2250            })
2251            .await
2252            .unwrap();
2253        buffer.update(cx, |buffer, cx| {
2254            buffer.edit_via_marked_text(
2255                &"
2256                    one
2257                    «TWO»
2258                    three
2259                    four
2260                    five
2261                    six
2262                    seven
2263                    eight
2264                    nine
2265                    ten
2266                    ELEVEN
2267                    twelve
2268                "
2269                .unindent(),
2270                None,
2271                cx,
2272            );
2273        });
2274        project
2275            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
2276            .await
2277            .unwrap();
2278        cx.run_until_parked();
2279
2280        assert_state_with_diff(
2281            &editor,
2282            cx,
2283            &"
2284                  one
2285                - two
2286                + TWO
2287                  three
2288                  four
2289                  five
2290                  ˇnine
2291                  ten
2292                - eleven
2293                + ELEVEN
2294                  twelve
2295            "
2296            .unindent(),
2297        );
2298    }
2299
2300    #[gpui::test]
2301    async fn test_branch_diff(cx: &mut TestAppContext) {
2302        init_test(cx);
2303
2304        let fs = FakeFs::new(cx.executor());
2305        fs.insert_tree(
2306            path!("/project"),
2307            json!({
2308                ".git": {},
2309                "a.txt": "C",
2310                "b.txt": "new",
2311                "c.txt": "in-merge-base-and-work-tree",
2312                "d.txt": "created-in-head",
2313            }),
2314        )
2315        .await;
2316        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2317        let (workspace, cx) =
2318            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2319        let diff = cx
2320            .update(|window, cx| {
2321                ProjectDiff::new_with_default_branch(project.clone(), workspace, window, cx)
2322            })
2323            .await
2324            .unwrap();
2325        cx.run_until_parked();
2326
2327        fs.set_head_for_repo(
2328            Path::new(path!("/project/.git")),
2329            &[("a.txt", "B".into()), ("d.txt", "created-in-head".into())],
2330            "sha",
2331        );
2332        // fs.set_index_for_repo(dot_git, index_state);
2333        fs.set_merge_base_content_for_repo(
2334            Path::new(path!("/project/.git")),
2335            &[
2336                ("a.txt", "A".into()),
2337                ("c.txt", "in-merge-base-and-work-tree".into()),
2338            ],
2339        );
2340        cx.run_until_parked();
2341
2342        let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2343
2344        assert_state_with_diff(
2345            &editor,
2346            cx,
2347            &"
2348                - A
2349                + ˇC
2350                + new
2351                + created-in-head"
2352                .unindent(),
2353        );
2354
2355        let statuses: HashMap<Arc<RelPath>, Option<FileStatus>> =
2356            editor.update(cx, |editor, cx| {
2357                editor
2358                    .buffer()
2359                    .read(cx)
2360                    .all_buffers()
2361                    .iter()
2362                    .map(|buffer| {
2363                        (
2364                            buffer.read(cx).file().unwrap().path().clone(),
2365                            editor.status_for_buffer_id(buffer.read(cx).remote_id(), cx),
2366                        )
2367                    })
2368                    .collect()
2369            });
2370
2371        assert_eq!(
2372            statuses,
2373            HashMap::from_iter([
2374                (
2375                    rel_path("a.txt").into_arc(),
2376                    Some(FileStatus::Tracked(TrackedStatus {
2377                        index_status: git::status::StatusCode::Modified,
2378                        worktree_status: git::status::StatusCode::Modified
2379                    }))
2380                ),
2381                (rel_path("b.txt").into_arc(), Some(FileStatus::Untracked)),
2382                (
2383                    rel_path("d.txt").into_arc(),
2384                    Some(FileStatus::Tracked(TrackedStatus {
2385                        index_status: git::status::StatusCode::Added,
2386                        worktree_status: git::status::StatusCode::Added
2387                    }))
2388                )
2389            ])
2390        );
2391    }
2392
2393    #[gpui::test]
2394    async fn test_update_on_uncommit(cx: &mut TestAppContext) {
2395        init_test(cx);
2396
2397        let fs = FakeFs::new(cx.executor());
2398        fs.insert_tree(
2399            path!("/project"),
2400            json!({
2401                ".git": {},
2402                "README.md": "# My cool project\n".to_owned()
2403            }),
2404        )
2405        .await;
2406        fs.set_head_and_index_for_repo(
2407            Path::new(path!("/project/.git")),
2408            &[("README.md", "# My cool project\n".to_owned())],
2409        );
2410        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
2411        let worktree_id = project.read_with(cx, |project, cx| {
2412            project.worktrees(cx).next().unwrap().read(cx).id()
2413        });
2414        let (workspace, cx) =
2415            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2416        cx.run_until_parked();
2417
2418        let _editor = workspace
2419            .update_in(cx, |workspace, window, cx| {
2420                workspace.open_path((worktree_id, rel_path("README.md")), None, true, window, cx)
2421            })
2422            .await
2423            .unwrap()
2424            .downcast::<Editor>()
2425            .unwrap();
2426
2427        cx.focus(&workspace);
2428        cx.update(|window, cx| {
2429            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2430        });
2431        cx.run_until_parked();
2432        let item = workspace.update(cx, |workspace, cx| {
2433            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2434        });
2435        cx.focus(&item);
2436        let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2437
2438        fs.set_head_and_index_for_repo(
2439            Path::new(path!("/project/.git")),
2440            &[(
2441                "README.md",
2442                "# My cool project\nDetails to come.\n".to_owned(),
2443            )],
2444        );
2445        cx.run_until_parked();
2446
2447        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2448
2449        cx.assert_excerpts_with_selections("[EXCERPT]\nˇ# My cool project\nDetails to come.\n");
2450    }
2451}