project_diff.rs

   1use crate::{
   2    git_panel::{GitPanel, GitPanelAddon, GitStatusEntry},
   3    remote_button::{render_publish_button, render_push_button},
   4};
   5use anyhow::Result;
   6use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
   7use collections::HashSet;
   8use editor::{
   9    Editor, EditorEvent,
  10    actions::{GoToHunk, GoToPreviousHunk},
  11    scroll::Autoscroll,
  12};
  13use futures::StreamExt;
  14use git::{
  15    Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll, UnstageAndNext,
  16    repository::{Branch, Upstream, UpstreamTracking, UpstreamTrackingStatus},
  17    status::FileStatus,
  18};
  19use gpui::{
  20    Action, AnyElement, AnyView, App, AppContext as _, AsyncWindowContext, Entity, EventEmitter,
  21    FocusHandle, Focusable, Render, Subscription, Task, WeakEntity, actions,
  22};
  23use language::{Anchor, Buffer, Capability, OffsetRangeExt};
  24use multi_buffer::{MultiBuffer, PathKey};
  25use project::{
  26    Project, ProjectPath,
  27    git_store::{GitStore, GitStoreEvent, RepositoryEvent},
  28};
  29use std::any::{Any, TypeId};
  30use theme::ActiveTheme;
  31use ui::{KeyBinding, Tooltip, prelude::*, vertical_divider};
  32use util::ResultExt as _;
  33use workspace::{
  34    CloseActiveItem, ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation,
  35    ToolbarItemView, Workspace,
  36    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
  37    searchable::SearchableItemHandle,
  38};
  39
  40actions!(git, [Diff, Add]);
  41
  42pub struct ProjectDiff {
  43    project: Entity<Project>,
  44    multibuffer: Entity<MultiBuffer>,
  45    editor: Entity<Editor>,
  46    git_store: Entity<GitStore>,
  47    workspace: WeakEntity<Workspace>,
  48    focus_handle: FocusHandle,
  49    update_needed: postage::watch::Sender<()>,
  50    pending_scroll: Option<PathKey>,
  51    current_branch: Option<Branch>,
  52    _task: Task<Result<()>>,
  53    _subscription: Subscription,
  54}
  55
  56#[derive(Debug)]
  57struct DiffBuffer {
  58    path_key: PathKey,
  59    buffer: Entity<Buffer>,
  60    diff: Entity<BufferDiff>,
  61    file_status: FileStatus,
  62}
  63
  64const CONFLICT_NAMESPACE: u32 = 0;
  65const TRACKED_NAMESPACE: u32 = 1;
  66const NEW_NAMESPACE: u32 = 2;
  67
  68impl ProjectDiff {
  69    pub(crate) fn register(workspace: &mut Workspace, cx: &mut Context<Workspace>) {
  70        workspace.register_action(Self::deploy);
  71        workspace.register_action(|workspace, _: &Add, window, cx| {
  72            Self::deploy(workspace, &Diff, window, cx);
  73        });
  74        workspace::register_serializable_item::<ProjectDiff>(cx);
  75    }
  76
  77    fn deploy(
  78        workspace: &mut Workspace,
  79        _: &Diff,
  80        window: &mut Window,
  81        cx: &mut Context<Workspace>,
  82    ) {
  83        Self::deploy_at(workspace, None, window, cx)
  84    }
  85
  86    pub fn deploy_at(
  87        workspace: &mut Workspace,
  88        entry: Option<GitStatusEntry>,
  89        window: &mut Window,
  90        cx: &mut Context<Workspace>,
  91    ) {
  92        telemetry::event!(
  93            "Git Diff Opened",
  94            source = if entry.is_some() {
  95                "Git Panel"
  96            } else {
  97                "Action"
  98            }
  99        );
 100        let project_diff = if let Some(existing) = workspace.item_of_type::<Self>(cx) {
 101            workspace.activate_item(&existing, true, true, window, cx);
 102            existing
 103        } else {
 104            let workspace_handle = cx.entity();
 105            let project_diff =
 106                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
 107            workspace.add_item_to_active_pane(
 108                Box::new(project_diff.clone()),
 109                None,
 110                true,
 111                window,
 112                cx,
 113            );
 114            project_diff
 115        };
 116        if let Some(entry) = entry {
 117            project_diff.update(cx, |project_diff, cx| {
 118                project_diff.move_to_entry(entry, window, cx);
 119            })
 120        }
 121    }
 122
 123    pub fn autoscroll(&self, cx: &mut Context<Self>) {
 124        self.editor.update(cx, |editor, cx| {
 125            editor.request_autoscroll(Autoscroll::fit(), cx);
 126        })
 127    }
 128
 129    fn new(
 130        project: Entity<Project>,
 131        workspace: Entity<Workspace>,
 132        window: &mut Window,
 133        cx: &mut Context<Self>,
 134    ) -> Self {
 135        let focus_handle = cx.focus_handle();
 136        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 137
 138        let editor = cx.new(|cx| {
 139            let mut diff_display_editor =
 140                Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
 141            diff_display_editor.disable_inline_diagnostics();
 142            diff_display_editor.set_expand_all_diff_hunks(cx);
 143            diff_display_editor.register_addon(GitPanelAddon {
 144                workspace: workspace.downgrade(),
 145            });
 146            diff_display_editor
 147        });
 148        cx.subscribe_in(&editor, window, Self::handle_editor_event)
 149            .detach();
 150
 151        let git_store = project.read(cx).git_store().clone();
 152        let git_store_subscription = cx.subscribe_in(
 153            &git_store,
 154            window,
 155            move |this, _git_store, event, _window, _cx| match event {
 156                GitStoreEvent::ActiveRepositoryChanged(_)
 157                | GitStoreEvent::RepositoryUpdated(_, RepositoryEvent::Updated { .. }, true) => {
 158                    *this.update_needed.borrow_mut() = ();
 159                }
 160                _ => {}
 161            },
 162        );
 163
 164        let (mut send, recv) = postage::watch::channel::<()>();
 165        let worker = window.spawn(cx, {
 166            let this = cx.weak_entity();
 167            async |cx| Self::handle_status_updates(this, recv, cx).await
 168        });
 169        // Kick off a refresh immediately
 170        *send.borrow_mut() = ();
 171
 172        Self {
 173            project,
 174            git_store: git_store.clone(),
 175            workspace: workspace.downgrade(),
 176            focus_handle,
 177            editor,
 178            multibuffer,
 179            pending_scroll: None,
 180            update_needed: send,
 181            current_branch: None,
 182            _task: worker,
 183            _subscription: git_store_subscription,
 184        }
 185    }
 186
 187    pub fn move_to_entry(
 188        &mut self,
 189        entry: GitStatusEntry,
 190        window: &mut Window,
 191        cx: &mut Context<Self>,
 192    ) {
 193        let Some(git_repo) = self.git_store.read(cx).active_repository() else {
 194            return;
 195        };
 196        let repo = git_repo.read(cx);
 197
 198        let namespace = if repo.has_conflict(&entry.repo_path) {
 199            CONFLICT_NAMESPACE
 200        } else if entry.status.is_created() {
 201            NEW_NAMESPACE
 202        } else {
 203            TRACKED_NAMESPACE
 204        };
 205
 206        let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
 207
 208        self.move_to_path(path_key, window, cx)
 209    }
 210
 211    pub fn active_path(&self, cx: &App) -> Option<ProjectPath> {
 212        let editor = self.editor.read(cx);
 213        let position = editor.selections.newest_anchor().head();
 214        let multi_buffer = editor.buffer().read(cx);
 215        let (_, buffer, _) = multi_buffer.excerpt_containing(position, cx)?;
 216
 217        let file = buffer.read(cx).file()?;
 218        Some(ProjectPath {
 219            worktree_id: file.worktree_id(cx),
 220            path: file.path().clone(),
 221        })
 222    }
 223
 224    fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
 225        if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
 226            self.editor.update(cx, |editor, cx| {
 227                editor.change_selections(Some(Autoscroll::focused()), window, cx, |s| {
 228                    s.select_ranges([position..position]);
 229                })
 230            });
 231        } else {
 232            self.pending_scroll = Some(path_key);
 233        }
 234    }
 235
 236    fn button_states(&self, cx: &App) -> ButtonStates {
 237        let editor = self.editor.read(cx);
 238        let snapshot = self.multibuffer.read(cx).snapshot(cx);
 239        let prev_next = snapshot.diff_hunks().skip(1).next().is_some();
 240        let mut selection = true;
 241
 242        let mut ranges = editor
 243            .selections
 244            .disjoint_anchor_ranges()
 245            .collect::<Vec<_>>();
 246        if !ranges.iter().any(|range| range.start != range.end) {
 247            selection = false;
 248            if let Some((excerpt_id, buffer, range)) = self.editor.read(cx).active_excerpt(cx) {
 249                ranges = vec![multi_buffer::Anchor::range_in_buffer(
 250                    excerpt_id,
 251                    buffer.read(cx).remote_id(),
 252                    range,
 253                )];
 254            } else {
 255                ranges = Vec::default();
 256            }
 257        }
 258        let mut has_staged_hunks = false;
 259        let mut has_unstaged_hunks = false;
 260        for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
 261            match hunk.secondary_status {
 262                DiffHunkSecondaryStatus::HasSecondaryHunk
 263                | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending => {
 264                    has_unstaged_hunks = true;
 265                }
 266                DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
 267                    has_staged_hunks = true;
 268                    has_unstaged_hunks = true;
 269                }
 270                DiffHunkSecondaryStatus::NoSecondaryHunk
 271                | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending => {
 272                    has_staged_hunks = true;
 273                }
 274            }
 275        }
 276        let mut stage_all = false;
 277        let mut unstage_all = false;
 278        self.workspace
 279            .read_with(cx, |workspace, cx| {
 280                if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
 281                    let git_panel = git_panel.read(cx);
 282                    stage_all = git_panel.can_stage_all();
 283                    unstage_all = git_panel.can_unstage_all();
 284                }
 285            })
 286            .ok();
 287
 288        return ButtonStates {
 289            stage: has_unstaged_hunks,
 290            unstage: has_staged_hunks,
 291            prev_next,
 292            selection,
 293            stage_all,
 294            unstage_all,
 295        };
 296    }
 297
 298    fn handle_editor_event(
 299        &mut self,
 300        editor: &Entity<Editor>,
 301        event: &EditorEvent,
 302        window: &mut Window,
 303        cx: &mut Context<Self>,
 304    ) {
 305        match event {
 306            EditorEvent::SelectionsChanged { local: true } => {
 307                let Some(project_path) = self.active_path(cx) else {
 308                    return;
 309                };
 310                self.workspace
 311                    .update(cx, |workspace, cx| {
 312                        if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
 313                            git_panel.update(cx, |git_panel, cx| {
 314                                git_panel.select_entry_by_path(project_path, window, cx)
 315                            })
 316                        }
 317                    })
 318                    .ok();
 319            }
 320            _ => {}
 321        }
 322        if editor.focus_handle(cx).contains_focused(window, cx) {
 323            if self.multibuffer.read(cx).is_empty() {
 324                self.focus_handle.focus(window)
 325            }
 326        }
 327    }
 328
 329    fn load_buffers(&mut self, cx: &mut Context<Self>) -> Vec<Task<Result<DiffBuffer>>> {
 330        let Some(repo) = self.git_store.read(cx).active_repository() else {
 331            self.multibuffer.update(cx, |multibuffer, cx| {
 332                multibuffer.clear(cx);
 333            });
 334            return vec![];
 335        };
 336
 337        let mut previous_paths = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
 338
 339        let mut result = vec![];
 340        repo.update(cx, |repo, cx| {
 341            for entry in repo.cached_status() {
 342                if !entry.status.has_changes() {
 343                    continue;
 344                }
 345                let Some(project_path) = repo.repo_path_to_project_path(&entry.repo_path, cx)
 346                else {
 347                    continue;
 348                };
 349                let namespace = if repo.has_conflict(&entry.repo_path) {
 350                    CONFLICT_NAMESPACE
 351                } else if entry.status.is_created() {
 352                    NEW_NAMESPACE
 353                } else {
 354                    TRACKED_NAMESPACE
 355                };
 356                let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
 357
 358                previous_paths.remove(&path_key);
 359                let load_buffer = self
 360                    .project
 361                    .update(cx, |project, cx| project.open_buffer(project_path, cx));
 362
 363                let project = self.project.clone();
 364                result.push(cx.spawn(async move |_, cx| {
 365                    let buffer = load_buffer.await?;
 366                    let changes = project
 367                        .update(cx, |project, cx| {
 368                            project.open_uncommitted_diff(buffer.clone(), cx)
 369                        })?
 370                        .await?;
 371                    Ok(DiffBuffer {
 372                        path_key,
 373                        buffer,
 374                        diff: changes,
 375                        file_status: entry.status,
 376                    })
 377                }));
 378            }
 379        });
 380        self.multibuffer.update(cx, |multibuffer, cx| {
 381            for path in previous_paths {
 382                multibuffer.remove_excerpts_for_path(path, cx);
 383            }
 384        });
 385        result
 386    }
 387
 388    fn register_buffer(
 389        &mut self,
 390        diff_buffer: DiffBuffer,
 391        window: &mut Window,
 392        cx: &mut Context<Self>,
 393    ) {
 394        let path_key = diff_buffer.path_key;
 395        let buffer = diff_buffer.buffer;
 396        let diff = diff_buffer.diff;
 397
 398        let snapshot = buffer.read(cx).snapshot();
 399        let diff = diff.read(cx);
 400        let diff_hunk_ranges = diff
 401            .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
 402            .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
 403            .collect::<Vec<_>>();
 404
 405        let (was_empty, is_excerpt_newly_added) = self.multibuffer.update(cx, |multibuffer, cx| {
 406            let was_empty = multibuffer.is_empty();
 407            let (_, is_newly_added) = multibuffer.set_excerpts_for_path(
 408                path_key.clone(),
 409                buffer,
 410                diff_hunk_ranges,
 411                editor::DEFAULT_MULTIBUFFER_CONTEXT,
 412                cx,
 413            );
 414            (was_empty, is_newly_added)
 415        });
 416
 417        self.editor.update(cx, |editor, cx| {
 418            if was_empty {
 419                editor.change_selections(None, window, cx, |selections| {
 420                    // TODO select the very beginning (possibly inside a deletion)
 421                    selections.select_ranges([0..0])
 422                });
 423            }
 424            if is_excerpt_newly_added && diff_buffer.file_status.is_deleted() {
 425                editor.fold_buffer(snapshot.text.remote_id(), cx)
 426            }
 427        });
 428
 429        if self.multibuffer.read(cx).is_empty()
 430            && self
 431                .editor
 432                .read(cx)
 433                .focus_handle(cx)
 434                .contains_focused(window, cx)
 435        {
 436            self.focus_handle.focus(window);
 437        } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
 438            self.editor.update(cx, |editor, cx| {
 439                editor.focus_handle(cx).focus(window);
 440            });
 441        }
 442        if self.pending_scroll.as_ref() == Some(&path_key) {
 443            self.move_to_path(path_key, window, cx);
 444        }
 445    }
 446
 447    pub async fn handle_status_updates(
 448        this: WeakEntity<Self>,
 449        mut recv: postage::watch::Receiver<()>,
 450        cx: &mut AsyncWindowContext,
 451    ) -> Result<()> {
 452        while let Some(_) = recv.next().await {
 453            this.update(cx, |this, cx| {
 454                let new_branch = this
 455                    .git_store
 456                    .read(cx)
 457                    .active_repository()
 458                    .and_then(|active_repository| active_repository.read(cx).branch.clone());
 459                if new_branch != this.current_branch {
 460                    this.current_branch = new_branch;
 461                    cx.notify();
 462                }
 463            })?;
 464
 465            let buffers_to_load = this.update(cx, |this, cx| this.load_buffers(cx))?;
 466            for buffer_to_load in buffers_to_load {
 467                if let Some(buffer) = buffer_to_load.await.log_err() {
 468                    cx.update(|window, cx| {
 469                        this.update(cx, |this, cx| this.register_buffer(buffer, window, cx))
 470                            .ok();
 471                    })?;
 472                }
 473            }
 474            this.update(cx, |this, cx| {
 475                this.pending_scroll.take();
 476                cx.notify();
 477            })?;
 478        }
 479
 480        Ok(())
 481    }
 482
 483    #[cfg(any(test, feature = "test-support"))]
 484    pub fn excerpt_paths(&self, cx: &App) -> Vec<String> {
 485        self.multibuffer
 486            .read(cx)
 487            .excerpt_paths()
 488            .map(|key| key.path().to_string_lossy().to_string())
 489            .collect()
 490    }
 491}
 492
 493impl EventEmitter<EditorEvent> for ProjectDiff {}
 494
 495impl Focusable for ProjectDiff {
 496    fn focus_handle(&self, cx: &App) -> FocusHandle {
 497        if self.multibuffer.read(cx).is_empty() {
 498            self.focus_handle.clone()
 499        } else {
 500            self.editor.focus_handle(cx)
 501        }
 502    }
 503}
 504
 505impl Item for ProjectDiff {
 506    type Event = EditorEvent;
 507
 508    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 509        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
 510    }
 511
 512    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 513        Editor::to_item_events(event, f)
 514    }
 515
 516    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 517        self.editor
 518            .update(cx, |editor, cx| editor.deactivated(window, cx));
 519    }
 520
 521    fn navigate(
 522        &mut self,
 523        data: Box<dyn Any>,
 524        window: &mut Window,
 525        cx: &mut Context<Self>,
 526    ) -> bool {
 527        self.editor
 528            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 529    }
 530
 531    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 532        Some("Project Diff".into())
 533    }
 534
 535    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
 536        Label::new("Uncommitted Changes")
 537            .color(if params.selected {
 538                Color::Default
 539            } else {
 540                Color::Muted
 541            })
 542            .into_any_element()
 543    }
 544
 545    fn telemetry_event_text(&self) -> Option<&'static str> {
 546        Some("Project Diff Opened")
 547    }
 548
 549    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 550        Some(Box::new(self.editor.clone()))
 551    }
 552
 553    fn for_each_project_item(
 554        &self,
 555        cx: &App,
 556        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 557    ) {
 558        self.editor.for_each_project_item(cx, f)
 559    }
 560
 561    fn is_singleton(&self, _: &App) -> bool {
 562        false
 563    }
 564
 565    fn set_nav_history(
 566        &mut self,
 567        nav_history: ItemNavHistory,
 568        _: &mut Window,
 569        cx: &mut Context<Self>,
 570    ) {
 571        self.editor.update(cx, |editor, _| {
 572            editor.set_nav_history(Some(nav_history));
 573        });
 574    }
 575
 576    fn clone_on_split(
 577        &self,
 578        _workspace_id: Option<workspace::WorkspaceId>,
 579        window: &mut Window,
 580        cx: &mut Context<Self>,
 581    ) -> Option<Entity<Self>>
 582    where
 583        Self: Sized,
 584    {
 585        let workspace = self.workspace.upgrade()?;
 586        Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
 587    }
 588
 589    fn is_dirty(&self, cx: &App) -> bool {
 590        self.multibuffer.read(cx).is_dirty(cx)
 591    }
 592
 593    fn has_conflict(&self, cx: &App) -> bool {
 594        self.multibuffer.read(cx).has_conflict(cx)
 595    }
 596
 597    fn can_save(&self, _: &App) -> bool {
 598        true
 599    }
 600
 601    fn save(
 602        &mut self,
 603        format: bool,
 604        project: Entity<Project>,
 605        window: &mut Window,
 606        cx: &mut Context<Self>,
 607    ) -> Task<Result<()>> {
 608        self.editor.save(format, project, window, cx)
 609    }
 610
 611    fn save_as(
 612        &mut self,
 613        _: Entity<Project>,
 614        _: ProjectPath,
 615        _window: &mut Window,
 616        _: &mut Context<Self>,
 617    ) -> Task<Result<()>> {
 618        unreachable!()
 619    }
 620
 621    fn reload(
 622        &mut self,
 623        project: Entity<Project>,
 624        window: &mut Window,
 625        cx: &mut Context<Self>,
 626    ) -> Task<Result<()>> {
 627        self.editor.reload(project, window, cx)
 628    }
 629
 630    fn act_as_type<'a>(
 631        &'a self,
 632        type_id: TypeId,
 633        self_handle: &'a Entity<Self>,
 634        _: &'a App,
 635    ) -> Option<AnyView> {
 636        if type_id == TypeId::of::<Self>() {
 637            Some(self_handle.to_any())
 638        } else if type_id == TypeId::of::<Editor>() {
 639            Some(self.editor.to_any())
 640        } else {
 641            None
 642        }
 643    }
 644
 645    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 646        ToolbarItemLocation::PrimaryLeft
 647    }
 648
 649    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 650        self.editor.breadcrumbs(theme, cx)
 651    }
 652
 653    fn added_to_workspace(
 654        &mut self,
 655        workspace: &mut Workspace,
 656        window: &mut Window,
 657        cx: &mut Context<Self>,
 658    ) {
 659        self.editor.update(cx, |editor, cx| {
 660            editor.added_to_workspace(workspace, window, cx)
 661        });
 662    }
 663}
 664
 665impl Render for ProjectDiff {
 666    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 667        let is_empty = self.multibuffer.read(cx).is_empty();
 668
 669        div()
 670            .track_focus(&self.focus_handle)
 671            .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
 672            .bg(cx.theme().colors().editor_background)
 673            .flex()
 674            .items_center()
 675            .justify_center()
 676            .size_full()
 677            .when(is_empty, |el| {
 678                let remote_button = if let Some(panel) = self
 679                    .workspace
 680                    .upgrade()
 681                    .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
 682                {
 683                    panel.update(cx, |panel, cx| panel.render_remote_button(cx))
 684                } else {
 685                    None
 686                };
 687                let keybinding_focus_handle = self.focus_handle(cx).clone();
 688                el.child(
 689                    v_flex()
 690                        .gap_1()
 691                        .child(
 692                            h_flex()
 693                                .justify_around()
 694                                .child(Label::new("No uncommitted changes")),
 695                        )
 696                        .map(|el| match remote_button {
 697                            Some(button) => el.child(h_flex().justify_around().child(button)),
 698                            None => el.child(
 699                                h_flex()
 700                                    .justify_around()
 701                                    .child(Label::new("Remote up to date")),
 702                            ),
 703                        })
 704                        .child(
 705                            h_flex().justify_around().mt_1().child(
 706                                Button::new("project-diff-close-button", "Close")
 707                                    // .style(ButtonStyle::Transparent)
 708                                    .key_binding(KeyBinding::for_action_in(
 709                                        &CloseActiveItem::default(),
 710                                        &keybinding_focus_handle,
 711                                        window,
 712                                        cx,
 713                                    ))
 714                                    .on_click(move |_, window, cx| {
 715                                        window.focus(&keybinding_focus_handle);
 716                                        window.dispatch_action(
 717                                            Box::new(CloseActiveItem::default()),
 718                                            cx,
 719                                        );
 720                                    }),
 721                            ),
 722                        ),
 723                )
 724            })
 725            .when(!is_empty, |el| el.child(self.editor.clone()))
 726    }
 727}
 728
 729impl SerializableItem for ProjectDiff {
 730    fn serialized_item_kind() -> &'static str {
 731        "ProjectDiff"
 732    }
 733
 734    fn cleanup(
 735        _: workspace::WorkspaceId,
 736        _: Vec<workspace::ItemId>,
 737        _: &mut Window,
 738        _: &mut App,
 739    ) -> Task<Result<()>> {
 740        Task::ready(Ok(()))
 741    }
 742
 743    fn deserialize(
 744        _project: Entity<Project>,
 745        workspace: WeakEntity<Workspace>,
 746        _workspace_id: workspace::WorkspaceId,
 747        _item_id: workspace::ItemId,
 748        window: &mut Window,
 749        cx: &mut App,
 750    ) -> Task<Result<Entity<Self>>> {
 751        window.spawn(cx, async move |cx| {
 752            workspace.update_in(cx, |workspace, window, cx| {
 753                let workspace_handle = cx.entity();
 754                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
 755            })
 756        })
 757    }
 758
 759    fn serialize(
 760        &mut self,
 761        _workspace: &mut Workspace,
 762        _item_id: workspace::ItemId,
 763        _closing: bool,
 764        _window: &mut Window,
 765        _cx: &mut Context<Self>,
 766    ) -> Option<Task<Result<()>>> {
 767        None
 768    }
 769
 770    fn should_serialize(&self, _: &Self::Event) -> bool {
 771        false
 772    }
 773}
 774
 775pub struct ProjectDiffToolbar {
 776    project_diff: Option<WeakEntity<ProjectDiff>>,
 777    workspace: WeakEntity<Workspace>,
 778}
 779
 780impl ProjectDiffToolbar {
 781    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
 782        Self {
 783            project_diff: None,
 784            workspace: workspace.weak_handle(),
 785        }
 786    }
 787
 788    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
 789        self.project_diff.as_ref()?.upgrade()
 790    }
 791
 792    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 793        if let Some(project_diff) = self.project_diff(cx) {
 794            project_diff.focus_handle(cx).focus(window);
 795        }
 796        let action = action.boxed_clone();
 797        cx.defer(move |cx| {
 798            cx.dispatch_action(action.as_ref());
 799        })
 800    }
 801
 802    fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 803        self.workspace
 804            .update(cx, |workspace, cx| {
 805                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
 806                    panel.update(cx, |panel, cx| {
 807                        panel.stage_all(&Default::default(), window, cx);
 808                    });
 809                }
 810            })
 811            .ok();
 812    }
 813
 814    fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 815        self.workspace
 816            .update(cx, |workspace, cx| {
 817                let Some(panel) = workspace.panel::<GitPanel>(cx) else {
 818                    return;
 819                };
 820                panel.update(cx, |panel, cx| {
 821                    panel.unstage_all(&Default::default(), window, cx);
 822                });
 823            })
 824            .ok();
 825    }
 826}
 827
 828impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
 829
 830impl ToolbarItemView for ProjectDiffToolbar {
 831    fn set_active_pane_item(
 832        &mut self,
 833        active_pane_item: Option<&dyn ItemHandle>,
 834        _: &mut Window,
 835        cx: &mut Context<Self>,
 836    ) -> ToolbarItemLocation {
 837        self.project_diff = active_pane_item
 838            .and_then(|item| item.act_as::<ProjectDiff>(cx))
 839            .map(|entity| entity.downgrade());
 840        if self.project_diff.is_some() {
 841            ToolbarItemLocation::PrimaryRight
 842        } else {
 843            ToolbarItemLocation::Hidden
 844        }
 845    }
 846
 847    fn pane_focus_update(
 848        &mut self,
 849        _pane_focused: bool,
 850        _window: &mut Window,
 851        _cx: &mut Context<Self>,
 852    ) {
 853    }
 854}
 855
 856struct ButtonStates {
 857    stage: bool,
 858    unstage: bool,
 859    prev_next: bool,
 860    selection: bool,
 861    stage_all: bool,
 862    unstage_all: bool,
 863}
 864
 865impl Render for ProjectDiffToolbar {
 866    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 867        let Some(project_diff) = self.project_diff(cx) else {
 868            return div();
 869        };
 870        let focus_handle = project_diff.focus_handle(cx);
 871        let button_states = project_diff.read(cx).button_states(cx);
 872
 873        h_group_xl()
 874            .my_neg_1()
 875            .items_center()
 876            .py_1()
 877            .pl_2()
 878            .pr_1()
 879            .flex_wrap()
 880            .justify_between()
 881            .child(
 882                h_group_sm()
 883                    .when(button_states.selection, |el| {
 884                        el.child(
 885                            Button::new("stage", "Toggle Staged")
 886                                .tooltip(Tooltip::for_action_title_in(
 887                                    "Toggle Staged",
 888                                    &ToggleStaged,
 889                                    &focus_handle,
 890                                ))
 891                                .disabled(!button_states.stage && !button_states.unstage)
 892                                .on_click(cx.listener(|this, _, window, cx| {
 893                                    this.dispatch_action(&ToggleStaged, window, cx)
 894                                })),
 895                        )
 896                    })
 897                    .when(!button_states.selection, |el| {
 898                        el.child(
 899                            Button::new("stage", "Stage")
 900                                .tooltip(Tooltip::for_action_title_in(
 901                                    "Stage and go to next hunk",
 902                                    &StageAndNext,
 903                                    &focus_handle,
 904                                ))
 905                                .on_click(cx.listener(|this, _, window, cx| {
 906                                    this.dispatch_action(&StageAndNext, window, cx)
 907                                })),
 908                        )
 909                        .child(
 910                            Button::new("unstage", "Unstage")
 911                                .tooltip(Tooltip::for_action_title_in(
 912                                    "Unstage and go to next hunk",
 913                                    &UnstageAndNext,
 914                                    &focus_handle,
 915                                ))
 916                                .on_click(cx.listener(|this, _, window, cx| {
 917                                    this.dispatch_action(&UnstageAndNext, window, cx)
 918                                })),
 919                        )
 920                    }),
 921            )
 922            // n.b. the only reason these arrows are here is because we don't
 923            // support "undo" for staging so we need a way to go back.
 924            .child(
 925                h_group_sm()
 926                    .child(
 927                        IconButton::new("up", IconName::ArrowUp)
 928                            .shape(ui::IconButtonShape::Square)
 929                            .tooltip(Tooltip::for_action_title_in(
 930                                "Go to previous hunk",
 931                                &GoToPreviousHunk,
 932                                &focus_handle,
 933                            ))
 934                            .disabled(!button_states.prev_next)
 935                            .on_click(cx.listener(|this, _, window, cx| {
 936                                this.dispatch_action(&GoToPreviousHunk, window, cx)
 937                            })),
 938                    )
 939                    .child(
 940                        IconButton::new("down", IconName::ArrowDown)
 941                            .shape(ui::IconButtonShape::Square)
 942                            .tooltip(Tooltip::for_action_title_in(
 943                                "Go to next hunk",
 944                                &GoToHunk,
 945                                &focus_handle,
 946                            ))
 947                            .disabled(!button_states.prev_next)
 948                            .on_click(cx.listener(|this, _, window, cx| {
 949                                this.dispatch_action(&GoToHunk, window, cx)
 950                            })),
 951                    ),
 952            )
 953            .child(vertical_divider())
 954            .child(
 955                h_group_sm()
 956                    .when(
 957                        button_states.unstage_all && !button_states.stage_all,
 958                        |el| {
 959                            el.child(
 960                                Button::new("unstage-all", "Unstage All")
 961                                    .tooltip(Tooltip::for_action_title_in(
 962                                        "Unstage all changes",
 963                                        &UnstageAll,
 964                                        &focus_handle,
 965                                    ))
 966                                    .on_click(cx.listener(|this, _, window, cx| {
 967                                        this.unstage_all(window, cx)
 968                                    })),
 969                            )
 970                        },
 971                    )
 972                    .when(
 973                        !button_states.unstage_all || button_states.stage_all,
 974                        |el| {
 975                            el.child(
 976                                // todo make it so that changing to say "Unstaged"
 977                                // doesn't change the position.
 978                                div().child(
 979                                    Button::new("stage-all", "Stage All")
 980                                        .disabled(!button_states.stage_all)
 981                                        .tooltip(Tooltip::for_action_title_in(
 982                                            "Stage all changes",
 983                                            &StageAll,
 984                                            &focus_handle,
 985                                        ))
 986                                        .on_click(cx.listener(|this, _, window, cx| {
 987                                            this.stage_all(window, cx)
 988                                        })),
 989                                ),
 990                            )
 991                        },
 992                    )
 993                    .child(
 994                        Button::new("commit", "Commit")
 995                            .tooltip(Tooltip::for_action_title_in(
 996                                "Commit",
 997                                &Commit,
 998                                &focus_handle,
 999                            ))
1000                            .on_click(cx.listener(|this, _, window, cx| {
1001                                this.dispatch_action(&Commit, window, cx);
1002                            })),
1003                    ),
1004            )
1005    }
1006}
1007
1008#[derive(IntoElement, RegisterComponent)]
1009pub struct ProjectDiffEmptyState {
1010    pub no_repo: bool,
1011    pub can_push_and_pull: bool,
1012    pub focus_handle: Option<FocusHandle>,
1013    pub current_branch: Option<Branch>,
1014    // has_pending_commits: bool,
1015    // ahead_of_remote: bool,
1016    // no_git_repository: bool,
1017}
1018
1019impl RenderOnce for ProjectDiffEmptyState {
1020    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1021        let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1022            match self.current_branch {
1023                Some(Branch {
1024                    upstream:
1025                        Some(Upstream {
1026                            tracking:
1027                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1028                                    ahead, behind, ..
1029                                }),
1030                            ..
1031                        }),
1032                    ..
1033                }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0) => true,
1034                _ => false,
1035            }
1036        };
1037
1038        let change_count = |current_branch: &Branch| -> (usize, usize) {
1039            match current_branch {
1040                Branch {
1041                    upstream:
1042                        Some(Upstream {
1043                            tracking:
1044                                UpstreamTracking::Tracked(UpstreamTrackingStatus {
1045                                    ahead, behind, ..
1046                                }),
1047                            ..
1048                        }),
1049                    ..
1050                } => (*ahead as usize, *behind as usize),
1051                _ => (0, 0),
1052            }
1053        };
1054
1055        let not_ahead_or_behind = status_against_remote(0, 0);
1056        let ahead_of_remote = status_against_remote(1, 0);
1057        let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1058            branch.upstream.is_none()
1059        } else {
1060            false
1061        };
1062
1063        let has_branch_container = |branch: &Branch| {
1064            h_flex()
1065                .max_w(px(420.))
1066                .bg(cx.theme().colors().text.opacity(0.05))
1067                .border_1()
1068                .border_color(cx.theme().colors().border)
1069                .rounded_sm()
1070                .gap_8()
1071                .px_6()
1072                .py_4()
1073                .map(|this| {
1074                    if ahead_of_remote {
1075                        let ahead_count = change_count(branch).0;
1076                        let ahead_string = format!("{} Commits Ahead", ahead_count);
1077                        this.child(
1078                            v_flex()
1079                                .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1080                                .child(
1081                                    Label::new(format!("Push your changes to {}", branch.name))
1082                                        .color(Color::Muted),
1083                                ),
1084                        )
1085                        .child(div().child(render_push_button(
1086                            self.focus_handle,
1087                            "push".into(),
1088                            ahead_count as u32,
1089                        )))
1090                    } else if branch_not_on_remote {
1091                        this.child(
1092                            v_flex()
1093                                .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1094                                .child(
1095                                    Label::new(format!("Create {} on remote", branch.name))
1096                                        .color(Color::Muted),
1097                                ),
1098                        )
1099                        .child(
1100                            div().child(render_publish_button(self.focus_handle, "publish".into())),
1101                        )
1102                    } else {
1103                        this.child(Label::new("Remote status unknown").color(Color::Muted))
1104                    }
1105                })
1106        };
1107
1108        v_flex().size_full().items_center().justify_center().child(
1109            v_flex()
1110                .gap_1()
1111                .when(self.no_repo, |this| {
1112                    // TODO: add git init
1113                    this.text_center()
1114                        .child(Label::new("No Repository").color(Color::Muted))
1115                })
1116                .map(|this| {
1117                    if not_ahead_or_behind && self.current_branch.is_some() {
1118                        this.text_center()
1119                            .child(Label::new("No Changes").color(Color::Muted))
1120                    } else {
1121                        this.when_some(self.current_branch.as_ref(), |this, branch| {
1122                            this.child(has_branch_container(&branch))
1123                        })
1124                    }
1125                }),
1126        )
1127    }
1128}
1129
1130// .when(self.can_push_and_pull, |this| {
1131//     let remote_button = crate::render_remote_button(
1132//         "project-diff-remote-button",
1133//         &branch,
1134//         self.focus_handle.clone(),
1135//         false,
1136//     );
1137
1138//     match remote_button {
1139//         Some(button) => {
1140//             this.child(h_flex().justify_around().child(button))
1141//         }
1142//         None => this.child(
1143//             h_flex()
1144//                 .justify_around()
1145//                 .child(Label::new("Remote up to date")),
1146//         ),
1147//     }
1148// }),
1149//
1150// // .map(|this| {
1151//     this.child(h_flex().justify_around().mt_1().child(
1152//         Button::new("project-diff-close-button", "Close").when_some(
1153//             self.focus_handle.clone(),
1154//             |this, focus_handle| {
1155//                 this.key_binding(KeyBinding::for_action_in(
1156//                     &CloseActiveItem::default(),
1157//                     &focus_handle,
1158//                     window,
1159//                     cx,
1160//                 ))
1161//                 .on_click(move |_, window, cx| {
1162//                     window.focus(&focus_handle);
1163//                     window
1164//                         .dispatch_action(Box::new(CloseActiveItem::default()), cx);
1165//                 })
1166//             },
1167//         ),
1168//     ))
1169// }),
1170
1171mod preview {
1172    use git::repository::{
1173        Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1174    };
1175    use ui::prelude::*;
1176
1177    use super::ProjectDiffEmptyState;
1178
1179    // View this component preview using `workspace: open component-preview`
1180    impl Component for ProjectDiffEmptyState {
1181        fn scope() -> ComponentScope {
1182            ComponentScope::VersionControl
1183        }
1184
1185        fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1186            let unknown_upstream: Option<UpstreamTracking> = None;
1187            let ahead_of_upstream: Option<UpstreamTracking> = Some(
1188                UpstreamTrackingStatus {
1189                    ahead: 2,
1190                    behind: 0,
1191                }
1192                .into(),
1193            );
1194
1195            let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1196                UpstreamTrackingStatus {
1197                    ahead: 0,
1198                    behind: 0,
1199                }
1200                .into(),
1201            );
1202
1203            fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1204                Branch {
1205                    is_head: true,
1206                    name: "some-branch".into(),
1207                    upstream: upstream.map(|tracking| Upstream {
1208                        ref_name: "origin/some-branch".into(),
1209                        tracking,
1210                    }),
1211                    most_recent_commit: Some(CommitSummary {
1212                        sha: "abc123".into(),
1213                        subject: "Modify stuff".into(),
1214                        commit_timestamp: 1710932954,
1215                        has_parent: true,
1216                    }),
1217                }
1218            }
1219
1220            let no_repo_state = ProjectDiffEmptyState {
1221                no_repo: true,
1222                can_push_and_pull: false,
1223                focus_handle: None,
1224                current_branch: None,
1225            };
1226
1227            let no_changes_state = ProjectDiffEmptyState {
1228                no_repo: false,
1229                can_push_and_pull: true,
1230                focus_handle: None,
1231                current_branch: Some(branch(not_ahead_or_behind_upstream)),
1232            };
1233
1234            let ahead_of_upstream_state = ProjectDiffEmptyState {
1235                no_repo: false,
1236                can_push_and_pull: true,
1237                focus_handle: None,
1238                current_branch: Some(branch(ahead_of_upstream)),
1239            };
1240
1241            let unknown_upstream_state = ProjectDiffEmptyState {
1242                no_repo: false,
1243                can_push_and_pull: true,
1244                focus_handle: None,
1245                current_branch: Some(branch(unknown_upstream)),
1246            };
1247
1248            let (width, height) = (px(480.), px(320.));
1249
1250            Some(
1251                v_flex()
1252                    .gap_6()
1253                    .children(vec![
1254                        example_group(vec![
1255                            single_example(
1256                                "No Repo",
1257                                div()
1258                                    .w(width)
1259                                    .h(height)
1260                                    .child(no_repo_state)
1261                                    .into_any_element(),
1262                            ),
1263                            single_example(
1264                                "No Changes",
1265                                div()
1266                                    .w(width)
1267                                    .h(height)
1268                                    .child(no_changes_state)
1269                                    .into_any_element(),
1270                            ),
1271                            single_example(
1272                                "Unknown Upstream",
1273                                div()
1274                                    .w(width)
1275                                    .h(height)
1276                                    .child(unknown_upstream_state)
1277                                    .into_any_element(),
1278                            ),
1279                            single_example(
1280                                "Ahead of Remote",
1281                                div()
1282                                    .w(width)
1283                                    .h(height)
1284                                    .child(ahead_of_upstream_state)
1285                                    .into_any_element(),
1286                            ),
1287                        ])
1288                        .vertical(),
1289                    ])
1290                    .into_any_element(),
1291            )
1292        }
1293    }
1294}
1295
1296#[cfg(not(target_os = "windows"))]
1297#[cfg(test)]
1298mod tests {
1299    use db::indoc;
1300    use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1301    use gpui::TestAppContext;
1302    use project::FakeFs;
1303    use serde_json::json;
1304    use settings::SettingsStore;
1305    use std::path::Path;
1306    use unindent::Unindent as _;
1307    use util::path;
1308
1309    use super::*;
1310
1311    #[ctor::ctor]
1312    fn init_logger() {
1313        env_logger::init();
1314    }
1315
1316    fn init_test(cx: &mut TestAppContext) {
1317        cx.update(|cx| {
1318            let store = SettingsStore::test(cx);
1319            cx.set_global(store);
1320            theme::init(theme::LoadThemes::JustBase, cx);
1321            language::init(cx);
1322            Project::init_settings(cx);
1323            workspace::init_settings(cx);
1324            editor::init(cx);
1325            crate::init(cx);
1326        });
1327    }
1328
1329    #[gpui::test]
1330    async fn test_save_after_restore(cx: &mut TestAppContext) {
1331        init_test(cx);
1332
1333        let fs = FakeFs::new(cx.executor());
1334        fs.insert_tree(
1335            path!("/project"),
1336            json!({
1337                ".git": {},
1338                "foo.txt": "FOO\n",
1339            }),
1340        )
1341        .await;
1342        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1343        let (workspace, cx) =
1344            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1345        let diff = cx.new_window_entity(|window, cx| {
1346            ProjectDiff::new(project.clone(), workspace, window, cx)
1347        });
1348        cx.run_until_parked();
1349
1350        fs.set_head_for_repo(
1351            path!("/project/.git").as_ref(),
1352            &[("foo.txt".into(), "foo\n".into())],
1353        );
1354        fs.set_index_for_repo(
1355            path!("/project/.git").as_ref(),
1356            &[("foo.txt".into(), "foo\n".into())],
1357        );
1358        cx.run_until_parked();
1359
1360        let editor = diff.update(cx, |diff, _| diff.editor.clone());
1361        assert_state_with_diff(
1362            &editor,
1363            cx,
1364            &"
1365                - foo
1366                + ˇFOO
1367            "
1368            .unindent(),
1369        );
1370
1371        editor.update_in(cx, |editor, window, cx| {
1372            editor.git_restore(&Default::default(), window, cx);
1373        });
1374        cx.run_until_parked();
1375
1376        assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1377
1378        let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1379        assert_eq!(text, "foo\n");
1380    }
1381
1382    #[gpui::test]
1383    async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1384        init_test(cx);
1385
1386        let fs = FakeFs::new(cx.executor());
1387        fs.insert_tree(
1388            path!("/project"),
1389            json!({
1390                ".git": {},
1391                "bar": "BAR\n",
1392                "foo": "FOO\n",
1393            }),
1394        )
1395        .await;
1396        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1397        let (workspace, cx) =
1398            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1399        let diff = cx.new_window_entity(|window, cx| {
1400            ProjectDiff::new(project.clone(), workspace, window, cx)
1401        });
1402        cx.run_until_parked();
1403
1404        fs.set_head_and_index_for_repo(
1405            path!("/project/.git").as_ref(),
1406            &[
1407                ("bar".into(), "bar\n".into()),
1408                ("foo".into(), "foo\n".into()),
1409            ],
1410        );
1411        cx.run_until_parked();
1412
1413        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1414            diff.move_to_path(
1415                PathKey::namespaced(TRACKED_NAMESPACE, Path::new("foo").into()),
1416                window,
1417                cx,
1418            );
1419            diff.editor.clone()
1420        });
1421        assert_state_with_diff(
1422            &editor,
1423            cx,
1424            &"
1425                - bar
1426                + BAR
1427
1428                - ˇfoo
1429                + FOO
1430            "
1431            .unindent(),
1432        );
1433
1434        let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1435            diff.move_to_path(
1436                PathKey::namespaced(TRACKED_NAMESPACE, Path::new("bar").into()),
1437                window,
1438                cx,
1439            );
1440            diff.editor.clone()
1441        });
1442        assert_state_with_diff(
1443            &editor,
1444            cx,
1445            &"
1446                - ˇbar
1447                + BAR
1448
1449                - foo
1450                + FOO
1451            "
1452            .unindent(),
1453        );
1454    }
1455
1456    #[gpui::test]
1457    async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1458        init_test(cx);
1459
1460        let fs = FakeFs::new(cx.executor());
1461        fs.insert_tree(
1462            path!("/project"),
1463            json!({
1464                ".git": {},
1465                "foo": "modified\n",
1466            }),
1467        )
1468        .await;
1469        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1470        let (workspace, cx) =
1471            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1472        let buffer = project
1473            .update(cx, |project, cx| {
1474                project.open_local_buffer(path!("/project/foo"), cx)
1475            })
1476            .await
1477            .unwrap();
1478        let buffer_editor = cx.new_window_entity(|window, cx| {
1479            Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1480        });
1481        let diff = cx.new_window_entity(|window, cx| {
1482            ProjectDiff::new(project.clone(), workspace, window, cx)
1483        });
1484        cx.run_until_parked();
1485
1486        fs.set_head_for_repo(
1487            path!("/project/.git").as_ref(),
1488            &[("foo".into(), "original\n".into())],
1489        );
1490        cx.run_until_parked();
1491
1492        let diff_editor = diff.update(cx, |diff, _| diff.editor.clone());
1493
1494        assert_state_with_diff(
1495            &diff_editor,
1496            cx,
1497            &"
1498                - original
1499                + ˇmodified
1500            "
1501            .unindent(),
1502        );
1503
1504        let prev_buffer_hunks =
1505            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1506                let snapshot = buffer_editor.snapshot(window, cx);
1507                let snapshot = &snapshot.buffer_snapshot;
1508                let prev_buffer_hunks = buffer_editor
1509                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1510                    .collect::<Vec<_>>();
1511                buffer_editor.git_restore(&Default::default(), window, cx);
1512                prev_buffer_hunks
1513            });
1514        assert_eq!(prev_buffer_hunks.len(), 1);
1515        cx.run_until_parked();
1516
1517        let new_buffer_hunks =
1518            cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1519                let snapshot = buffer_editor.snapshot(window, cx);
1520                let snapshot = &snapshot.buffer_snapshot;
1521                buffer_editor
1522                    .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1523                    .collect::<Vec<_>>()
1524            });
1525        assert_eq!(new_buffer_hunks.as_slice(), &[]);
1526
1527        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1528            buffer_editor.set_text("different\n", window, cx);
1529            buffer_editor.save(false, project.clone(), window, cx)
1530        })
1531        .await
1532        .unwrap();
1533
1534        cx.run_until_parked();
1535
1536        cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1537            buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1538        });
1539
1540        assert_state_with_diff(
1541            &buffer_editor,
1542            cx,
1543            &"
1544                - original
1545                + different
1546                  ˇ"
1547            .unindent(),
1548        );
1549
1550        assert_state_with_diff(
1551            &diff_editor,
1552            cx,
1553            &"
1554                - original
1555                + different
1556                  ˇ"
1557            .unindent(),
1558        );
1559    }
1560
1561    use crate::project_diff::{self, ProjectDiff};
1562
1563    #[gpui::test]
1564    async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1565        init_test(cx);
1566
1567        let fs = FakeFs::new(cx.executor());
1568        fs.insert_tree(
1569            "/a",
1570            json!({
1571                ".git":{},
1572                "a.txt": "created\n",
1573                "b.txt": "really changed\n",
1574                "c.txt": "unchanged\n"
1575            }),
1576        )
1577        .await;
1578
1579        fs.set_git_content_for_repo(
1580            Path::new("/a/.git"),
1581            &[
1582                ("b.txt".into(), "before\n".to_string(), None),
1583                ("c.txt".into(), "unchanged\n".to_string(), None),
1584                ("d.txt".into(), "deleted\n".to_string(), None),
1585            ],
1586        );
1587
1588        let project = Project::test(fs, [Path::new("/a")], cx).await;
1589        let (workspace, cx) =
1590            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1591
1592        cx.run_until_parked();
1593
1594        cx.focus(&workspace);
1595        cx.update(|window, cx| {
1596            window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1597        });
1598
1599        cx.run_until_parked();
1600
1601        let item = workspace.update(cx, |workspace, cx| {
1602            workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1603        });
1604        cx.focus(&item);
1605        let editor = item.update(cx, |item, _| item.editor.clone());
1606
1607        let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1608
1609        cx.assert_excerpts_with_selections(indoc!(
1610            "
1611            [EXCERPT]
1612            before
1613            really changed
1614            [EXCERPT]
1615            [FOLDED]
1616            [EXCERPT]
1617            ˇcreated
1618        "
1619        ));
1620
1621        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1622
1623        cx.assert_excerpts_with_selections(indoc!(
1624            "
1625            [EXCERPT]
1626            before
1627            really changed
1628            [EXCERPT]
1629            ˇ[FOLDED]
1630            [EXCERPT]
1631            created
1632        "
1633        ));
1634
1635        cx.dispatch_action(editor::actions::GoToPreviousHunk);
1636
1637        cx.assert_excerpts_with_selections(indoc!(
1638            "
1639            [EXCERPT]
1640            ˇbefore
1641            really changed
1642            [EXCERPT]
1643            [FOLDED]
1644            [EXCERPT]
1645            created
1646        "
1647        ));
1648    }
1649}