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::Result;
   8use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
   9use collections::HashSet;
  10use editor::{
  11    Editor, EditorEvent, SelectionEffects,
  12    actions::{GoToHunk, GoToPreviousHunk},
  13    multibuffer_context_lines,
  14    scroll::Autoscroll,
  15};
  16use futures::StreamExt;
  17use git::{
  18    Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll, UnstageAndNext,
  19    repository::{Branch, Upstream, UpstreamTracking, UpstreamTrackingStatus},
  20    status::FileStatus,
  21};
  22use gpui::{
  23    Action, AnyElement, AnyView, App, AppContext as _, AsyncWindowContext, Entity, EventEmitter,
  24    FocusHandle, Focusable, Render, Subscription, Task, WeakEntity, actions,
  25};
  26use language::{Anchor, Buffer, Capability, OffsetRangeExt};
  27use multi_buffer::{MultiBuffer, PathKey};
  28use project::{
  29    Project, ProjectPath,
  30    git_store::{GitStore, GitStoreEvent, RepositoryEvent},
  31};
  32use settings::{Settings, SettingsStore};
  33use std::any::{Any, TypeId};
  34use std::ops::Range;
  35use theme::ActiveTheme;
  36use ui::{KeyBinding, Tooltip, prelude::*, vertical_divider};
  37use util::ResultExt as _;
  38use workspace::{
  39    CloseActiveItem, ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation,
  40    ToolbarItemView, Workspace,
  41    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},
  42    searchable::SearchableItemHandle,
  43};
  44
  45actions!(
  46    git,
  47    [
  48        /// Shows the diff between the working directory and the index.
  49        Diff,
  50        /// Adds files to the git staging area.
  51        Add
  52    ]
  53);
  54
  55pub struct ProjectDiff {
  56    project: Entity<Project>,
  57    multibuffer: Entity<MultiBuffer>,
  58    editor: Entity<Editor>,
  59    git_store: Entity<GitStore>,
  60    workspace: WeakEntity<Workspace>,
  61    focus_handle: FocusHandle,
  62    update_needed: postage::watch::Sender<()>,
  63    pending_scroll: Option<PathKey>,
  64    _task: Task<Result<()>>,
  65    _subscription: Subscription,
  66}
  67
  68#[derive(Debug)]
  69struct DiffBuffer {
  70    path_key: PathKey,
  71    buffer: Entity<Buffer>,
  72    diff: Entity<BufferDiff>,
  73    file_status: FileStatus,
  74}
  75
  76const CONFLICT_NAMESPACE: u64 = 1;
  77const TRACKED_NAMESPACE: u64 = 2;
  78const NEW_NAMESPACE: u64 = 3;
  79
  80impl ProjectDiff {
  81    pub(crate) fn register(workspace: &mut Workspace, cx: &mut Context<Workspace>) {
  82        workspace.register_action(Self::deploy);
  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    pub fn deploy_at(
  99        workspace: &mut Workspace,
 100        entry: Option<GitStatusEntry>,
 101        window: &mut Window,
 102        cx: &mut Context<Workspace>,
 103    ) {
 104        telemetry::event!(
 105            "Git Diff Opened",
 106            source = if entry.is_some() {
 107                "Git Panel"
 108            } else {
 109                "Action"
 110            }
 111        );
 112        let project_diff = if let Some(existing) = workspace.item_of_type::<Self>(cx) {
 113            workspace.activate_item(&existing, true, true, window, cx);
 114            existing
 115        } else {
 116            let workspace_handle = cx.entity();
 117            let project_diff =
 118                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
 119            workspace.add_item_to_active_pane(
 120                Box::new(project_diff.clone()),
 121                None,
 122                true,
 123                window,
 124                cx,
 125            );
 126            project_diff
 127        };
 128        if let Some(entry) = entry {
 129            project_diff.update(cx, |project_diff, cx| {
 130                project_diff.move_to_entry(entry, window, cx);
 131            })
 132        }
 133    }
 134
 135    pub fn autoscroll(&self, cx: &mut Context<Self>) {
 136        self.editor.update(cx, |editor, cx| {
 137            editor.request_autoscroll(Autoscroll::fit(), cx);
 138        })
 139    }
 140
 141    fn new(
 142        project: Entity<Project>,
 143        workspace: Entity<Workspace>,
 144        window: &mut Window,
 145        cx: &mut Context<Self>,
 146    ) -> Self {
 147        let focus_handle = cx.focus_handle();
 148        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 149
 150        let editor = cx.new(|cx| {
 151            let mut diff_display_editor =
 152                Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
 153            diff_display_editor.disable_diagnostics(cx);
 154            diff_display_editor.set_expand_all_diff_hunks(cx);
 155            diff_display_editor.register_addon(GitPanelAddon {
 156                workspace: workspace.downgrade(),
 157            });
 158            diff_display_editor
 159        });
 160        window.defer(cx, {
 161            let workspace = workspace.clone();
 162            let editor = editor.clone();
 163            move |window, cx| {
 164                workspace.update(cx, |workspace, cx| {
 165                    editor.update(cx, |editor, cx| {
 166                        editor.added_to_workspace(workspace, window, cx);
 167                    })
 168                });
 169            }
 170        });
 171        cx.subscribe_in(&editor, window, Self::handle_editor_event)
 172            .detach();
 173
 174        let git_store = project.read(cx).git_store().clone();
 175        let git_store_subscription = cx.subscribe_in(
 176            &git_store,
 177            window,
 178            move |this, _git_store, event, _window, _cx| match event {
 179                GitStoreEvent::ActiveRepositoryChanged(_)
 180                | GitStoreEvent::RepositoryUpdated(_, RepositoryEvent::Updated { .. }, true)
 181                | GitStoreEvent::ConflictsUpdated => {
 182                    *this.update_needed.borrow_mut() = ();
 183                }
 184                _ => {}
 185            },
 186        );
 187
 188        let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
 189        let mut was_collapse_untracked_diff =
 190            GitPanelSettings::get_global(cx).collapse_untracked_diff;
 191        cx.observe_global::<SettingsStore>(move |this, cx| {
 192            let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
 193            let is_collapse_untracked_diff =
 194                GitPanelSettings::get_global(cx).collapse_untracked_diff;
 195            if is_sort_by_path != was_sort_by_path
 196                || is_collapse_untracked_diff != was_collapse_untracked_diff
 197            {
 198                *this.update_needed.borrow_mut() = ();
 199            }
 200            was_sort_by_path = is_sort_by_path;
 201            was_collapse_untracked_diff = is_collapse_untracked_diff;
 202        })
 203        .detach();
 204
 205        let (mut send, recv) = postage::watch::channel::<()>();
 206        let worker = window.spawn(cx, {
 207            let this = cx.weak_entity();
 208            async |cx| Self::handle_status_updates(this, recv, cx).await
 209        });
 210        // Kick off a refresh immediately
 211        *send.borrow_mut() = ();
 212
 213        Self {
 214            project,
 215            git_store: git_store.clone(),
 216            workspace: workspace.downgrade(),
 217            focus_handle,
 218            editor,
 219            multibuffer,
 220            pending_scroll: None,
 221            update_needed: send,
 222            _task: worker,
 223            _subscription: git_store_subscription,
 224        }
 225    }
 226
 227    pub fn move_to_entry(
 228        &mut self,
 229        entry: GitStatusEntry,
 230        window: &mut Window,
 231        cx: &mut Context<Self>,
 232    ) {
 233        let Some(git_repo) = self.git_store.read(cx).active_repository() else {
 234            return;
 235        };
 236        let repo = git_repo.read(cx);
 237
 238        let namespace = if repo.had_conflict_on_last_merge_head_change(&entry.repo_path) {
 239            CONFLICT_NAMESPACE
 240        } else if entry.status.is_created() {
 241            NEW_NAMESPACE
 242        } else {
 243            TRACKED_NAMESPACE
 244        };
 245
 246        let path_key = PathKey::namespaced(namespace, entry.repo_path.0);
 247
 248        self.move_to_path(path_key, window, cx)
 249    }
 250
 251    pub fn active_path(&self, cx: &App) -> Option<ProjectPath> {
 252        let editor = self.editor.read(cx);
 253        let position = editor.selections.newest_anchor().head();
 254        let multi_buffer = editor.buffer().read(cx);
 255        let (_, buffer, _) = multi_buffer.excerpt_containing(position, cx)?;
 256
 257        let file = buffer.read(cx).file()?;
 258        Some(ProjectPath {
 259            worktree_id: file.worktree_id(cx),
 260            path: file.path().clone(),
 261        })
 262    }
 263
 264    fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
 265        if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
 266            self.editor.update(cx, |editor, cx| {
 267                editor.change_selections(
 268                    SelectionEffects::scroll(Autoscroll::focused()),
 269                    window,
 270                    cx,
 271                    |s| {
 272                        s.select_ranges([position..position]);
 273                    },
 274                )
 275            });
 276        } else {
 277            self.pending_scroll = Some(path_key);
 278        }
 279    }
 280
 281    fn button_states(&self, cx: &App) -> ButtonStates {
 282        let editor = self.editor.read(cx);
 283        let snapshot = self.multibuffer.read(cx).snapshot(cx);
 284        let prev_next = snapshot.diff_hunks().nth(1).is_some();
 285        let mut selection = true;
 286
 287        let mut ranges = editor
 288            .selections
 289            .disjoint_anchor_ranges()
 290            .collect::<Vec<_>>();
 291        if !ranges.iter().any(|range| range.start != range.end) {
 292            selection = false;
 293            if let Some((excerpt_id, buffer, range)) = self.editor.read(cx).active_excerpt(cx) {
 294                ranges = vec![multi_buffer::Anchor::range_in_buffer(
 295                    excerpt_id,
 296                    buffer.read(cx).remote_id(),
 297                    range,
 298                )];
 299            } else {
 300                ranges = Vec::default();
 301            }
 302        }
 303        let mut has_staged_hunks = false;
 304        let mut has_unstaged_hunks = false;
 305        for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
 306            match hunk.secondary_status {
 307                DiffHunkSecondaryStatus::HasSecondaryHunk
 308                | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending => {
 309                    has_unstaged_hunks = true;
 310                }
 311                DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
 312                    has_staged_hunks = true;
 313                    has_unstaged_hunks = true;
 314                }
 315                DiffHunkSecondaryStatus::NoSecondaryHunk
 316                | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending => {
 317                    has_staged_hunks = true;
 318                }
 319            }
 320        }
 321        let mut stage_all = false;
 322        let mut unstage_all = false;
 323        self.workspace
 324            .read_with(cx, |workspace, cx| {
 325                if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
 326                    let git_panel = git_panel.read(cx);
 327                    stage_all = git_panel.can_stage_all();
 328                    unstage_all = git_panel.can_unstage_all();
 329                }
 330            })
 331            .ok();
 332
 333        ButtonStates {
 334            stage: has_unstaged_hunks,
 335            unstage: has_staged_hunks,
 336            prev_next,
 337            selection,
 338            stage_all,
 339            unstage_all,
 340        }
 341    }
 342
 343    fn handle_editor_event(
 344        &mut self,
 345        editor: &Entity<Editor>,
 346        event: &EditorEvent,
 347        window: &mut Window,
 348        cx: &mut Context<Self>,
 349    ) {
 350        if let EditorEvent::SelectionsChanged { local: true } = event {
 351            let Some(project_path) = self.active_path(cx) else {
 352                return;
 353            };
 354            self.workspace
 355                .update(cx, |workspace, cx| {
 356                    if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
 357                        git_panel.update(cx, |git_panel, cx| {
 358                            git_panel.select_entry_by_path(project_path, window, cx)
 359                        })
 360                    }
 361                })
 362                .ok();
 363        }
 364        if editor.focus_handle(cx).contains_focused(window, cx)
 365            && self.multibuffer.read(cx).is_empty()
 366        {
 367            self.focus_handle.focus(window)
 368        }
 369    }
 370
 371    fn load_buffers(&mut self, cx: &mut Context<Self>) -> Vec<Task<Result<DiffBuffer>>> {
 372        let Some(repo) = self.git_store.read(cx).active_repository() else {
 373            self.multibuffer.update(cx, |multibuffer, cx| {
 374                multibuffer.clear(cx);
 375            });
 376            return vec![];
 377        };
 378
 379        let mut previous_paths = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
 380
 381        let mut result = vec![];
 382        repo.update(cx, |repo, cx| {
 383            for entry in repo.cached_status() {
 384                if !entry.status.has_changes() {
 385                    continue;
 386                }
 387                let Some(project_path) = repo.repo_path_to_project_path(&entry.repo_path, cx)
 388                else {
 389                    continue;
 390                };
 391                let namespace = if GitPanelSettings::get_global(cx).sort_by_path {
 392                    TRACKED_NAMESPACE
 393                } else if repo.had_conflict_on_last_merge_head_change(&entry.repo_path) {
 394                    CONFLICT_NAMESPACE
 395                } else if entry.status.is_created() {
 396                    NEW_NAMESPACE
 397                } else {
 398                    TRACKED_NAMESPACE
 399                };
 400                let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
 401
 402                previous_paths.remove(&path_key);
 403                let load_buffer = self
 404                    .project
 405                    .update(cx, |project, cx| project.open_buffer(project_path, cx));
 406
 407                let project = self.project.clone();
 408                result.push(cx.spawn(async move |_, cx| {
 409                    let buffer = load_buffer.await?;
 410                    let changes = project
 411                        .update(cx, |project, cx| {
 412                            project.open_uncommitted_diff(buffer.clone(), cx)
 413                        })?
 414                        .await?;
 415                    Ok(DiffBuffer {
 416                        path_key,
 417                        buffer,
 418                        diff: changes,
 419                        file_status: entry.status,
 420                    })
 421                }));
 422            }
 423        });
 424        self.multibuffer.update(cx, |multibuffer, cx| {
 425            for path in previous_paths {
 426                multibuffer.remove_excerpts_for_path(path, cx);
 427            }
 428        });
 429        result
 430    }
 431
 432    fn register_buffer(
 433        &mut self,
 434        diff_buffer: DiffBuffer,
 435        window: &mut Window,
 436        cx: &mut Context<Self>,
 437    ) {
 438        let path_key = diff_buffer.path_key;
 439        let buffer = diff_buffer.buffer;
 440        let diff = diff_buffer.diff;
 441
 442        let conflict_addon = self
 443            .editor
 444            .read(cx)
 445            .addon::<ConflictAddon>()
 446            .expect("project diff editor should have a conflict addon");
 447
 448        let snapshot = buffer.read(cx).snapshot();
 449        let diff = diff.read(cx);
 450        let diff_hunk_ranges = diff
 451            .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
 452            .map(|diff_hunk| diff_hunk.buffer_range);
 453        let conflicts = conflict_addon
 454            .conflict_set(snapshot.remote_id())
 455            .map(|conflict_set| conflict_set.read(cx).snapshot().conflicts)
 456            .unwrap_or_default();
 457        let conflicts = conflicts.iter().map(|conflict| conflict.range.clone());
 458
 459        let excerpt_ranges = merge_anchor_ranges(diff_hunk_ranges, conflicts, &snapshot)
 460            .map(|range| range.to_point(&snapshot))
 461            .collect::<Vec<_>>();
 462
 463        let (was_empty, is_excerpt_newly_added) = self.multibuffer.update(cx, |multibuffer, cx| {
 464            let was_empty = multibuffer.is_empty();
 465            let (_, is_newly_added) = multibuffer.set_excerpts_for_path(
 466                path_key.clone(),
 467                buffer,
 468                excerpt_ranges,
 469                multibuffer_context_lines(cx),
 470                cx,
 471            );
 472            (was_empty, is_newly_added)
 473        });
 474
 475        self.editor.update(cx, |editor, cx| {
 476            if was_empty {
 477                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
 478                    // TODO select the very beginning (possibly inside a deletion)
 479                    selections.select_ranges([0..0])
 480                });
 481            }
 482            if is_excerpt_newly_added
 483                && (diff_buffer.file_status.is_deleted()
 484                    || (diff_buffer.file_status.is_untracked()
 485                        && GitPanelSettings::get_global(cx).collapse_untracked_diff))
 486            {
 487                editor.fold_buffer(snapshot.text.remote_id(), cx)
 488            }
 489        });
 490
 491        if self.multibuffer.read(cx).is_empty()
 492            && self
 493                .editor
 494                .read(cx)
 495                .focus_handle(cx)
 496                .contains_focused(window, cx)
 497        {
 498            self.focus_handle.focus(window);
 499        } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
 500            self.editor.update(cx, |editor, cx| {
 501                editor.focus_handle(cx).focus(window);
 502            });
 503        }
 504        if self.pending_scroll.as_ref() == Some(&path_key) {
 505            self.move_to_path(path_key, window, cx);
 506        }
 507    }
 508
 509    pub async fn handle_status_updates(
 510        this: WeakEntity<Self>,
 511        mut recv: postage::watch::Receiver<()>,
 512        cx: &mut AsyncWindowContext,
 513    ) -> Result<()> {
 514        while (recv.next().await).is_some() {
 515            let buffers_to_load = this.update(cx, |this, cx| this.load_buffers(cx))?;
 516            for buffer_to_load in buffers_to_load {
 517                if let Some(buffer) = buffer_to_load.await.log_err() {
 518                    cx.update(|window, cx| {
 519                        this.update(cx, |this, cx| this.register_buffer(buffer, window, cx))
 520                            .ok();
 521                    })?;
 522                }
 523            }
 524            this.update(cx, |this, cx| {
 525                this.pending_scroll.take();
 526                cx.notify();
 527            })?;
 528        }
 529
 530        Ok(())
 531    }
 532
 533    #[cfg(any(test, feature = "test-support"))]
 534    pub fn excerpt_paths(&self, cx: &App) -> Vec<std::sync::Arc<util::rel_path::RelPath>> {
 535        self.multibuffer
 536            .read(cx)
 537            .excerpt_paths()
 538            .map(|key| key.path())
 539            .cloned()
 540            .collect()
 541    }
 542}
 543
 544impl EventEmitter<EditorEvent> for ProjectDiff {}
 545
 546impl Focusable for ProjectDiff {
 547    fn focus_handle(&self, cx: &App) -> FocusHandle {
 548        if self.multibuffer.read(cx).is_empty() {
 549            self.focus_handle.clone()
 550        } else {
 551            self.editor.focus_handle(cx)
 552        }
 553    }
 554}
 555
 556impl Item for ProjectDiff {
 557    type Event = EditorEvent;
 558
 559    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 560        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
 561    }
 562
 563    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 564        Editor::to_item_events(event, f)
 565    }
 566
 567    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 568        self.editor
 569            .update(cx, |editor, cx| editor.deactivated(window, cx));
 570    }
 571
 572    fn navigate(
 573        &mut self,
 574        data: Box<dyn Any>,
 575        window: &mut Window,
 576        cx: &mut Context<Self>,
 577    ) -> bool {
 578        self.editor
 579            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 580    }
 581
 582    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 583        Some("Project Diff".into())
 584    }
 585
 586    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
 587        Label::new("Uncommitted Changes")
 588            .color(if params.selected {
 589                Color::Default
 590            } else {
 591                Color::Muted
 592            })
 593            .into_any_element()
 594    }
 595
 596    fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {
 597        "Uncommitted Changes".into()
 598    }
 599
 600    fn telemetry_event_text(&self) -> Option<&'static str> {
 601        Some("Project Diff Opened")
 602    }
 603
 604    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 605        Some(Box::new(self.editor.clone()))
 606    }
 607
 608    fn for_each_project_item(
 609        &self,
 610        cx: &App,
 611        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 612    ) {
 613        self.editor.for_each_project_item(cx, f)
 614    }
 615
 616    fn is_singleton(&self, _: &App) -> bool {
 617        false
 618    }
 619
 620    fn set_nav_history(
 621        &mut self,
 622        nav_history: ItemNavHistory,
 623        _: &mut Window,
 624        cx: &mut Context<Self>,
 625    ) {
 626        self.editor.update(cx, |editor, _| {
 627            editor.set_nav_history(Some(nav_history));
 628        });
 629    }
 630
 631    fn clone_on_split(
 632        &self,
 633        _workspace_id: Option<workspace::WorkspaceId>,
 634        window: &mut Window,
 635        cx: &mut Context<Self>,
 636    ) -> Option<Entity<Self>>
 637    where
 638        Self: Sized,
 639    {
 640        let workspace = self.workspace.upgrade()?;
 641        Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
 642    }
 643
 644    fn is_dirty(&self, cx: &App) -> bool {
 645        self.multibuffer.read(cx).is_dirty(cx)
 646    }
 647
 648    fn has_conflict(&self, cx: &App) -> bool {
 649        self.multibuffer.read(cx).has_conflict(cx)
 650    }
 651
 652    fn can_save(&self, _: &App) -> bool {
 653        true
 654    }
 655
 656    fn save(
 657        &mut self,
 658        options: SaveOptions,
 659        project: Entity<Project>,
 660        window: &mut Window,
 661        cx: &mut Context<Self>,
 662    ) -> Task<Result<()>> {
 663        self.editor.save(options, project, window, cx)
 664    }
 665
 666    fn save_as(
 667        &mut self,
 668        _: Entity<Project>,
 669        _: ProjectPath,
 670        _window: &mut Window,
 671        _: &mut Context<Self>,
 672    ) -> Task<Result<()>> {
 673        unreachable!()
 674    }
 675
 676    fn reload(
 677        &mut self,
 678        project: Entity<Project>,
 679        window: &mut Window,
 680        cx: &mut Context<Self>,
 681    ) -> Task<Result<()>> {
 682        self.editor.reload(project, window, cx)
 683    }
 684
 685    fn act_as_type<'a>(
 686        &'a self,
 687        type_id: TypeId,
 688        self_handle: &'a Entity<Self>,
 689        _: &'a App,
 690    ) -> Option<AnyView> {
 691        if type_id == TypeId::of::<Self>() {
 692            Some(self_handle.to_any())
 693        } else if type_id == TypeId::of::<Editor>() {
 694            Some(self.editor.to_any())
 695        } else {
 696            None
 697        }
 698    }
 699
 700    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 701        ToolbarItemLocation::PrimaryLeft
 702    }
 703
 704    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 705        self.editor.breadcrumbs(theme, cx)
 706    }
 707
 708    fn added_to_workspace(
 709        &mut self,
 710        workspace: &mut Workspace,
 711        window: &mut Window,
 712        cx: &mut Context<Self>,
 713    ) {
 714        self.editor.update(cx, |editor, cx| {
 715            editor.added_to_workspace(workspace, window, cx)
 716        });
 717    }
 718}
 719
 720impl Render for ProjectDiff {
 721    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 722        let is_empty = self.multibuffer.read(cx).is_empty();
 723
 724        div()
 725            .track_focus(&self.focus_handle)
 726            .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
 727            .bg(cx.theme().colors().editor_background)
 728            .flex()
 729            .items_center()
 730            .justify_center()
 731            .size_full()
 732            .when(is_empty, |el| {
 733                let remote_button = if let Some(panel) = self
 734                    .workspace
 735                    .upgrade()
 736                    .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
 737                {
 738                    panel.update(cx, |panel, cx| panel.render_remote_button(cx))
 739                } else {
 740                    None
 741                };
 742                let keybinding_focus_handle = self.focus_handle(cx);
 743                el.child(
 744                    v_flex()
 745                        .gap_1()
 746                        .child(
 747                            h_flex()
 748                                .justify_around()
 749                                .child(Label::new("No uncommitted changes")),
 750                        )
 751                        .map(|el| match remote_button {
 752                            Some(button) => el.child(h_flex().justify_around().child(button)),
 753                            None => el.child(
 754                                h_flex()
 755                                    .justify_around()
 756                                    .child(Label::new("Remote up to date")),
 757                            ),
 758                        })
 759                        .child(
 760                            h_flex().justify_around().mt_1().child(
 761                                Button::new("project-diff-close-button", "Close")
 762                                    // .style(ButtonStyle::Transparent)
 763                                    .key_binding(KeyBinding::for_action_in(
 764                                        &CloseActiveItem::default(),
 765                                        &keybinding_focus_handle,
 766                                        window,
 767                                        cx,
 768                                    ))
 769                                    .on_click(move |_, window, cx| {
 770                                        window.focus(&keybinding_focus_handle);
 771                                        window.dispatch_action(
 772                                            Box::new(CloseActiveItem::default()),
 773                                            cx,
 774                                        );
 775                                    }),
 776                            ),
 777                        ),
 778                )
 779            })
 780            .when(!is_empty, |el| el.child(self.editor.clone()))
 781    }
 782}
 783
 784impl SerializableItem for ProjectDiff {
 785    fn serialized_item_kind() -> &'static str {
 786        "ProjectDiff"
 787    }
 788
 789    fn cleanup(
 790        _: workspace::WorkspaceId,
 791        _: Vec<workspace::ItemId>,
 792        _: &mut Window,
 793        _: &mut App,
 794    ) -> Task<Result<()>> {
 795        Task::ready(Ok(()))
 796    }
 797
 798    fn deserialize(
 799        _project: Entity<Project>,
 800        workspace: WeakEntity<Workspace>,
 801        _workspace_id: workspace::WorkspaceId,
 802        _item_id: workspace::ItemId,
 803        window: &mut Window,
 804        cx: &mut App,
 805    ) -> Task<Result<Entity<Self>>> {
 806        window.spawn(cx, async move |cx| {
 807            workspace.update_in(cx, |workspace, window, cx| {
 808                let workspace_handle = cx.entity();
 809                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
 810            })
 811        })
 812    }
 813
 814    fn serialize(
 815        &mut self,
 816        _workspace: &mut Workspace,
 817        _item_id: workspace::ItemId,
 818        _closing: bool,
 819        _window: &mut Window,
 820        _cx: &mut Context<Self>,
 821    ) -> Option<Task<Result<()>>> {
 822        None
 823    }
 824
 825    fn should_serialize(&self, _: &Self::Event) -> bool {
 826        false
 827    }
 828}
 829
 830pub struct ProjectDiffToolbar {
 831    project_diff: Option<WeakEntity<ProjectDiff>>,
 832    workspace: WeakEntity<Workspace>,
 833}
 834
 835impl ProjectDiffToolbar {
 836    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
 837        Self {
 838            project_diff: None,
 839            workspace: workspace.weak_handle(),
 840        }
 841    }
 842
 843    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
 844        self.project_diff.as_ref()?.upgrade()
 845    }
 846
 847    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 848        if let Some(project_diff) = self.project_diff(cx) {
 849            project_diff.focus_handle(cx).focus(window);
 850        }
 851        let action = action.boxed_clone();
 852        cx.defer(move |cx| {
 853            cx.dispatch_action(action.as_ref());
 854        })
 855    }
 856
 857    fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 858        self.workspace
 859            .update(cx, |workspace, cx| {
 860                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
 861                    panel.update(cx, |panel, cx| {
 862                        panel.stage_all(&Default::default(), window, cx);
 863                    });
 864                }
 865            })
 866            .ok();
 867    }
 868
 869    fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 870        self.workspace
 871            .update(cx, |workspace, cx| {
 872                let Some(panel) = workspace.panel::<GitPanel>(cx) else {
 873                    return;
 874                };
 875                panel.update(cx, |panel, cx| {
 876                    panel.unstage_all(&Default::default(), window, cx);
 877                });
 878            })
 879            .ok();
 880    }
 881}
 882
 883impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
 884
 885impl ToolbarItemView for ProjectDiffToolbar {
 886    fn set_active_pane_item(
 887        &mut self,
 888        active_pane_item: Option<&dyn ItemHandle>,
 889        _: &mut Window,
 890        cx: &mut Context<Self>,
 891    ) -> ToolbarItemLocation {
 892        self.project_diff = active_pane_item
 893            .and_then(|item| item.act_as::<ProjectDiff>(cx))
 894            .map(|entity| entity.downgrade());
 895        if self.project_diff.is_some() {
 896            ToolbarItemLocation::PrimaryRight
 897        } else {
 898            ToolbarItemLocation::Hidden
 899        }
 900    }
 901
 902    fn pane_focus_update(
 903        &mut self,
 904        _pane_focused: bool,
 905        _window: &mut Window,
 906        _cx: &mut Context<Self>,
 907    ) {
 908    }
 909}
 910
 911struct ButtonStates {
 912    stage: bool,
 913    unstage: bool,
 914    prev_next: bool,
 915    selection: bool,
 916    stage_all: bool,
 917    unstage_all: bool,
 918}
 919
 920impl Render for ProjectDiffToolbar {
 921    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 922        let Some(project_diff) = self.project_diff(cx) else {
 923            return div();
 924        };
 925        let focus_handle = project_diff.focus_handle(cx);
 926        let button_states = project_diff.read(cx).button_states(cx);
 927
 928        h_group_xl()
 929            .my_neg_1()
 930            .py_1()
 931            .items_center()
 932            .flex_wrap()
 933            .justify_between()
 934            .child(
 935                h_group_sm()
 936                    .when(button_states.selection, |el| {
 937                        el.child(
 938                            Button::new("stage", "Toggle Staged")
 939                                .tooltip(Tooltip::for_action_title_in(
 940                                    "Toggle Staged",
 941                                    &ToggleStaged,
 942                                    &focus_handle,
 943                                ))
 944                                .disabled(!button_states.stage && !button_states.unstage)
 945                                .on_click(cx.listener(|this, _, window, cx| {
 946                                    this.dispatch_action(&ToggleStaged, window, cx)
 947                                })),
 948                        )
 949                    })
 950                    .when(!button_states.selection, |el| {
 951                        el.child(
 952                            Button::new("stage", "Stage")
 953                                .tooltip(Tooltip::for_action_title_in(
 954                                    "Stage and go to next hunk",
 955                                    &StageAndNext,
 956                                    &focus_handle,
 957                                ))
 958                                .on_click(cx.listener(|this, _, window, cx| {
 959                                    this.dispatch_action(&StageAndNext, window, cx)
 960                                })),
 961                        )
 962                        .child(
 963                            Button::new("unstage", "Unstage")
 964                                .tooltip(Tooltip::for_action_title_in(
 965                                    "Unstage and go to next hunk",
 966                                    &UnstageAndNext,
 967                                    &focus_handle,
 968                                ))
 969                                .on_click(cx.listener(|this, _, window, cx| {
 970                                    this.dispatch_action(&UnstageAndNext, window, cx)
 971                                })),
 972                        )
 973                    }),
 974            )
 975            // n.b. the only reason these arrows are here is because we don't
 976            // support "undo" for staging so we need a way to go back.
 977            .child(
 978                h_group_sm()
 979                    .child(
 980                        IconButton::new("up", IconName::ArrowUp)
 981                            .shape(ui::IconButtonShape::Square)
 982                            .tooltip(Tooltip::for_action_title_in(
 983                                "Go to previous hunk",
 984                                &GoToPreviousHunk,
 985                                &focus_handle,
 986                            ))
 987                            .disabled(!button_states.prev_next)
 988                            .on_click(cx.listener(|this, _, window, cx| {
 989                                this.dispatch_action(&GoToPreviousHunk, window, cx)
 990                            })),
 991                    )
 992                    .child(
 993                        IconButton::new("down", IconName::ArrowDown)
 994                            .shape(ui::IconButtonShape::Square)
 995                            .tooltip(Tooltip::for_action_title_in(
 996                                "Go to next hunk",
 997                                &GoToHunk,
 998                                &focus_handle,
 999                            ))
1000                            .disabled(!button_states.prev_next)
1001                            .on_click(cx.listener(|this, _, window, cx| {
1002                                this.dispatch_action(&GoToHunk, window, cx)
1003                            })),
1004                    ),
1005            )
1006            .child(vertical_divider())
1007            .child(
1008                h_group_sm()
1009                    .when(
1010                        button_states.unstage_all && !button_states.stage_all,
1011                        |el| {
1012                            el.child(
1013                                Button::new("unstage-all", "Unstage All")
1014                                    .tooltip(Tooltip::for_action_title_in(
1015                                        "Unstage all changes",
1016                                        &UnstageAll,
1017                                        &focus_handle,
1018                                    ))
1019                                    .on_click(cx.listener(|this, _, window, cx| {
1020                                        this.unstage_all(window, cx)
1021                                    })),
1022                            )
1023                        },
1024                    )
1025                    .when(
1026                        !button_states.unstage_all || button_states.stage_all,
1027                        |el| {
1028                            el.child(
1029                                // todo make it so that changing to say "Unstaged"
1030                                // doesn't change the position.
1031                                div().child(
1032                                    Button::new("stage-all", "Stage All")
1033                                        .disabled(!button_states.stage_all)
1034                                        .tooltip(Tooltip::for_action_title_in(
1035                                            "Stage all changes",
1036                                            &StageAll,
1037                                            &focus_handle,
1038                                        ))
1039                                        .on_click(cx.listener(|this, _, window, cx| {
1040                                            this.stage_all(window, cx)
1041                                        })),
1042                                ),
1043                            )
1044                        },
1045                    )
1046                    .child(
1047                        Button::new("commit", "Commit")
1048                            .tooltip(Tooltip::for_action_title_in(
1049                                "Commit",
1050                                &Commit,
1051                                &focus_handle,
1052                            ))
1053                            .on_click(cx.listener(|this, _, window, cx| {
1054                                this.dispatch_action(&Commit, window, cx);
1055                            })),
1056                    ),
1057            )
1058    }
1059}
1060
1061#[derive(IntoElement, RegisterComponent)]
1062pub struct ProjectDiffEmptyState {
1063    pub no_repo: bool,
1064    pub can_push_and_pull: bool,
1065    pub focus_handle: Option<FocusHandle>,
1066    pub current_branch: Option<Branch>,
1067    // has_pending_commits: bool,
1068    // ahead_of_remote: bool,
1069    // no_git_repository: bool,
1070}
1071
1072impl RenderOnce for ProjectDiffEmptyState {
1073    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1074        let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1075            matches!(self.current_branch, Some(Branch {
1076                    upstream:
1077                        Some(Upstream {
1078                            tracking:
1079                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1080                                    ahead, behind, ..
1081                                }),
1082                            ..
1083                        }),
1084                    ..
1085                }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1086        };
1087
1088        let change_count = |current_branch: &Branch| -> (usize, usize) {
1089            match current_branch {
1090                Branch {
1091                    upstream:
1092                        Some(Upstream {
1093                            tracking:
1094                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1095                                    ahead, behind, ..
1096                                }),
1097                            ..
1098                        }),
1099                    ..
1100                } => (*ahead as usize, *behind as usize),
1101                _ => (0, 0),
1102            }
1103        };
1104
1105        let not_ahead_or_behind = status_against_remote(0, 0);
1106        let ahead_of_remote = status_against_remote(1, 0);
1107        let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1108            branch.upstream.is_none()
1109        } else {
1110            false
1111        };
1112
1113        let has_branch_container = |branch: &Branch| {
1114            h_flex()
1115                .max_w(px(420.))
1116                .bg(cx.theme().colors().text.opacity(0.05))
1117                .border_1()
1118                .border_color(cx.theme().colors().border)
1119                .rounded_sm()
1120                .gap_8()
1121                .px_6()
1122                .py_4()
1123                .map(|this| {
1124                    if ahead_of_remote {
1125                        let ahead_count = change_count(branch).0;
1126                        let ahead_string = format!("{} Commits Ahead", ahead_count);
1127                        this.child(
1128                            v_flex()
1129                                .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1130                                .child(
1131                                    Label::new(format!("Push your changes to {}", branch.name()))
1132                                        .color(Color::Muted),
1133                                ),
1134                        )
1135                        .child(div().child(render_push_button(
1136                            self.focus_handle,
1137                            "push".into(),
1138                            ahead_count as u32,
1139                        )))
1140                    } else if branch_not_on_remote {
1141                        this.child(
1142                            v_flex()
1143                                .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1144                                .child(
1145                                    Label::new(format!("Create {} on remote", branch.name()))
1146                                        .color(Color::Muted),
1147                                ),
1148                        )
1149                        .child(
1150                            div().child(render_publish_button(self.focus_handle, "publish".into())),
1151                        )
1152                    } else {
1153                        this.child(Label::new("Remote status unknown").color(Color::Muted))
1154                    }
1155                })
1156        };
1157
1158        v_flex().size_full().items_center().justify_center().child(
1159            v_flex()
1160                .gap_1()
1161                .when(self.no_repo, |this| {
1162                    // TODO: add git init
1163                    this.text_center()
1164                        .child(Label::new("No Repository").color(Color::Muted))
1165                })
1166                .map(|this| {
1167                    if not_ahead_or_behind && self.current_branch.is_some() {
1168                        this.text_center()
1169                            .child(Label::new("No Changes").color(Color::Muted))
1170                    } else {
1171                        this.when_some(self.current_branch.as_ref(), |this, branch| {
1172                            this.child(has_branch_container(branch))
1173                        })
1174                    }
1175                }),
1176        )
1177    }
1178}
1179
1180mod preview {
1181    use git::repository::{
1182        Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1183    };
1184    use ui::prelude::*;
1185
1186    use super::ProjectDiffEmptyState;
1187
1188    // View this component preview using `workspace: open component-preview`
1189    impl Component for ProjectDiffEmptyState {
1190        fn scope() -> ComponentScope {
1191            ComponentScope::VersionControl
1192        }
1193
1194        fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1195            let unknown_upstream: Option<UpstreamTracking> = None;
1196            let ahead_of_upstream: Option<UpstreamTracking> = Some(
1197                UpstreamTrackingStatus {
1198                    ahead: 2,
1199                    behind: 0,
1200                }
1201                .into(),
1202            );
1203
1204            let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1205                UpstreamTrackingStatus {
1206                    ahead: 0,
1207                    behind: 0,
1208                }
1209                .into(),
1210            );
1211
1212            fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1213                Branch {
1214                    is_head: true,
1215                    ref_name: "some-branch".into(),
1216                    upstream: upstream.map(|tracking| Upstream {
1217                        ref_name: "origin/some-branch".into(),
1218                        tracking,
1219                    }),
1220                    most_recent_commit: Some(CommitSummary {
1221                        sha: "abc123".into(),
1222                        subject: "Modify stuff".into(),
1223                        commit_timestamp: 1710932954,
1224                        author_name: "John Doe".into(),
1225                        has_parent: true,
1226                    }),
1227                }
1228            }
1229
1230            let no_repo_state = ProjectDiffEmptyState {
1231                no_repo: true,
1232                can_push_and_pull: false,
1233                focus_handle: None,
1234                current_branch: None,
1235            };
1236
1237            let no_changes_state = ProjectDiffEmptyState {
1238                no_repo: false,
1239                can_push_and_pull: true,
1240                focus_handle: None,
1241                current_branch: Some(branch(not_ahead_or_behind_upstream)),
1242            };
1243
1244            let ahead_of_upstream_state = ProjectDiffEmptyState {
1245                no_repo: false,
1246                can_push_and_pull: true,
1247                focus_handle: None,
1248                current_branch: Some(branch(ahead_of_upstream)),
1249            };
1250
1251            let unknown_upstream_state = ProjectDiffEmptyState {
1252                no_repo: false,
1253                can_push_and_pull: true,
1254                focus_handle: None,
1255                current_branch: Some(branch(unknown_upstream)),
1256            };
1257
1258            let (width, height) = (px(480.), px(320.));
1259
1260            Some(
1261                v_flex()
1262                    .gap_6()
1263                    .children(vec![
1264                        example_group(vec![
1265                            single_example(
1266                                "No Repo",
1267                                div()
1268                                    .w(width)
1269                                    .h(height)
1270                                    .child(no_repo_state)
1271                                    .into_any_element(),
1272                            ),
1273                            single_example(
1274                                "No Changes",
1275                                div()
1276                                    .w(width)
1277                                    .h(height)
1278                                    .child(no_changes_state)
1279                                    .into_any_element(),
1280                            ),
1281                            single_example(
1282                                "Unknown Upstream",
1283                                div()
1284                                    .w(width)
1285                                    .h(height)
1286                                    .child(unknown_upstream_state)
1287                                    .into_any_element(),
1288                            ),
1289                            single_example(
1290                                "Ahead of Remote",
1291                                div()
1292                                    .w(width)
1293                                    .h(height)
1294                                    .child(ahead_of_upstream_state)
1295                                    .into_any_element(),
1296                            ),
1297                        ])
1298                        .vertical(),
1299                    ])
1300                    .into_any_element(),
1301            )
1302        }
1303    }
1304}
1305
1306fn merge_anchor_ranges<'a>(
1307    left: impl 'a + Iterator<Item = Range<Anchor>>,
1308    right: impl 'a + Iterator<Item = Range<Anchor>>,
1309    snapshot: &'a language::BufferSnapshot,
1310) -> impl 'a + Iterator<Item = Range<Anchor>> {
1311    let mut left = left.fuse().peekable();
1312    let mut right = right.fuse().peekable();
1313
1314    std::iter::from_fn(move || {
1315        let Some(left_range) = left.peek() else {
1316            return right.next();
1317        };
1318        let Some(right_range) = right.peek() else {
1319            return left.next();
1320        };
1321
1322        let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1323            left.next().unwrap()
1324        } else {
1325            right.next().unwrap()
1326        };
1327
1328        // Extend the basic range while there's overlap with a range from either stream.
1329        loop {
1330            if let Some(left_range) = left
1331                .peek()
1332                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1333                .cloned()
1334            {
1335                left.next();
1336                next_range.end = left_range.end;
1337            } else if let Some(right_range) = right
1338                .peek()
1339                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1340                .cloned()
1341            {
1342                right.next();
1343                next_range.end = right_range.end;
1344            } else {
1345                break;
1346            }
1347        }
1348
1349        Some(next_range)
1350    })
1351}
1352
1353#[cfg(not(target_os = "windows"))]
1354#[cfg(test)]
1355mod tests {
1356    use db::indoc;
1357    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1358    use git::status::{UnmergedStatus, UnmergedStatusCode};
1359    use gpui::TestAppContext;
1360    use project::FakeFs;
1361    use serde_json::json;
1362    use settings::SettingsStore;
1363    use std::path::Path;
1364    use unindent::Unindent as _;
1365    use util::{path, rel_path::rel_path};
1366
1367    use super::*;
1368
1369    #[ctor::ctor]
1370    fn init_logger() {
1371        zlog::init_test();
1372    }
1373
1374    fn init_test(cx: &mut TestAppContext) {
1375        cx.update(|cx| {
1376            let store = SettingsStore::test(cx);
1377            cx.set_global(store);
1378            theme::init(theme::LoadThemes::JustBase, cx);
1379            language::init(cx);
1380            Project::init_settings(cx);
1381            workspace::init_settings(cx);
1382            editor::init(cx);
1383            crate::init(cx);
1384        });
1385    }
1386
1387    #[gpui::test]
1388    async fn test_save_after_restore(cx: &mut TestAppContext) {
1389        init_test(cx);
1390
1391        let fs = FakeFs::new(cx.executor());
1392        fs.insert_tree(
1393            path!("/project"),
1394            json!({
1395                ".git": {},
1396                "foo.txt": "FOO\n",
1397            }),
1398        )
1399        .await;
1400        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1401        let (workspace, cx) =
1402            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1403        let diff = cx.new_window_entity(|window, cx| {
1404            ProjectDiff::new(project.clone(), workspace, window, cx)
1405        });
1406        cx.run_until_parked();
1407
1408        fs.set_head_for_repo(
1409            path!("/project/.git").as_ref(),
1410            &[("foo.txt", "foo\n".into())],
1411            "deadbeef",
1412        );
1413        fs.set_index_for_repo(
1414            path!("/project/.git").as_ref(),
1415            &[("foo.txt", "foo\n".into())],
1416        );
1417        cx.run_until_parked();
1418
1419        let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1420        assert_state_with_diff(
1421            &editor,
1422            cx,
1423            &"
1424                - foo
1425                + ˇFOO
1426            "
1427            .unindent(),
1428        );
1429
1430        editor.update_in(cx, |editor, window, cx| {
1431            editor.git_restore(&Default::default(), window, cx);
1432        });
1433        cx.run_until_parked();
1434
1435        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1436
1437        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1438        assert_eq!(text, "foo\n");
1439    }
1440
1441    #[gpui::test]
1442    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1443        init_test(cx);
1444
1445        let fs = FakeFs::new(cx.executor());
1446        fs.insert_tree(
1447            path!("/project"),
1448            json!({
1449                ".git": {},
1450                "bar": "BAR\n",
1451                "foo": "FOO\n",
1452            }),
1453        )
1454        .await;
1455        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1456        let (workspace, cx) =
1457            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1458        let diff = cx.new_window_entity(|window, cx| {
1459            ProjectDiff::new(project.clone(), workspace, window, cx)
1460        });
1461        cx.run_until_parked();
1462
1463        fs.set_head_and_index_for_repo(
1464            path!("/project/.git").as_ref(),
1465            &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1466        );
1467        cx.run_until_parked();
1468
1469        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1470            diff.move_to_path(
1471                PathKey::namespaced(TRACKED_NAMESPACE, rel_path("foo").into_arc()),
1472                window,
1473                cx,
1474            );
1475            diff.editor.clone()
1476        });
1477        assert_state_with_diff(
1478            &editor,
1479            cx,
1480            &"
1481                - bar
1482                + BAR
1483
1484                - ˇfoo
1485                + FOO
1486            "
1487            .unindent(),
1488        );
1489
1490        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1491            diff.move_to_path(
1492                PathKey::namespaced(TRACKED_NAMESPACE, rel_path("bar").into_arc()),
1493                window,
1494                cx,
1495            );
1496            diff.editor.clone()
1497        });
1498        assert_state_with_diff(
1499            &editor,
1500            cx,
1501            &"
1502                - ˇbar
1503                + BAR
1504
1505                - foo
1506                + FOO
1507            "
1508            .unindent(),
1509        );
1510    }
1511
1512    #[gpui::test]
1513    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1514        init_test(cx);
1515
1516        let fs = FakeFs::new(cx.executor());
1517        fs.insert_tree(
1518            path!("/project"),
1519            json!({
1520                ".git": {},
1521                "foo": "modified\n",
1522            }),
1523        )
1524        .await;
1525        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1526        let (workspace, cx) =
1527            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1528        let buffer = project
1529            .update(cx, |project, cx| {
1530                project.open_local_buffer(path!("/project/foo"), cx)
1531            })
1532            .await
1533            .unwrap();
1534        let buffer_editor = cx.new_window_entity(|window, cx| {
1535            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1536        });
1537        let diff = cx.new_window_entity(|window, cx| {
1538            ProjectDiff::new(project.clone(), workspace, window, cx)
1539        });
1540        cx.run_until_parked();
1541
1542        fs.set_head_for_repo(
1543            path!("/project/.git").as_ref(),
1544            &[("foo", "original\n".into())],
1545            "deadbeef",
1546        );
1547        cx.run_until_parked();
1548
1549        let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1550
1551        assert_state_with_diff(
1552            &diff_editor,
1553            cx,
1554            &"
1555                - original
1556                + ˇmodified
1557            "
1558            .unindent(),
1559        );
1560
1561        let prev_buffer_hunks =
1562            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1563                let snapshot = buffer_editor.snapshot(window, cx);
1564                let snapshot = &snapshot.buffer_snapshot;
1565                let prev_buffer_hunks = buffer_editor
1566                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1567                    .collect::<Vec<_>>();
1568                buffer_editor.git_restore(&Default::default(), window, cx);
1569                prev_buffer_hunks
1570            });
1571        assert_eq!(prev_buffer_hunks.len(), 1);
1572        cx.run_until_parked();
1573
1574        let new_buffer_hunks =
1575            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1576                let snapshot = buffer_editor.snapshot(window, cx);
1577                let snapshot = &snapshot.buffer_snapshot;
1578                buffer_editor
1579                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1580                    .collect::<Vec<_>>()
1581            });
1582        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1583
1584        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1585            buffer_editor.set_text("different\n", window, cx);
1586            buffer_editor.save(
1587                SaveOptions {
1588                    format: false,
1589                    autosave: false,
1590                },
1591                project.clone(),
1592                window,
1593                cx,
1594            )
1595        })
1596        .await
1597        .unwrap();
1598
1599        cx.run_until_parked();
1600
1601        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1602            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1603        });
1604
1605        assert_state_with_diff(
1606            &buffer_editor,
1607            cx,
1608            &"
1609                - original
1610                + different
1611                  ˇ"
1612            .unindent(),
1613        );
1614
1615        assert_state_with_diff(
1616            &diff_editor,
1617            cx,
1618            &"
1619                - original
1620                + different
1621                  ˇ"
1622            .unindent(),
1623        );
1624    }
1625
1626    use crate::{
1627        conflict_view::resolve_conflict,
1628        project_diff::{self, ProjectDiff},
1629    };
1630
1631    #[gpui::test]
1632    async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1633        init_test(cx);
1634
1635        let fs = FakeFs::new(cx.executor());
1636        fs.insert_tree(
1637            "/a",
1638            json!({
1639                ".git": {},
1640                "a.txt": "created\n",
1641                "b.txt": "really changed\n",
1642                "c.txt": "unchanged\n"
1643            }),
1644        )
1645        .await;
1646
1647        fs.set_head_and_index_for_repo(
1648            Path::new("/a/.git"),
1649            &[
1650                ("b.txt", "before\n".to_string()),
1651                ("c.txt", "unchanged\n".to_string()),
1652                ("d.txt", "deleted\n".to_string()),
1653            ],
1654        );
1655
1656        let project = Project::test(fs, [Path::new("/a")], cx).await;
1657        let (workspace, cx) =
1658            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1659
1660        cx.run_until_parked();
1661
1662        cx.focus(&workspace);
1663        cx.update(|window, cx| {
1664            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1665        });
1666
1667        cx.run_until_parked();
1668
1669        let item = workspace.update(cx, |workspace, cx| {
1670            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1671        });
1672        cx.focus(&item);
1673        let editor = item.read_with(cx, |item, _| item.editor.clone());
1674
1675        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1676
1677        cx.assert_excerpts_with_selections(indoc!(
1678            "
1679            [EXCERPT]
1680            before
1681            really changed
1682            [EXCERPT]
1683            [FOLDED]
1684            [EXCERPT]
1685            ˇcreated
1686        "
1687        ));
1688
1689        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1690
1691        cx.assert_excerpts_with_selections(indoc!(
1692            "
1693            [EXCERPT]
1694            before
1695            really changed
1696            [EXCERPT]
1697            ˇ[FOLDED]
1698            [EXCERPT]
1699            created
1700        "
1701        ));
1702
1703        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1704
1705        cx.assert_excerpts_with_selections(indoc!(
1706            "
1707            [EXCERPT]
1708            ˇbefore
1709            really changed
1710            [EXCERPT]
1711            [FOLDED]
1712            [EXCERPT]
1713            created
1714        "
1715        ));
1716    }
1717
1718    #[gpui::test]
1719    async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1720        init_test(cx);
1721
1722        let git_contents = indoc! {r#"
1723            #[rustfmt::skip]
1724            fn main() {
1725                let x = 0.0; // this line will be removed
1726                // 1
1727                // 2
1728                // 3
1729                let y = 0.0; // this line will be removed
1730                // 1
1731                // 2
1732                // 3
1733                let arr = [
1734                    0.0, // this line will be removed
1735                    0.0, // this line will be removed
1736                    0.0, // this line will be removed
1737                    0.0, // this line will be removed
1738                ];
1739            }
1740        "#};
1741        let buffer_contents = indoc! {"
1742            #[rustfmt::skip]
1743            fn main() {
1744                // 1
1745                // 2
1746                // 3
1747                // 1
1748                // 2
1749                // 3
1750                let arr = [
1751                ];
1752            }
1753        "};
1754
1755        let fs = FakeFs::new(cx.executor());
1756        fs.insert_tree(
1757            "/a",
1758            json!({
1759                ".git": {},
1760                "main.rs": buffer_contents,
1761            }),
1762        )
1763        .await;
1764
1765        fs.set_head_and_index_for_repo(
1766            Path::new("/a/.git"),
1767            &[("main.rs", git_contents.to_owned())],
1768        );
1769
1770        let project = Project::test(fs, [Path::new("/a")], cx).await;
1771        let (workspace, cx) =
1772            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1773
1774        cx.run_until_parked();
1775
1776        cx.focus(&workspace);
1777        cx.update(|window, cx| {
1778            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1779        });
1780
1781        cx.run_until_parked();
1782
1783        let item = workspace.update(cx, |workspace, cx| {
1784            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1785        });
1786        cx.focus(&item);
1787        let editor = item.read_with(cx, |item, _| item.editor.clone());
1788
1789        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1790
1791        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1792
1793        cx.dispatch_action(editor::actions::GoToHunk);
1794        cx.dispatch_action(editor::actions::GoToHunk);
1795        cx.dispatch_action(git::Restore);
1796        cx.dispatch_action(editor::actions::MoveToBeginning);
1797
1798        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1799    }
1800
1801    #[gpui::test]
1802    async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1803        init_test(cx);
1804
1805        let fs = FakeFs::new(cx.executor());
1806        fs.insert_tree(
1807            path!("/project"),
1808            json!({
1809                ".git": {},
1810                "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1811            }),
1812        )
1813        .await;
1814        fs.set_status_for_repo(
1815            Path::new(path!("/project/.git")),
1816            &[(
1817                "foo",
1818                UnmergedStatus {
1819                    first_head: UnmergedStatusCode::Updated,
1820                    second_head: UnmergedStatusCode::Updated,
1821                }
1822                .into(),
1823            )],
1824        );
1825        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1826        let (workspace, cx) =
1827            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1828        let diff = cx.new_window_entity(|window, cx| {
1829            ProjectDiff::new(project.clone(), workspace, window, cx)
1830        });
1831        cx.run_until_parked();
1832
1833        cx.update(|window, cx| {
1834            let editor = diff.read(cx).editor.clone();
1835            let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1836            assert_eq!(excerpt_ids.len(), 1);
1837            let excerpt_id = excerpt_ids[0];
1838            let buffer = editor
1839                .read(cx)
1840                .buffer()
1841                .read(cx)
1842                .all_buffers()
1843                .into_iter()
1844                .next()
1845                .unwrap();
1846            let buffer_id = buffer.read(cx).remote_id();
1847            let conflict_set = diff
1848                .read(cx)
1849                .editor
1850                .read(cx)
1851                .addon::<ConflictAddon>()
1852                .unwrap()
1853                .conflict_set(buffer_id)
1854                .unwrap();
1855            assert!(conflict_set.read(cx).has_conflict);
1856            let snapshot = conflict_set.read(cx).snapshot();
1857            assert_eq!(snapshot.conflicts.len(), 1);
1858
1859            let ours_range = snapshot.conflicts[0].ours.clone();
1860
1861            resolve_conflict(
1862                editor.downgrade(),
1863                excerpt_id,
1864                snapshot.conflicts[0].clone(),
1865                vec![ours_range],
1866                window,
1867                cx,
1868            )
1869        })
1870        .await;
1871
1872        let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1873        let contents = String::from_utf8(contents).unwrap();
1874        assert_eq!(contents, "ours\n");
1875    }
1876}