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