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