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                        author_name: "John Doe".into(),
1224                        has_parent: true,
1225                    }),
1226                }
1227            }
1228
1229            let no_repo_state = ProjectDiffEmptyState {
1230                no_repo: true,
1231                can_push_and_pull: false,
1232                focus_handle: None,
1233                current_branch: None,
1234            };
1235
1236            let no_changes_state = ProjectDiffEmptyState {
1237                no_repo: false,
1238                can_push_and_pull: true,
1239                focus_handle: None,
1240                current_branch: Some(branch(not_ahead_or_behind_upstream)),
1241            };
1242
1243            let ahead_of_upstream_state = ProjectDiffEmptyState {
1244                no_repo: false,
1245                can_push_and_pull: true,
1246                focus_handle: None,
1247                current_branch: Some(branch(ahead_of_upstream)),
1248            };
1249
1250            let unknown_upstream_state = ProjectDiffEmptyState {
1251                no_repo: false,
1252                can_push_and_pull: true,
1253                focus_handle: None,
1254                current_branch: Some(branch(unknown_upstream)),
1255            };
1256
1257            let (width, height) = (px(480.), px(320.));
1258
1259            Some(
1260                v_flex()
1261                    .gap_6()
1262                    .children(vec![
1263                        example_group(vec![
1264                            single_example(
1265                                "No Repo",
1266                                div()
1267                                    .w(width)
1268                                    .h(height)
1269                                    .child(no_repo_state)
1270                                    .into_any_element(),
1271                            ),
1272                            single_example(
1273                                "No Changes",
1274                                div()
1275                                    .w(width)
1276                                    .h(height)
1277                                    .child(no_changes_state)
1278                                    .into_any_element(),
1279                            ),
1280                            single_example(
1281                                "Unknown Upstream",
1282                                div()
1283                                    .w(width)
1284                                    .h(height)
1285                                    .child(unknown_upstream_state)
1286                                    .into_any_element(),
1287                            ),
1288                            single_example(
1289                                "Ahead of Remote",
1290                                div()
1291                                    .w(width)
1292                                    .h(height)
1293                                    .child(ahead_of_upstream_state)
1294                                    .into_any_element(),
1295                            ),
1296                        ])
1297                        .vertical(),
1298                    ])
1299                    .into_any_element(),
1300            )
1301        }
1302    }
1303}
1304
1305fn merge_anchor_ranges<'a>(
1306    left: impl 'a + Iterator<Item = Range<Anchor>>,
1307    right: impl 'a + Iterator<Item = Range<Anchor>>,
1308    snapshot: &'a language::BufferSnapshot,
1309) -> impl 'a + Iterator<Item = Range<Anchor>> {
1310    let mut left = left.fuse().peekable();
1311    let mut right = right.fuse().peekable();
1312
1313    std::iter::from_fn(move || {
1314        let Some(left_range) = left.peek() else {
1315            return right.next();
1316        };
1317        let Some(right_range) = right.peek() else {
1318            return left.next();
1319        };
1320
1321        let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1322            left.next().unwrap()
1323        } else {
1324            right.next().unwrap()
1325        };
1326
1327        // Extend the basic range while there's overlap with a range from either stream.
1328        loop {
1329            if let Some(left_range) = left
1330                .peek()
1331                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1332                .cloned()
1333            {
1334                left.next();
1335                next_range.end = left_range.end;
1336            } else if let Some(right_range) = right
1337                .peek()
1338                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1339                .cloned()
1340            {
1341                right.next();
1342                next_range.end = right_range.end;
1343            } else {
1344                break;
1345            }
1346        }
1347
1348        Some(next_range)
1349    })
1350}
1351
1352#[cfg(not(target_os = "windows"))]
1353#[cfg(test)]
1354mod tests {
1355    use db::indoc;
1356    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1357    use git::status::{UnmergedStatus, UnmergedStatusCode};
1358    use gpui::TestAppContext;
1359    use project::FakeFs;
1360    use serde_json::json;
1361    use settings::SettingsStore;
1362    use std::path::Path;
1363    use unindent::Unindent as _;
1364    use util::path;
1365
1366    use super::*;
1367
1368    #[ctor::ctor]
1369    fn init_logger() {
1370        zlog::init_test();
1371    }
1372
1373    fn init_test(cx: &mut TestAppContext) {
1374        cx.update(|cx| {
1375            let store = SettingsStore::test(cx);
1376            cx.set_global(store);
1377            theme::init(theme::LoadThemes::JustBase, cx);
1378            language::init(cx);
1379            Project::init_settings(cx);
1380            workspace::init_settings(cx);
1381            editor::init(cx);
1382            crate::init(cx);
1383        });
1384    }
1385
1386    #[gpui::test]
1387    async fn test_save_after_restore(cx: &mut TestAppContext) {
1388        init_test(cx);
1389
1390        let fs = FakeFs::new(cx.executor());
1391        fs.insert_tree(
1392            path!("/project"),
1393            json!({
1394                ".git": {},
1395                "foo.txt": "FOO\n",
1396            }),
1397        )
1398        .await;
1399        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1400        let (workspace, cx) =
1401            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1402        let diff = cx.new_window_entity(|window, cx| {
1403            ProjectDiff::new(project.clone(), workspace, window, cx)
1404        });
1405        cx.run_until_parked();
1406
1407        fs.set_head_for_repo(
1408            path!("/project/.git").as_ref(),
1409            &[("foo.txt".into(), "foo\n".into())],
1410            "deadbeef",
1411        );
1412        fs.set_index_for_repo(
1413            path!("/project/.git").as_ref(),
1414            &[("foo.txt".into(), "foo\n".into())],
1415        );
1416        cx.run_until_parked();
1417
1418        let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1419        assert_state_with_diff(
1420            &editor,
1421            cx,
1422            &"
1423                - foo
1424                + ˇFOO
1425            "
1426            .unindent(),
1427        );
1428
1429        editor.update_in(cx, |editor, window, cx| {
1430            editor.git_restore(&Default::default(), window, cx);
1431        });
1432        cx.run_until_parked();
1433
1434        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1435
1436        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1437        assert_eq!(text, "foo\n");
1438    }
1439
1440    #[gpui::test]
1441    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1442        init_test(cx);
1443
1444        let fs = FakeFs::new(cx.executor());
1445        fs.insert_tree(
1446            path!("/project"),
1447            json!({
1448                ".git": {},
1449                "bar": "BAR\n",
1450                "foo": "FOO\n",
1451            }),
1452        )
1453        .await;
1454        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1455        let (workspace, cx) =
1456            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1457        let diff = cx.new_window_entity(|window, cx| {
1458            ProjectDiff::new(project.clone(), workspace, window, cx)
1459        });
1460        cx.run_until_parked();
1461
1462        fs.set_head_and_index_for_repo(
1463            path!("/project/.git").as_ref(),
1464            &[
1465                ("bar".into(), "bar\n".into()),
1466                ("foo".into(), "foo\n".into()),
1467            ],
1468        );
1469        cx.run_until_parked();
1470
1471        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1472            diff.move_to_path(
1473                PathKey::namespaced(TRACKED_NAMESPACE, Path::new("foo").into()),
1474                window,
1475                cx,
1476            );
1477            diff.editor.clone()
1478        });
1479        assert_state_with_diff(
1480            &editor,
1481            cx,
1482            &"
1483                - bar
1484                + BAR
1485
1486                - ˇfoo
1487                + FOO
1488            "
1489            .unindent(),
1490        );
1491
1492        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1493            diff.move_to_path(
1494                PathKey::namespaced(TRACKED_NAMESPACE, Path::new("bar").into()),
1495                window,
1496                cx,
1497            );
1498            diff.editor.clone()
1499        });
1500        assert_state_with_diff(
1501            &editor,
1502            cx,
1503            &"
1504                - ˇbar
1505                + BAR
1506
1507                - foo
1508                + FOO
1509            "
1510            .unindent(),
1511        );
1512    }
1513
1514    #[gpui::test]
1515    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1516        init_test(cx);
1517
1518        let fs = FakeFs::new(cx.executor());
1519        fs.insert_tree(
1520            path!("/project"),
1521            json!({
1522                ".git": {},
1523                "foo": "modified\n",
1524            }),
1525        )
1526        .await;
1527        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1528        let (workspace, cx) =
1529            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1530        let buffer = project
1531            .update(cx, |project, cx| {
1532                project.open_local_buffer(path!("/project/foo"), cx)
1533            })
1534            .await
1535            .unwrap();
1536        let buffer_editor = cx.new_window_entity(|window, cx| {
1537            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1538        });
1539        let diff = cx.new_window_entity(|window, cx| {
1540            ProjectDiff::new(project.clone(), workspace, window, cx)
1541        });
1542        cx.run_until_parked();
1543
1544        fs.set_head_for_repo(
1545            path!("/project/.git").as_ref(),
1546            &[("foo".into(), "original\n".into())],
1547            "deadbeef",
1548        );
1549        cx.run_until_parked();
1550
1551        let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1552
1553        assert_state_with_diff(
1554            &diff_editor,
1555            cx,
1556            &"
1557                - original
1558                + ˇmodified
1559            "
1560            .unindent(),
1561        );
1562
1563        let prev_buffer_hunks =
1564            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1565                let snapshot = buffer_editor.snapshot(window, cx);
1566                let snapshot = &snapshot.buffer_snapshot;
1567                let prev_buffer_hunks = buffer_editor
1568                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1569                    .collect::<Vec<_>>();
1570                buffer_editor.git_restore(&Default::default(), window, cx);
1571                prev_buffer_hunks
1572            });
1573        assert_eq!(prev_buffer_hunks.len(), 1);
1574        cx.run_until_parked();
1575
1576        let new_buffer_hunks =
1577            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1578                let snapshot = buffer_editor.snapshot(window, cx);
1579                let snapshot = &snapshot.buffer_snapshot;
1580                buffer_editor
1581                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1582                    .collect::<Vec<_>>()
1583            });
1584        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1585
1586        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1587            buffer_editor.set_text("different\n", window, cx);
1588            buffer_editor.save(
1589                SaveOptions {
1590                    format: false,
1591                    autosave: false,
1592                },
1593                project.clone(),
1594                window,
1595                cx,
1596            )
1597        })
1598        .await
1599        .unwrap();
1600
1601        cx.run_until_parked();
1602
1603        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1604            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1605        });
1606
1607        assert_state_with_diff(
1608            &buffer_editor,
1609            cx,
1610            &"
1611                - original
1612                + different
1613                  ˇ"
1614            .unindent(),
1615        );
1616
1617        assert_state_with_diff(
1618            &diff_editor,
1619            cx,
1620            &"
1621                - original
1622                + different
1623                  ˇ"
1624            .unindent(),
1625        );
1626    }
1627
1628    use crate::{
1629        conflict_view::resolve_conflict,
1630        project_diff::{self, ProjectDiff},
1631    };
1632
1633    #[gpui::test]
1634    async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1635        init_test(cx);
1636
1637        let fs = FakeFs::new(cx.executor());
1638        fs.insert_tree(
1639            "/a",
1640            json!({
1641                ".git": {},
1642                "a.txt": "created\n",
1643                "b.txt": "really changed\n",
1644                "c.txt": "unchanged\n"
1645            }),
1646        )
1647        .await;
1648
1649        fs.set_git_content_for_repo(
1650            Path::new("/a/.git"),
1651            &[
1652                ("b.txt".into(), "before\n".to_string(), None),
1653                ("c.txt".into(), "unchanged\n".to_string(), None),
1654                ("d.txt".into(), "deleted\n".to_string(), None),
1655            ],
1656        );
1657
1658        let project = Project::test(fs, [Path::new("/a")], cx).await;
1659        let (workspace, cx) =
1660            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1661
1662        cx.run_until_parked();
1663
1664        cx.focus(&workspace);
1665        cx.update(|window, cx| {
1666            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1667        });
1668
1669        cx.run_until_parked();
1670
1671        let item = workspace.update(cx, |workspace, cx| {
1672            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1673        });
1674        cx.focus(&item);
1675        let editor = item.read_with(cx, |item, _| item.editor.clone());
1676
1677        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1678
1679        cx.assert_excerpts_with_selections(indoc!(
1680            "
1681            [EXCERPT]
1682            before
1683            really changed
1684            [EXCERPT]
1685            [FOLDED]
1686            [EXCERPT]
1687            ˇcreated
1688        "
1689        ));
1690
1691        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1692
1693        cx.assert_excerpts_with_selections(indoc!(
1694            "
1695            [EXCERPT]
1696            before
1697            really changed
1698            [EXCERPT]
1699            ˇ[FOLDED]
1700            [EXCERPT]
1701            created
1702        "
1703        ));
1704
1705        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1706
1707        cx.assert_excerpts_with_selections(indoc!(
1708            "
1709            [EXCERPT]
1710            ˇbefore
1711            really changed
1712            [EXCERPT]
1713            [FOLDED]
1714            [EXCERPT]
1715            created
1716        "
1717        ));
1718    }
1719
1720    #[gpui::test]
1721    async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1722        init_test(cx);
1723
1724        let git_contents = indoc! {r#"
1725            #[rustfmt::skip]
1726            fn main() {
1727                let x = 0.0; // this line will be removed
1728                // 1
1729                // 2
1730                // 3
1731                let y = 0.0; // this line will be removed
1732                // 1
1733                // 2
1734                // 3
1735                let arr = [
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                    0.0, // this line will be removed
1740                ];
1741            }
1742        "#};
1743        let buffer_contents = indoc! {"
1744            #[rustfmt::skip]
1745            fn main() {
1746                // 1
1747                // 2
1748                // 3
1749                // 1
1750                // 2
1751                // 3
1752                let arr = [
1753                ];
1754            }
1755        "};
1756
1757        let fs = FakeFs::new(cx.executor());
1758        fs.insert_tree(
1759            "/a",
1760            json!({
1761                ".git": {},
1762                "main.rs": buffer_contents,
1763            }),
1764        )
1765        .await;
1766
1767        fs.set_git_content_for_repo(
1768            Path::new("/a/.git"),
1769            &[("main.rs".into(), git_contents.to_owned(), None)],
1770        );
1771
1772        let project = Project::test(fs, [Path::new("/a")], cx).await;
1773        let (workspace, cx) =
1774            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1775
1776        cx.run_until_parked();
1777
1778        cx.focus(&workspace);
1779        cx.update(|window, cx| {
1780            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1781        });
1782
1783        cx.run_until_parked();
1784
1785        let item = workspace.update(cx, |workspace, cx| {
1786            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1787        });
1788        cx.focus(&item);
1789        let editor = item.read_with(cx, |item, _| item.editor.clone());
1790
1791        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1792
1793        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1794
1795        cx.dispatch_action(editor::actions::GoToHunk);
1796        cx.dispatch_action(editor::actions::GoToHunk);
1797        cx.dispatch_action(git::Restore);
1798        cx.dispatch_action(editor::actions::MoveToBeginning);
1799
1800        cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1801    }
1802
1803    #[gpui::test]
1804    async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1805        init_test(cx);
1806
1807        let fs = FakeFs::new(cx.executor());
1808        fs.insert_tree(
1809            path!("/project"),
1810            json!({
1811                ".git": {},
1812                "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1813            }),
1814        )
1815        .await;
1816        fs.set_status_for_repo(
1817            Path::new(path!("/project/.git")),
1818            &[(
1819                Path::new("foo"),
1820                UnmergedStatus {
1821                    first_head: UnmergedStatusCode::Updated,
1822                    second_head: UnmergedStatusCode::Updated,
1823                }
1824                .into(),
1825            )],
1826        );
1827        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1828        let (workspace, cx) =
1829            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1830        let diff = cx.new_window_entity(|window, cx| {
1831            ProjectDiff::new(project.clone(), workspace, window, cx)
1832        });
1833        cx.run_until_parked();
1834
1835        cx.update(|window, cx| {
1836            let editor = diff.read(cx).editor.clone();
1837            let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1838            assert_eq!(excerpt_ids.len(), 1);
1839            let excerpt_id = excerpt_ids[0];
1840            let buffer = editor
1841                .read(cx)
1842                .buffer()
1843                .read(cx)
1844                .all_buffers()
1845                .into_iter()
1846                .next()
1847                .unwrap();
1848            let buffer_id = buffer.read(cx).remote_id();
1849            let conflict_set = diff
1850                .read(cx)
1851                .editor
1852                .read(cx)
1853                .addon::<ConflictAddon>()
1854                .unwrap()
1855                .conflict_set(buffer_id)
1856                .unwrap();
1857            assert!(conflict_set.read(cx).has_conflict);
1858            let snapshot = conflict_set.read(cx).snapshot();
1859            assert_eq!(snapshot.conflicts.len(), 1);
1860
1861            let ours_range = snapshot.conflicts[0].ours.clone();
1862
1863            resolve_conflict(
1864                editor.downgrade(),
1865                excerpt_id,
1866                snapshot.conflicts[0].clone(),
1867                vec![ours_range],
1868                window,
1869                cx,
1870            )
1871        })
1872        .await;
1873
1874        let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1875        let contents = String::from_utf8(contents).unwrap();
1876        assert_eq!(contents, "ours\n");
1877    }
1878}