project_diff.rs

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