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