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 set_nav_history(
 617        &mut self,
 618        nav_history: ItemNavHistory,
 619        _: &mut Window,
 620        cx: &mut Context<Self>,
 621    ) {
 622        self.editor.update(cx, |editor, _| {
 623            editor.set_nav_history(Some(nav_history));
 624        });
 625    }
 626
 627    fn clone_on_split(
 628        &self,
 629        _workspace_id: Option<workspace::WorkspaceId>,
 630        window: &mut Window,
 631        cx: &mut Context<Self>,
 632    ) -> Option<Entity<Self>>
 633    where
 634        Self: Sized,
 635    {
 636        let workspace = self.workspace.upgrade()?;
 637        Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
 638    }
 639
 640    fn is_dirty(&self, cx: &App) -> bool {
 641        self.multibuffer.read(cx).is_dirty(cx)
 642    }
 643
 644    fn has_conflict(&self, cx: &App) -> bool {
 645        self.multibuffer.read(cx).has_conflict(cx)
 646    }
 647
 648    fn can_save(&self, _: &App) -> bool {
 649        true
 650    }
 651
 652    fn save(
 653        &mut self,
 654        options: SaveOptions,
 655        project: Entity<Project>,
 656        window: &mut Window,
 657        cx: &mut Context<Self>,
 658    ) -> Task<Result<()>> {
 659        self.editor.save(options, project, window, cx)
 660    }
 661
 662    fn save_as(
 663        &mut self,
 664        _: Entity<Project>,
 665        _: ProjectPath,
 666        _window: &mut Window,
 667        _: &mut Context<Self>,
 668    ) -> Task<Result<()>> {
 669        unreachable!()
 670    }
 671
 672    fn reload(
 673        &mut self,
 674        project: Entity<Project>,
 675        window: &mut Window,
 676        cx: &mut Context<Self>,
 677    ) -> Task<Result<()>> {
 678        self.editor.reload(project, window, cx)
 679    }
 680
 681    fn act_as_type<'a>(
 682        &'a self,
 683        type_id: TypeId,
 684        self_handle: &'a Entity<Self>,
 685        _: &'a App,
 686    ) -> Option<AnyView> {
 687        if type_id == TypeId::of::<Self>() {
 688            Some(self_handle.to_any())
 689        } else if type_id == TypeId::of::<Editor>() {
 690            Some(self.editor.to_any())
 691        } else {
 692            None
 693        }
 694    }
 695
 696    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 697        ToolbarItemLocation::PrimaryLeft
 698    }
 699
 700    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 701        self.editor.breadcrumbs(theme, cx)
 702    }
 703
 704    fn added_to_workspace(
 705        &mut self,
 706        workspace: &mut Workspace,
 707        window: &mut Window,
 708        cx: &mut Context<Self>,
 709    ) {
 710        self.editor.update(cx, |editor, cx| {
 711            editor.added_to_workspace(workspace, window, cx)
 712        });
 713    }
 714}
 715
 716impl Render for ProjectDiff {
 717    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 718        let is_empty = self.multibuffer.read(cx).is_empty();
 719
 720        div()
 721            .track_focus(&self.focus_handle)
 722            .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
 723            .bg(cx.theme().colors().editor_background)
 724            .flex()
 725            .items_center()
 726            .justify_center()
 727            .size_full()
 728            .when(is_empty, |el| {
 729                let remote_button = if let Some(panel) = self
 730                    .workspace
 731                    .upgrade()
 732                    .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
 733                {
 734                    panel.update(cx, |panel, cx| panel.render_remote_button(cx))
 735                } else {
 736                    None
 737                };
 738                let keybinding_focus_handle = self.focus_handle(cx);
 739                el.child(
 740                    v_flex()
 741                        .gap_1()
 742                        .child(
 743                            h_flex()
 744                                .justify_around()
 745                                .child(Label::new("No uncommitted changes")),
 746                        )
 747                        .map(|el| match remote_button {
 748                            Some(button) => el.child(h_flex().justify_around().child(button)),
 749                            None => el.child(
 750                                h_flex()
 751                                    .justify_around()
 752                                    .child(Label::new("Remote up to date")),
 753                            ),
 754                        })
 755                        .child(
 756                            h_flex().justify_around().mt_1().child(
 757                                Button::new("project-diff-close-button", "Close")
 758                                    // .style(ButtonStyle::Transparent)
 759                                    .key_binding(KeyBinding::for_action_in(
 760                                        &CloseActiveItem::default(),
 761                                        &keybinding_focus_handle,
 762                                        window,
 763                                        cx,
 764                                    ))
 765                                    .on_click(move |_, window, cx| {
 766                                        window.focus(&keybinding_focus_handle);
 767                                        window.dispatch_action(
 768                                            Box::new(CloseActiveItem::default()),
 769                                            cx,
 770                                        );
 771                                    }),
 772                            ),
 773                        ),
 774                )
 775            })
 776            .when(!is_empty, |el| el.child(self.editor.clone()))
 777    }
 778}
 779
 780impl SerializableItem for ProjectDiff {
 781    fn serialized_item_kind() -> &'static str {
 782        "ProjectDiff"
 783    }
 784
 785    fn cleanup(
 786        _: workspace::WorkspaceId,
 787        _: Vec<workspace::ItemId>,
 788        _: &mut Window,
 789        _: &mut App,
 790    ) -> Task<Result<()>> {
 791        Task::ready(Ok(()))
 792    }
 793
 794    fn deserialize(
 795        _project: Entity<Project>,
 796        workspace: WeakEntity<Workspace>,
 797        _workspace_id: workspace::WorkspaceId,
 798        _item_id: workspace::ItemId,
 799        window: &mut Window,
 800        cx: &mut App,
 801    ) -> Task<Result<Entity<Self>>> {
 802        window.spawn(cx, async move |cx| {
 803            workspace.update_in(cx, |workspace, window, cx| {
 804                let workspace_handle = cx.entity();
 805                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
 806            })
 807        })
 808    }
 809
 810    fn serialize(
 811        &mut self,
 812        _workspace: &mut Workspace,
 813        _item_id: workspace::ItemId,
 814        _closing: bool,
 815        _window: &mut Window,
 816        _cx: &mut Context<Self>,
 817    ) -> Option<Task<Result<()>>> {
 818        None
 819    }
 820
 821    fn should_serialize(&self, _: &Self::Event) -> bool {
 822        false
 823    }
 824}
 825
 826pub struct ProjectDiffToolbar {
 827    project_diff: Option<WeakEntity<ProjectDiff>>,
 828    workspace: WeakEntity<Workspace>,
 829}
 830
 831impl ProjectDiffToolbar {
 832    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
 833        Self {
 834            project_diff: None,
 835            workspace: workspace.weak_handle(),
 836        }
 837    }
 838
 839    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
 840        self.project_diff.as_ref()?.upgrade()
 841    }
 842
 843    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 844        if let Some(project_diff) = self.project_diff(cx) {
 845            project_diff.focus_handle(cx).focus(window);
 846        }
 847        let action = action.boxed_clone();
 848        cx.defer(move |cx| {
 849            cx.dispatch_action(action.as_ref());
 850        })
 851    }
 852
 853    fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 854        self.workspace
 855            .update(cx, |workspace, cx| {
 856                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
 857                    panel.update(cx, |panel, cx| {
 858                        panel.stage_all(&Default::default(), window, cx);
 859                    });
 860                }
 861            })
 862            .ok();
 863    }
 864
 865    fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 866        self.workspace
 867            .update(cx, |workspace, cx| {
 868                let Some(panel) = workspace.panel::<GitPanel>(cx) else {
 869                    return;
 870                };
 871                panel.update(cx, |panel, cx| {
 872                    panel.unstage_all(&Default::default(), window, cx);
 873                });
 874            })
 875            .ok();
 876    }
 877}
 878
 879impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
 880
 881impl ToolbarItemView for ProjectDiffToolbar {
 882    fn set_active_pane_item(
 883        &mut self,
 884        active_pane_item: Option<&dyn ItemHandle>,
 885        _: &mut Window,
 886        cx: &mut Context<Self>,
 887    ) -> ToolbarItemLocation {
 888        self.project_diff = active_pane_item
 889            .and_then(|item| item.act_as::<ProjectDiff>(cx))
 890            .map(|entity| entity.downgrade());
 891        if self.project_diff.is_some() {
 892            ToolbarItemLocation::PrimaryRight
 893        } else {
 894            ToolbarItemLocation::Hidden
 895        }
 896    }
 897
 898    fn pane_focus_update(
 899        &mut self,
 900        _pane_focused: bool,
 901        _window: &mut Window,
 902        _cx: &mut Context<Self>,
 903    ) {
 904    }
 905}
 906
 907struct ButtonStates {
 908    stage: bool,
 909    unstage: bool,
 910    prev_next: bool,
 911    selection: bool,
 912    stage_all: bool,
 913    unstage_all: bool,
 914}
 915
 916impl Render for ProjectDiffToolbar {
 917    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 918        let Some(project_diff) = self.project_diff(cx) else {
 919            return div();
 920        };
 921        let focus_handle = project_diff.focus_handle(cx);
 922        let button_states = project_diff.read(cx).button_states(cx);
 923
 924        h_group_xl()
 925            .my_neg_1()
 926            .py_1()
 927            .items_center()
 928            .flex_wrap()
 929            .justify_between()
 930            .child(
 931                h_group_sm()
 932                    .when(button_states.selection, |el| {
 933                        el.child(
 934                            Button::new("stage", "Toggle Staged")
 935                                .tooltip(Tooltip::for_action_title_in(
 936                                    "Toggle Staged",
 937                                    &ToggleStaged,
 938                                    &focus_handle,
 939                                ))
 940                                .disabled(!button_states.stage && !button_states.unstage)
 941                                .on_click(cx.listener(|this, _, window, cx| {
 942                                    this.dispatch_action(&ToggleStaged, window, cx)
 943                                })),
 944                        )
 945                    })
 946                    .when(!button_states.selection, |el| {
 947                        el.child(
 948                            Button::new("stage", "Stage")
 949                                .tooltip(Tooltip::for_action_title_in(
 950                                    "Stage and go to next hunk",
 951                                    &StageAndNext,
 952                                    &focus_handle,
 953                                ))
 954                                .on_click(cx.listener(|this, _, window, cx| {
 955                                    this.dispatch_action(&StageAndNext, window, cx)
 956                                })),
 957                        )
 958                        .child(
 959                            Button::new("unstage", "Unstage")
 960                                .tooltip(Tooltip::for_action_title_in(
 961                                    "Unstage and go to next hunk",
 962                                    &UnstageAndNext,
 963                                    &focus_handle,
 964                                ))
 965                                .on_click(cx.listener(|this, _, window, cx| {
 966                                    this.dispatch_action(&UnstageAndNext, window, cx)
 967                                })),
 968                        )
 969                    }),
 970            )
 971            // n.b. the only reason these arrows are here is because we don't
 972            // support "undo" for staging so we need a way to go back.
 973            .child(
 974                h_group_sm()
 975                    .child(
 976                        IconButton::new("up", IconName::ArrowUp)
 977                            .shape(ui::IconButtonShape::Square)
 978                            .tooltip(Tooltip::for_action_title_in(
 979                                "Go to previous hunk",
 980                                &GoToPreviousHunk,
 981                                &focus_handle,
 982                            ))
 983                            .disabled(!button_states.prev_next)
 984                            .on_click(cx.listener(|this, _, window, cx| {
 985                                this.dispatch_action(&GoToPreviousHunk, window, cx)
 986                            })),
 987                    )
 988                    .child(
 989                        IconButton::new("down", IconName::ArrowDown)
 990                            .shape(ui::IconButtonShape::Square)
 991                            .tooltip(Tooltip::for_action_title_in(
 992                                "Go to next hunk",
 993                                &GoToHunk,
 994                                &focus_handle,
 995                            ))
 996                            .disabled(!button_states.prev_next)
 997                            .on_click(cx.listener(|this, _, window, cx| {
 998                                this.dispatch_action(&GoToHunk, window, cx)
 999                            })),
1000                    ),
1001            )
1002            .child(vertical_divider())
1003            .child(
1004                h_group_sm()
1005                    .when(
1006                        button_states.unstage_all && !button_states.stage_all,
1007                        |el| {
1008                            el.child(
1009                                Button::new("unstage-all", "Unstage All")
1010                                    .tooltip(Tooltip::for_action_title_in(
1011                                        "Unstage all changes",
1012                                        &UnstageAll,
1013                                        &focus_handle,
1014                                    ))
1015                                    .on_click(cx.listener(|this, _, window, cx| {
1016                                        this.unstage_all(window, cx)
1017                                    })),
1018                            )
1019                        },
1020                    )
1021                    .when(
1022                        !button_states.unstage_all || button_states.stage_all,
1023                        |el| {
1024                            el.child(
1025                                // todo make it so that changing to say "Unstaged"
1026                                // doesn't change the position.
1027                                div().child(
1028                                    Button::new("stage-all", "Stage All")
1029                                        .disabled(!button_states.stage_all)
1030                                        .tooltip(Tooltip::for_action_title_in(
1031                                            "Stage all changes",
1032                                            &StageAll,
1033                                            &focus_handle,
1034                                        ))
1035                                        .on_click(cx.listener(|this, _, window, cx| {
1036                                            this.stage_all(window, cx)
1037                                        })),
1038                                ),
1039                            )
1040                        },
1041                    )
1042                    .child(
1043                        Button::new("commit", "Commit")
1044                            .tooltip(Tooltip::for_action_title_in(
1045                                "Commit",
1046                                &Commit,
1047                                &focus_handle,
1048                            ))
1049                            .on_click(cx.listener(|this, _, window, cx| {
1050                                this.dispatch_action(&Commit, window, cx);
1051                            })),
1052                    ),
1053            )
1054    }
1055}
1056
1057#[derive(IntoElement, RegisterComponent)]
1058pub struct ProjectDiffEmptyState {
1059    pub no_repo: bool,
1060    pub can_push_and_pull: bool,
1061    pub focus_handle: Option<FocusHandle>,
1062    pub current_branch: Option<Branch>,
1063    // has_pending_commits: bool,
1064    // ahead_of_remote: bool,
1065    // no_git_repository: bool,
1066}
1067
1068impl RenderOnce for ProjectDiffEmptyState {
1069    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1070        let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1071            matches!(self.current_branch, Some(Branch {
1072                    upstream:
1073                        Some(Upstream {
1074                            tracking:
1075                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1076                                    ahead, behind, ..
1077                                }),
1078                            ..
1079                        }),
1080                    ..
1081                }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1082        };
1083
1084        let change_count = |current_branch: &Branch| -> (usize, usize) {
1085            match current_branch {
1086                Branch {
1087                    upstream:
1088                        Some(Upstream {
1089                            tracking:
1090                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1091                                    ahead, behind, ..
1092                                }),
1093                            ..
1094                        }),
1095                    ..
1096                } => (*ahead as usize, *behind as usize),
1097                _ => (0, 0),
1098            }
1099        };
1100
1101        let not_ahead_or_behind = status_against_remote(0, 0);
1102        let ahead_of_remote = status_against_remote(1, 0);
1103        let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1104            branch.upstream.is_none()
1105        } else {
1106            false
1107        };
1108
1109        let has_branch_container = |branch: &Branch| {
1110            h_flex()
1111                .max_w(px(420.))
1112                .bg(cx.theme().colors().text.opacity(0.05))
1113                .border_1()
1114                .border_color(cx.theme().colors().border)
1115                .rounded_sm()
1116                .gap_8()
1117                .px_6()
1118                .py_4()
1119                .map(|this| {
1120                    if ahead_of_remote {
1121                        let ahead_count = change_count(branch).0;
1122                        let ahead_string = format!("{} Commits Ahead", ahead_count);
1123                        this.child(
1124                            v_flex()
1125                                .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1126                                .child(
1127                                    Label::new(format!("Push your changes to {}", branch.name()))
1128                                        .color(Color::Muted),
1129                                ),
1130                        )
1131                        .child(div().child(render_push_button(
1132                            self.focus_handle,
1133                            "push".into(),
1134                            ahead_count as u32,
1135                        )))
1136                    } else if branch_not_on_remote {
1137                        this.child(
1138                            v_flex()
1139                                .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1140                                .child(
1141                                    Label::new(format!("Create {} on remote", branch.name()))
1142                                        .color(Color::Muted),
1143                                ),
1144                        )
1145                        .child(
1146                            div().child(render_publish_button(self.focus_handle, "publish".into())),
1147                        )
1148                    } else {
1149                        this.child(Label::new("Remote status unknown").color(Color::Muted))
1150                    }
1151                })
1152        };
1153
1154        v_flex().size_full().items_center().justify_center().child(
1155            v_flex()
1156                .gap_1()
1157                .when(self.no_repo, |this| {
1158                    // TODO: add git init
1159                    this.text_center()
1160                        .child(Label::new("No Repository").color(Color::Muted))
1161                })
1162                .map(|this| {
1163                    if not_ahead_or_behind && self.current_branch.is_some() {
1164                        this.text_center()
1165                            .child(Label::new("No Changes").color(Color::Muted))
1166                    } else {
1167                        this.when_some(self.current_branch.as_ref(), |this, branch| {
1168                            this.child(has_branch_container(branch))
1169                        })
1170                    }
1171                }),
1172        )
1173    }
1174}
1175
1176mod preview {
1177    use git::repository::{
1178        Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1179    };
1180    use ui::prelude::*;
1181
1182    use super::ProjectDiffEmptyState;
1183
1184    // View this component preview using `workspace: open component-preview`
1185    impl Component for ProjectDiffEmptyState {
1186        fn scope() -> ComponentScope {
1187            ComponentScope::VersionControl
1188        }
1189
1190        fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1191            let unknown_upstream: Option<UpstreamTracking> = None;
1192            let ahead_of_upstream: Option<UpstreamTracking> = Some(
1193                UpstreamTrackingStatus {
1194                    ahead: 2,
1195                    behind: 0,
1196                }
1197                .into(),
1198            );
1199
1200            let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1201                UpstreamTrackingStatus {
1202                    ahead: 0,
1203                    behind: 0,
1204                }
1205                .into(),
1206            );
1207
1208            fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1209                Branch {
1210                    is_head: true,
1211                    ref_name: "some-branch".into(),
1212                    upstream: upstream.map(|tracking| Upstream {
1213                        ref_name: "origin/some-branch".into(),
1214                        tracking,
1215                    }),
1216                    most_recent_commit: Some(CommitSummary {
1217                        sha: "abc123".into(),
1218                        subject: "Modify stuff".into(),
1219                        commit_timestamp: 1710932954,
1220                        author_name: "John Doe".into(),
1221                        has_parent: true,
1222                    }),
1223                }
1224            }
1225
1226            let no_repo_state = ProjectDiffEmptyState {
1227                no_repo: true,
1228                can_push_and_pull: false,
1229                focus_handle: None,
1230                current_branch: None,
1231            };
1232
1233            let no_changes_state = ProjectDiffEmptyState {
1234                no_repo: false,
1235                can_push_and_pull: true,
1236                focus_handle: None,
1237                current_branch: Some(branch(not_ahead_or_behind_upstream)),
1238            };
1239
1240            let ahead_of_upstream_state = ProjectDiffEmptyState {
1241                no_repo: false,
1242                can_push_and_pull: true,
1243                focus_handle: None,
1244                current_branch: Some(branch(ahead_of_upstream)),
1245            };
1246
1247            let unknown_upstream_state = ProjectDiffEmptyState {
1248                no_repo: false,
1249                can_push_and_pull: true,
1250                focus_handle: None,
1251                current_branch: Some(branch(unknown_upstream)),
1252            };
1253
1254            let (width, height) = (px(480.), px(320.));
1255
1256            Some(
1257                v_flex()
1258                    .gap_6()
1259                    .children(vec![
1260                        example_group(vec![
1261                            single_example(
1262                                "No Repo",
1263                                div()
1264                                    .w(width)
1265                                    .h(height)
1266                                    .child(no_repo_state)
1267                                    .into_any_element(),
1268                            ),
1269                            single_example(
1270                                "No Changes",
1271                                div()
1272                                    .w(width)
1273                                    .h(height)
1274                                    .child(no_changes_state)
1275                                    .into_any_element(),
1276                            ),
1277                            single_example(
1278                                "Unknown Upstream",
1279                                div()
1280                                    .w(width)
1281                                    .h(height)
1282                                    .child(unknown_upstream_state)
1283                                    .into_any_element(),
1284                            ),
1285                            single_example(
1286                                "Ahead of Remote",
1287                                div()
1288                                    .w(width)
1289                                    .h(height)
1290                                    .child(ahead_of_upstream_state)
1291                                    .into_any_element(),
1292                            ),
1293                        ])
1294                        .vertical(),
1295                    ])
1296                    .into_any_element(),
1297            )
1298        }
1299    }
1300}
1301
1302fn merge_anchor_ranges<'a>(
1303    left: impl 'a + Iterator<Item = Range<Anchor>>,
1304    right: impl 'a + Iterator<Item = Range<Anchor>>,
1305    snapshot: &'a language::BufferSnapshot,
1306) -> impl 'a + Iterator<Item = Range<Anchor>> {
1307    let mut left = left.fuse().peekable();
1308    let mut right = right.fuse().peekable();
1309
1310    std::iter::from_fn(move || {
1311        let Some(left_range) = left.peek() else {
1312            return right.next();
1313        };
1314        let Some(right_range) = right.peek() else {
1315            return left.next();
1316        };
1317
1318        let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1319            left.next().unwrap()
1320        } else {
1321            right.next().unwrap()
1322        };
1323
1324        // Extend the basic range while there's overlap with a range from either stream.
1325        loop {
1326            if let Some(left_range) = left
1327                .peek()
1328                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1329                .cloned()
1330            {
1331                left.next();
1332                next_range.end = left_range.end;
1333            } else if let Some(right_range) = right
1334                .peek()
1335                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1336                .cloned()
1337            {
1338                right.next();
1339                next_range.end = right_range.end;
1340            } else {
1341                break;
1342            }
1343        }
1344
1345        Some(next_range)
1346    })
1347}
1348
1349#[cfg(not(target_os = "windows"))]
1350#[cfg(test)]
1351mod tests {
1352    use db::indoc;
1353    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1354    use git::status::{UnmergedStatus, UnmergedStatusCode};
1355    use gpui::TestAppContext;
1356    use project::FakeFs;
1357    use serde_json::json;
1358    use settings::SettingsStore;
1359    use std::path::Path;
1360    use unindent::Unindent as _;
1361    use util::{path, rel_path::rel_path};
1362
1363    use super::*;
1364
1365    #[ctor::ctor]
1366    fn init_logger() {
1367        zlog::init_test();
1368    }
1369
1370    fn init_test(cx: &mut TestAppContext) {
1371        cx.update(|cx| {
1372            let store = SettingsStore::test(cx);
1373            cx.set_global(store);
1374            theme::init(theme::LoadThemes::JustBase, cx);
1375            language::init(cx);
1376            Project::init_settings(cx);
1377            workspace::init_settings(cx);
1378            editor::init(cx);
1379            crate::init(cx);
1380        });
1381    }
1382
1383    #[gpui::test]
1384    async fn test_save_after_restore(cx: &mut TestAppContext) {
1385        init_test(cx);
1386
1387        let fs = FakeFs::new(cx.executor());
1388        fs.insert_tree(
1389            path!("/project"),
1390            json!({
1391                ".git": {},
1392                "foo.txt": "FOO\n",
1393            }),
1394        )
1395        .await;
1396        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1397        let (workspace, cx) =
1398            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1399        let diff = cx.new_window_entity(|window, cx| {
1400            ProjectDiff::new(project.clone(), workspace, window, cx)
1401        });
1402        cx.run_until_parked();
1403
1404        fs.set_head_for_repo(
1405            path!("/project/.git").as_ref(),
1406            &[("foo.txt", "foo\n".into())],
1407            "deadbeef",
1408        );
1409        fs.set_index_for_repo(
1410            path!("/project/.git").as_ref(),
1411            &[("foo.txt", "foo\n".into())],
1412        );
1413        cx.run_until_parked();
1414
1415        let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1416        assert_state_with_diff(
1417            &editor,
1418            cx,
1419            &"
1420                - foo
1421                + ˇFOO
1422            "
1423            .unindent(),
1424        );
1425
1426        editor.update_in(cx, |editor, window, cx| {
1427            editor.git_restore(&Default::default(), window, cx);
1428        });
1429        cx.run_until_parked();
1430
1431        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1432
1433        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1434        assert_eq!(text, "foo\n");
1435    }
1436
1437    #[gpui::test]
1438    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1439        init_test(cx);
1440
1441        let fs = FakeFs::new(cx.executor());
1442        fs.insert_tree(
1443            path!("/project"),
1444            json!({
1445                ".git": {},
1446                "bar": "BAR\n",
1447                "foo": "FOO\n",
1448            }),
1449        )
1450        .await;
1451        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1452        let (workspace, cx) =
1453            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1454        let diff = cx.new_window_entity(|window, cx| {
1455            ProjectDiff::new(project.clone(), workspace, window, cx)
1456        });
1457        cx.run_until_parked();
1458
1459        fs.set_head_and_index_for_repo(
1460            path!("/project/.git").as_ref(),
1461            &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1462        );
1463        cx.run_until_parked();
1464
1465        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1466            diff.move_to_path(
1467                PathKey::namespaced(TRACKED_NAMESPACE, rel_path("foo").into_arc()),
1468                window,
1469                cx,
1470            );
1471            diff.editor.clone()
1472        });
1473        assert_state_with_diff(
1474            &editor,
1475            cx,
1476            &"
1477                - bar
1478                + BAR
1479
1480                - ˇfoo
1481                + FOO
1482            "
1483            .unindent(),
1484        );
1485
1486        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1487            diff.move_to_path(
1488                PathKey::namespaced(TRACKED_NAMESPACE, rel_path("bar").into_arc()),
1489                window,
1490                cx,
1491            );
1492            diff.editor.clone()
1493        });
1494        assert_state_with_diff(
1495            &editor,
1496            cx,
1497            &"
1498                - ˇbar
1499                + BAR
1500
1501                - foo
1502                + FOO
1503            "
1504            .unindent(),
1505        );
1506    }
1507
1508    #[gpui::test]
1509    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1510        init_test(cx);
1511
1512        let fs = FakeFs::new(cx.executor());
1513        fs.insert_tree(
1514            path!("/project"),
1515            json!({
1516                ".git": {},
1517                "foo": "modified\n",
1518            }),
1519        )
1520        .await;
1521        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1522        let (workspace, cx) =
1523            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1524        let buffer = project
1525            .update(cx, |project, cx| {
1526                project.open_local_buffer(path!("/project/foo"), cx)
1527            })
1528            .await
1529            .unwrap();
1530        let buffer_editor = cx.new_window_entity(|window, cx| {
1531            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1532        });
1533        let diff = cx.new_window_entity(|window, cx| {
1534            ProjectDiff::new(project.clone(), workspace, window, cx)
1535        });
1536        cx.run_until_parked();
1537
1538        fs.set_head_for_repo(
1539            path!("/project/.git").as_ref(),
1540            &[("foo", "original\n".into())],
1541            "deadbeef",
1542        );
1543        cx.run_until_parked();
1544
1545        let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1546
1547        assert_state_with_diff(
1548            &diff_editor,
1549            cx,
1550            &"
1551                - original
1552                + ˇmodified
1553            "
1554            .unindent(),
1555        );
1556
1557        let prev_buffer_hunks =
1558            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1559                let snapshot = buffer_editor.snapshot(window, cx);
1560                let snapshot = &snapshot.buffer_snapshot;
1561                let prev_buffer_hunks = buffer_editor
1562                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1563                    .collect::<Vec<_>>();
1564                buffer_editor.git_restore(&Default::default(), window, cx);
1565                prev_buffer_hunks
1566            });
1567        assert_eq!(prev_buffer_hunks.len(), 1);
1568        cx.run_until_parked();
1569
1570        let new_buffer_hunks =
1571            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1572                let snapshot = buffer_editor.snapshot(window, cx);
1573                let snapshot = &snapshot.buffer_snapshot;
1574                buffer_editor
1575                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1576                    .collect::<Vec<_>>()
1577            });
1578        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1579
1580        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1581            buffer_editor.set_text("different\n", window, cx);
1582            buffer_editor.save(
1583                SaveOptions {
1584                    format: false,
1585                    autosave: false,
1586                },
1587                project.clone(),
1588                window,
1589                cx,
1590            )
1591        })
1592        .await
1593        .unwrap();
1594
1595        cx.run_until_parked();
1596
1597        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1598            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1599        });
1600
1601        assert_state_with_diff(
1602            &buffer_editor,
1603            cx,
1604            &"
1605                - original
1606                + different
1607                  ˇ"
1608            .unindent(),
1609        );
1610
1611        assert_state_with_diff(
1612            &diff_editor,
1613            cx,
1614            &"
1615                - original
1616                + different
1617                  ˇ"
1618            .unindent(),
1619        );
1620    }
1621
1622    use crate::{
1623        conflict_view::resolve_conflict,
1624        project_diff::{self, ProjectDiff},
1625    };
1626
1627    #[gpui::test]
1628    async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1629        init_test(cx);
1630
1631        let fs = FakeFs::new(cx.executor());
1632        fs.insert_tree(
1633            "/a",
1634            json!({
1635                ".git": {},
1636                "a.txt": "created\n",
1637                "b.txt": "really changed\n",
1638                "c.txt": "unchanged\n"
1639            }),
1640        )
1641        .await;
1642
1643        fs.set_head_and_index_for_repo(
1644            Path::new("/a/.git"),
1645            &[
1646                ("b.txt", "before\n".to_string()),
1647                ("c.txt", "unchanged\n".to_string()),
1648                ("d.txt", "deleted\n".to_string()),
1649            ],
1650        );
1651
1652        let project = Project::test(fs, [Path::new("/a")], cx).await;
1653        let (workspace, cx) =
1654            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1655
1656        cx.run_until_parked();
1657
1658        cx.focus(&workspace);
1659        cx.update(|window, cx| {
1660            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1661        });
1662
1663        cx.run_until_parked();
1664
1665        let item = workspace.update(cx, |workspace, cx| {
1666            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1667        });
1668        cx.focus(&item);
1669        let editor = item.read_with(cx, |item, _| item.editor.clone());
1670
1671        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1672
1673        cx.assert_excerpts_with_selections(indoc!(
1674            "
1675            [EXCERPT]
1676            before
1677            really changed
1678            [EXCERPT]
1679            [FOLDED]
1680            [EXCERPT]
1681            ˇcreated
1682        "
1683        ));
1684
1685        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1686
1687        cx.assert_excerpts_with_selections(indoc!(
1688            "
1689            [EXCERPT]
1690            before
1691            really changed
1692            [EXCERPT]
1693            ˇ[FOLDED]
1694            [EXCERPT]
1695            created
1696        "
1697        ));
1698
1699        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1700
1701        cx.assert_excerpts_with_selections(indoc!(
1702            "
1703            [EXCERPT]
1704            ˇbefore
1705            really changed
1706            [EXCERPT]
1707            [FOLDED]
1708            [EXCERPT]
1709            created
1710        "
1711        ));
1712    }
1713
1714    #[gpui::test]
1715    async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1716        init_test(cx);
1717
1718        let git_contents = indoc! {r#"
1719            #[rustfmt::skip]
1720            fn main() {
1721                let x = 0.0; // this line will be removed
1722                // 1
1723                // 2
1724                // 3
1725                let y = 0.0; // this line will be removed
1726                // 1
1727                // 2
1728                // 3
1729                let arr = [
1730                    0.0, // this line will be removed
1731                    0.0, // this line will be removed
1732                    0.0, // this line will be removed
1733                    0.0, // this line will be removed
1734                ];
1735            }
1736        "#};
1737        let buffer_contents = indoc! {"
1738            #[rustfmt::skip]
1739            fn main() {
1740                // 1
1741                // 2
1742                // 3
1743                // 1
1744                // 2
1745                // 3
1746                let arr = [
1747                ];
1748            }
1749        "};
1750
1751        let fs = FakeFs::new(cx.executor());
1752        fs.insert_tree(
1753            "/a",
1754            json!({
1755                ".git": {},
1756                "main.rs": buffer_contents,
1757            }),
1758        )
1759        .await;
1760
1761        fs.set_head_and_index_for_repo(
1762            Path::new("/a/.git"),
1763            &[("main.rs", git_contents.to_owned())],
1764        );
1765
1766        let project = Project::test(fs, [Path::new("/a")], cx).await;
1767        let (workspace, cx) =
1768            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1769
1770        cx.run_until_parked();
1771
1772        cx.focus(&workspace);
1773        cx.update(|window, cx| {
1774            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1775        });
1776
1777        cx.run_until_parked();
1778
1779        let item = workspace.update(cx, |workspace, cx| {
1780            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1781        });
1782        cx.focus(&item);
1783        let editor = item.read_with(cx, |item, _| item.editor.clone());
1784
1785        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1786
1787        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1788
1789        cx.dispatch_action(editor::actions::GoToHunk);
1790        cx.dispatch_action(editor::actions::GoToHunk);
1791        cx.dispatch_action(git::Restore);
1792        cx.dispatch_action(editor::actions::MoveToBeginning);
1793
1794        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1795    }
1796
1797    #[gpui::test]
1798    async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1799        init_test(cx);
1800
1801        let fs = FakeFs::new(cx.executor());
1802        fs.insert_tree(
1803            path!("/project"),
1804            json!({
1805                ".git": {},
1806                "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1807            }),
1808        )
1809        .await;
1810        fs.set_status_for_repo(
1811            Path::new(path!("/project/.git")),
1812            &[(
1813                "foo",
1814                UnmergedStatus {
1815                    first_head: UnmergedStatusCode::Updated,
1816                    second_head: UnmergedStatusCode::Updated,
1817                }
1818                .into(),
1819            )],
1820        );
1821        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1822        let (workspace, cx) =
1823            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1824        let diff = cx.new_window_entity(|window, cx| {
1825            ProjectDiff::new(project.clone(), workspace, window, cx)
1826        });
1827        cx.run_until_parked();
1828
1829        cx.update(|window, cx| {
1830            let editor = diff.read(cx).editor.clone();
1831            let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1832            assert_eq!(excerpt_ids.len(), 1);
1833            let excerpt_id = excerpt_ids[0];
1834            let buffer = editor
1835                .read(cx)
1836                .buffer()
1837                .read(cx)
1838                .all_buffers()
1839                .into_iter()
1840                .next()
1841                .unwrap();
1842            let buffer_id = buffer.read(cx).remote_id();
1843            let conflict_set = diff
1844                .read(cx)
1845                .editor
1846                .read(cx)
1847                .addon::<ConflictAddon>()
1848                .unwrap()
1849                .conflict_set(buffer_id)
1850                .unwrap();
1851            assert!(conflict_set.read(cx).has_conflict);
1852            let snapshot = conflict_set.read(cx).snapshot();
1853            assert_eq!(snapshot.conflicts.len(), 1);
1854
1855            let ours_range = snapshot.conflicts[0].ours.clone();
1856
1857            resolve_conflict(
1858                editor.downgrade(),
1859                excerpt_id,
1860                snapshot.conflicts[0].clone(),
1861                vec![ours_range],
1862                window,
1863                cx,
1864            )
1865        })
1866        .await;
1867
1868        let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1869        let contents = String::from_utf8(contents).unwrap();
1870        assert_eq!(contents, "ours\n");
1871    }
1872}