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