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