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