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