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