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},
  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(_, _, 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(test)]
1350mod tests {
1351    use db::indoc;
1352    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1353    use git::status::{UnmergedStatus, UnmergedStatusCode};
1354    use gpui::TestAppContext;
1355    use project::FakeFs;
1356    use serde_json::json;
1357    use settings::SettingsStore;
1358    use std::path::Path;
1359    use unindent::Unindent as _;
1360    use util::{path, rel_path::rel_path};
1361
1362    use super::*;
1363
1364    #[ctor::ctor]
1365    fn init_logger() {
1366        zlog::init_test();
1367    }
1368
1369    fn init_test(cx: &mut TestAppContext) {
1370        cx.update(|cx| {
1371            let store = SettingsStore::test(cx);
1372            cx.set_global(store);
1373            theme::init(theme::LoadThemes::JustBase, cx);
1374            language::init(cx);
1375            Project::init_settings(cx);
1376            workspace::init_settings(cx);
1377            editor::init(cx);
1378            crate::init(cx);
1379        });
1380    }
1381
1382    #[gpui::test]
1383    async fn test_save_after_restore(cx: &mut TestAppContext) {
1384        init_test(cx);
1385
1386        let fs = FakeFs::new(cx.executor());
1387        fs.insert_tree(
1388            path!("/project"),
1389            json!({
1390                ".git": {},
1391                "foo.txt": "FOO\n",
1392            }),
1393        )
1394        .await;
1395        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1396        let (workspace, cx) =
1397            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1398        let diff = cx.new_window_entity(|window, cx| {
1399            ProjectDiff::new(project.clone(), workspace, window, cx)
1400        });
1401        cx.run_until_parked();
1402
1403        fs.set_head_for_repo(
1404            path!("/project/.git").as_ref(),
1405            &[("foo.txt", "foo\n".into())],
1406            "deadbeef",
1407        );
1408        fs.set_index_for_repo(
1409            path!("/project/.git").as_ref(),
1410            &[("foo.txt", "foo\n".into())],
1411        );
1412        cx.run_until_parked();
1413
1414        let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1415        assert_state_with_diff(
1416            &editor,
1417            cx,
1418            &"
1419                - foo
1420                + ˇFOO
1421            "
1422            .unindent(),
1423        );
1424
1425        editor.update_in(cx, |editor, window, cx| {
1426            editor.git_restore(&Default::default(), window, cx);
1427        });
1428        cx.run_until_parked();
1429
1430        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1431
1432        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1433        assert_eq!(text, "foo\n");
1434    }
1435
1436    #[gpui::test]
1437    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1438        init_test(cx);
1439
1440        let fs = FakeFs::new(cx.executor());
1441        fs.insert_tree(
1442            path!("/project"),
1443            json!({
1444                ".git": {},
1445                "bar": "BAR\n",
1446                "foo": "FOO\n",
1447            }),
1448        )
1449        .await;
1450        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1451        let (workspace, cx) =
1452            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1453        let diff = cx.new_window_entity(|window, cx| {
1454            ProjectDiff::new(project.clone(), workspace, window, cx)
1455        });
1456        cx.run_until_parked();
1457
1458        fs.set_head_and_index_for_repo(
1459            path!("/project/.git").as_ref(),
1460            &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1461        );
1462        cx.run_until_parked();
1463
1464        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1465            diff.move_to_path(
1466                PathKey::namespaced(TRACKED_NAMESPACE, rel_path("foo").into_arc()),
1467                window,
1468                cx,
1469            );
1470            diff.editor.clone()
1471        });
1472        assert_state_with_diff(
1473            &editor,
1474            cx,
1475            &"
1476                - bar
1477                + BAR
1478
1479                - ˇfoo
1480                + FOO
1481            "
1482            .unindent(),
1483        );
1484
1485        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1486            diff.move_to_path(
1487                PathKey::namespaced(TRACKED_NAMESPACE, rel_path("bar").into_arc()),
1488                window,
1489                cx,
1490            );
1491            diff.editor.clone()
1492        });
1493        assert_state_with_diff(
1494            &editor,
1495            cx,
1496            &"
1497                - ˇbar
1498                + BAR
1499
1500                - foo
1501                + FOO
1502            "
1503            .unindent(),
1504        );
1505    }
1506
1507    #[gpui::test]
1508    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1509        init_test(cx);
1510
1511        let fs = FakeFs::new(cx.executor());
1512        fs.insert_tree(
1513            path!("/project"),
1514            json!({
1515                ".git": {},
1516                "foo": "modified\n",
1517            }),
1518        )
1519        .await;
1520        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1521        let (workspace, cx) =
1522            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1523        let buffer = project
1524            .update(cx, |project, cx| {
1525                project.open_local_buffer(path!("/project/foo"), cx)
1526            })
1527            .await
1528            .unwrap();
1529        let buffer_editor = cx.new_window_entity(|window, cx| {
1530            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1531        });
1532        let diff = cx.new_window_entity(|window, cx| {
1533            ProjectDiff::new(project.clone(), workspace, window, cx)
1534        });
1535        cx.run_until_parked();
1536
1537        fs.set_head_for_repo(
1538            path!("/project/.git").as_ref(),
1539            &[("foo", "original\n".into())],
1540            "deadbeef",
1541        );
1542        cx.run_until_parked();
1543
1544        let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1545
1546        assert_state_with_diff(
1547            &diff_editor,
1548            cx,
1549            &"
1550                - original
1551                + ˇmodified
1552            "
1553            .unindent(),
1554        );
1555
1556        let prev_buffer_hunks =
1557            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1558                let snapshot = buffer_editor.snapshot(window, cx);
1559                let snapshot = &snapshot.buffer_snapshot();
1560                let prev_buffer_hunks = buffer_editor
1561                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1562                    .collect::<Vec<_>>();
1563                buffer_editor.git_restore(&Default::default(), window, cx);
1564                prev_buffer_hunks
1565            });
1566        assert_eq!(prev_buffer_hunks.len(), 1);
1567        cx.run_until_parked();
1568
1569        let new_buffer_hunks =
1570            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1571                let snapshot = buffer_editor.snapshot(window, cx);
1572                let snapshot = &snapshot.buffer_snapshot();
1573                buffer_editor
1574                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1575                    .collect::<Vec<_>>()
1576            });
1577        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1578
1579        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1580            buffer_editor.set_text("different\n", window, cx);
1581            buffer_editor.save(
1582                SaveOptions {
1583                    format: false,
1584                    autosave: false,
1585                },
1586                project.clone(),
1587                window,
1588                cx,
1589            )
1590        })
1591        .await
1592        .unwrap();
1593
1594        cx.run_until_parked();
1595
1596        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1597            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1598        });
1599
1600        assert_state_with_diff(
1601            &buffer_editor,
1602            cx,
1603            &"
1604                - original
1605                + different
1606                  ˇ"
1607            .unindent(),
1608        );
1609
1610        assert_state_with_diff(
1611            &diff_editor,
1612            cx,
1613            &"
1614                - original
1615                + different
1616                  ˇ"
1617            .unindent(),
1618        );
1619    }
1620
1621    use crate::{
1622        conflict_view::resolve_conflict,
1623        project_diff::{self, ProjectDiff},
1624    };
1625
1626    #[cfg_attr(windows, ignore = "currently fails on windows")]
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    #[cfg_attr(windows, ignore = "currently fails on windows")]
1715    #[gpui::test]
1716    async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1717        init_test(cx);
1718
1719        let git_contents = indoc! {r#"
1720            #[rustfmt::skip]
1721            fn main() {
1722                let x = 0.0; // this line will be removed
1723                // 1
1724                // 2
1725                // 3
1726                let y = 0.0; // this line will be removed
1727                // 1
1728                // 2
1729                // 3
1730                let arr = [
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                    0.0, // this line will be removed
1735                ];
1736            }
1737        "#};
1738        let buffer_contents = indoc! {"
1739            #[rustfmt::skip]
1740            fn main() {
1741                // 1
1742                // 2
1743                // 3
1744                // 1
1745                // 2
1746                // 3
1747                let arr = [
1748                ];
1749            }
1750        "};
1751
1752        let fs = FakeFs::new(cx.executor());
1753        fs.insert_tree(
1754            "/a",
1755            json!({
1756                ".git": {},
1757                "main.rs": buffer_contents,
1758            }),
1759        )
1760        .await;
1761
1762        fs.set_head_and_index_for_repo(
1763            Path::new("/a/.git"),
1764            &[("main.rs", git_contents.to_owned())],
1765        );
1766
1767        let project = Project::test(fs, [Path::new("/a")], cx).await;
1768        let (workspace, cx) =
1769            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1770
1771        cx.run_until_parked();
1772
1773        cx.focus(&workspace);
1774        cx.update(|window, cx| {
1775            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1776        });
1777
1778        cx.run_until_parked();
1779
1780        let item = workspace.update(cx, |workspace, cx| {
1781            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1782        });
1783        cx.focus(&item);
1784        let editor = item.read_with(cx, |item, _| item.editor.clone());
1785
1786        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1787
1788        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1789
1790        cx.dispatch_action(editor::actions::GoToHunk);
1791        cx.dispatch_action(editor::actions::GoToHunk);
1792        cx.dispatch_action(git::Restore);
1793        cx.dispatch_action(editor::actions::MoveToBeginning);
1794
1795        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1796    }
1797
1798    #[gpui::test]
1799    async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1800        init_test(cx);
1801
1802        let fs = FakeFs::new(cx.executor());
1803        fs.insert_tree(
1804            path!("/project"),
1805            json!({
1806                ".git": {},
1807                "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1808            }),
1809        )
1810        .await;
1811        fs.set_status_for_repo(
1812            Path::new(path!("/project/.git")),
1813            &[(
1814                "foo",
1815                UnmergedStatus {
1816                    first_head: UnmergedStatusCode::Updated,
1817                    second_head: UnmergedStatusCode::Updated,
1818                }
1819                .into(),
1820            )],
1821        );
1822        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1823        let (workspace, cx) =
1824            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1825        let diff = cx.new_window_entity(|window, cx| {
1826            ProjectDiff::new(project.clone(), workspace, window, cx)
1827        });
1828        cx.run_until_parked();
1829
1830        cx.update(|window, cx| {
1831            let editor = diff.read(cx).editor.clone();
1832            let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1833            assert_eq!(excerpt_ids.len(), 1);
1834            let excerpt_id = excerpt_ids[0];
1835            let buffer = editor
1836                .read(cx)
1837                .buffer()
1838                .read(cx)
1839                .all_buffers()
1840                .into_iter()
1841                .next()
1842                .unwrap();
1843            let buffer_id = buffer.read(cx).remote_id();
1844            let conflict_set = diff
1845                .read(cx)
1846                .editor
1847                .read(cx)
1848                .addon::<ConflictAddon>()
1849                .unwrap()
1850                .conflict_set(buffer_id)
1851                .unwrap();
1852            assert!(conflict_set.read(cx).has_conflict);
1853            let snapshot = conflict_set.read(cx).snapshot();
1854            assert_eq!(snapshot.conflicts.len(), 1);
1855
1856            let ours_range = snapshot.conflicts[0].ours.clone();
1857
1858            resolve_conflict(
1859                editor.downgrade(),
1860                excerpt_id,
1861                snapshot.conflicts[0].clone(),
1862                vec![ours_range],
1863                window,
1864                cx,
1865            )
1866        })
1867        .await;
1868
1869        let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1870        let contents = String::from_utf8(contents).unwrap();
1871        assert_eq!(contents, "ours\n");
1872    }
1873
1874    #[gpui::test]
1875    async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
1876        init_test(cx);
1877
1878        let fs = FakeFs::new(cx.executor());
1879        fs.insert_tree(
1880            path!("/project"),
1881            json!({
1882                ".git": {},
1883                "foo.txt": "
1884                    one
1885                    two
1886                    three
1887                    four
1888                    five
1889                    six
1890                    seven
1891                    eight
1892                    nine
1893                    ten
1894                    ELEVEN
1895                    twelve
1896                ".unindent()
1897            }),
1898        )
1899        .await;
1900        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1901        let (workspace, cx) =
1902            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1903        let diff = cx.new_window_entity(|window, cx| {
1904            ProjectDiff::new(project.clone(), workspace, window, cx)
1905        });
1906        cx.run_until_parked();
1907
1908        fs.set_head_and_index_for_repo(
1909            Path::new(path!("/project/.git")),
1910            &[(
1911                "foo.txt",
1912                "
1913                    one
1914                    two
1915                    three
1916                    four
1917                    five
1918                    six
1919                    seven
1920                    eight
1921                    nine
1922                    ten
1923                    eleven
1924                    twelve
1925                "
1926                .unindent(),
1927            )],
1928        );
1929        cx.run_until_parked();
1930
1931        let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1932        assert_state_with_diff(
1933            &editor,
1934            cx,
1935            &"
1936                  ˇnine
1937                  ten
1938                - eleven
1939                + ELEVEN
1940                  twelve
1941            "
1942            .unindent(),
1943        );
1944
1945        let buffer = project
1946            .update(cx, |project, cx| {
1947                project.open_local_buffer(path!("/project/foo.txt"), cx)
1948            })
1949            .await
1950            .unwrap();
1951        buffer.update(cx, |buffer, cx| {
1952            buffer.edit_via_marked_text(
1953                &"
1954                    one
1955                    «TWO»
1956                    three
1957                    four
1958                    five
1959                    six
1960                    seven
1961                    eight
1962                    nine
1963                    ten
1964                    ELEVEN
1965                    twelve
1966                "
1967                .unindent(),
1968                None,
1969                cx,
1970            );
1971        });
1972        project
1973            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
1974            .await
1975            .unwrap();
1976        cx.run_until_parked();
1977
1978        assert_state_with_diff(
1979            &editor,
1980            cx,
1981            &"
1982                  one
1983                - two
1984                + TWO
1985                  three
1986                  four
1987                  five
1988                  ˇnine
1989                  ten
1990                - eleven
1991                + ELEVEN
1992                  twelve
1993            "
1994            .unindent(),
1995        );
1996    }
1997}