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