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 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
810 if let Some(project_diff) = self.project_diff(cx) {
811 project_diff.focus_handle(cx).focus(window);
812 }
813 let action = action.boxed_clone();
814 cx.defer(move |cx| {
815 cx.dispatch_action(action.as_ref());
816 })
817 }
818
819 fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
820 self.workspace
821 .update(cx, |workspace, cx| {
822 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
823 panel.update(cx, |panel, cx| {
824 panel.stage_all(&Default::default(), window, cx);
825 });
826 }
827 })
828 .ok();
829 }
830
831 fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
832 self.workspace
833 .update(cx, |workspace, cx| {
834 let Some(panel) = workspace.panel::<GitPanel>(cx) else {
835 return;
836 };
837 panel.update(cx, |panel, cx| {
838 panel.unstage_all(&Default::default(), window, cx);
839 });
840 })
841 .ok();
842 }
843}
844
845impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
846
847impl ToolbarItemView for ProjectDiffToolbar {
848 fn set_active_pane_item(
849 &mut self,
850 active_pane_item: Option<&dyn ItemHandle>,
851 _: &mut Window,
852 cx: &mut Context<Self>,
853 ) -> ToolbarItemLocation {
854 self.project_diff = active_pane_item
855 .and_then(|item| item.act_as::<ProjectDiff>(cx))
856 .map(|entity| entity.downgrade());
857 if self.project_diff.is_some() {
858 ToolbarItemLocation::PrimaryRight
859 } else {
860 ToolbarItemLocation::Hidden
861 }
862 }
863
864 fn pane_focus_update(
865 &mut self,
866 _pane_focused: bool,
867 _window: &mut Window,
868 _cx: &mut Context<Self>,
869 ) {
870 }
871}
872
873struct ButtonStates {
874 stage: bool,
875 unstage: bool,
876 prev_next: bool,
877 selection: bool,
878 stage_all: bool,
879 unstage_all: bool,
880}
881
882impl Render for ProjectDiffToolbar {
883 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
884 let Some(project_diff) = self.project_diff(cx) else {
885 return div();
886 };
887 let focus_handle = project_diff.focus_handle(cx);
888 let button_states = project_diff.read(cx).button_states(cx);
889
890 h_group_xl()
891 .my_neg_1()
892 .items_center()
893 .py_1()
894 .pl_2()
895 .pr_1()
896 .flex_wrap()
897 .justify_between()
898 .child(
899 h_group_sm()
900 .when(button_states.selection, |el| {
901 el.child(
902 Button::new("stage", "Toggle Staged")
903 .tooltip(Tooltip::for_action_title_in(
904 "Toggle Staged",
905 &ToggleStaged,
906 &focus_handle,
907 ))
908 .disabled(!button_states.stage && !button_states.unstage)
909 .on_click(cx.listener(|this, _, window, cx| {
910 this.dispatch_action(&ToggleStaged, window, cx)
911 })),
912 )
913 })
914 .when(!button_states.selection, |el| {
915 el.child(
916 Button::new("stage", "Stage")
917 .tooltip(Tooltip::for_action_title_in(
918 "Stage and go to next hunk",
919 &StageAndNext,
920 &focus_handle,
921 ))
922 .on_click(cx.listener(|this, _, window, cx| {
923 this.dispatch_action(&StageAndNext, window, cx)
924 })),
925 )
926 .child(
927 Button::new("unstage", "Unstage")
928 .tooltip(Tooltip::for_action_title_in(
929 "Unstage and go to next hunk",
930 &UnstageAndNext,
931 &focus_handle,
932 ))
933 .on_click(cx.listener(|this, _, window, cx| {
934 this.dispatch_action(&UnstageAndNext, window, cx)
935 })),
936 )
937 }),
938 )
939 // n.b. the only reason these arrows are here is because we don't
940 // support "undo" for staging so we need a way to go back.
941 .child(
942 h_group_sm()
943 .child(
944 IconButton::new("up", IconName::ArrowUp)
945 .shape(ui::IconButtonShape::Square)
946 .tooltip(Tooltip::for_action_title_in(
947 "Go to previous hunk",
948 &GoToPreviousHunk,
949 &focus_handle,
950 ))
951 .disabled(!button_states.prev_next)
952 .on_click(cx.listener(|this, _, window, cx| {
953 this.dispatch_action(&GoToPreviousHunk, window, cx)
954 })),
955 )
956 .child(
957 IconButton::new("down", IconName::ArrowDown)
958 .shape(ui::IconButtonShape::Square)
959 .tooltip(Tooltip::for_action_title_in(
960 "Go to next hunk",
961 &GoToHunk,
962 &focus_handle,
963 ))
964 .disabled(!button_states.prev_next)
965 .on_click(cx.listener(|this, _, window, cx| {
966 this.dispatch_action(&GoToHunk, window, cx)
967 })),
968 ),
969 )
970 .child(vertical_divider())
971 .child(
972 h_group_sm()
973 .when(
974 button_states.unstage_all && !button_states.stage_all,
975 |el| {
976 el.child(
977 Button::new("unstage-all", "Unstage All")
978 .tooltip(Tooltip::for_action_title_in(
979 "Unstage all changes",
980 &UnstageAll,
981 &focus_handle,
982 ))
983 .on_click(cx.listener(|this, _, window, cx| {
984 this.unstage_all(window, cx)
985 })),
986 )
987 },
988 )
989 .when(
990 !button_states.unstage_all || button_states.stage_all,
991 |el| {
992 el.child(
993 // todo make it so that changing to say "Unstaged"
994 // doesn't change the position.
995 div().child(
996 Button::new("stage-all", "Stage All")
997 .disabled(!button_states.stage_all)
998 .tooltip(Tooltip::for_action_title_in(
999 "Stage all changes",
1000 &StageAll,
1001 &focus_handle,
1002 ))
1003 .on_click(cx.listener(|this, _, window, cx| {
1004 this.stage_all(window, cx)
1005 })),
1006 ),
1007 )
1008 },
1009 )
1010 .child(
1011 Button::new("commit", "Commit")
1012 .tooltip(Tooltip::for_action_title_in(
1013 "Commit",
1014 &Commit,
1015 &focus_handle,
1016 ))
1017 .on_click(cx.listener(|this, _, window, cx| {
1018 this.dispatch_action(&Commit, window, cx);
1019 })),
1020 ),
1021 )
1022 }
1023}
1024
1025#[derive(IntoElement, IntoComponent)]
1026#[component(scope = "Version Control")]
1027pub struct ProjectDiffEmptyState {
1028 pub no_repo: bool,
1029 pub can_push_and_pull: bool,
1030 pub focus_handle: Option<FocusHandle>,
1031 pub current_branch: Option<Branch>,
1032 // has_pending_commits: bool,
1033 // ahead_of_remote: bool,
1034 // no_git_repository: bool,
1035}
1036
1037impl RenderOnce for ProjectDiffEmptyState {
1038 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1039 let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1040 match self.current_branch {
1041 Some(Branch {
1042 upstream:
1043 Some(Upstream {
1044 tracking:
1045 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1046 ahead, behind, ..
1047 }),
1048 ..
1049 }),
1050 ..
1051 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0) => true,
1052 _ => false,
1053 }
1054 };
1055
1056 let change_count = |current_branch: &Branch| -> (usize, usize) {
1057 match current_branch {
1058 Branch {
1059 upstream:
1060 Some(Upstream {
1061 tracking:
1062 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1063 ahead, behind, ..
1064 }),
1065 ..
1066 }),
1067 ..
1068 } => (*ahead as usize, *behind as usize),
1069 _ => (0, 0),
1070 }
1071 };
1072
1073 let not_ahead_or_behind = status_against_remote(0, 0);
1074 let ahead_of_remote = status_against_remote(1, 0);
1075 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1076 branch.upstream.is_none()
1077 } else {
1078 false
1079 };
1080
1081 let has_branch_container = |branch: &Branch| {
1082 h_flex()
1083 .max_w(px(420.))
1084 .bg(cx.theme().colors().text.opacity(0.05))
1085 .border_1()
1086 .border_color(cx.theme().colors().border)
1087 .rounded_sm()
1088 .gap_8()
1089 .px_6()
1090 .py_4()
1091 .map(|this| {
1092 if ahead_of_remote {
1093 let ahead_count = change_count(branch).0;
1094 let ahead_string = format!("{} Commits Ahead", ahead_count);
1095 this.child(
1096 v_flex()
1097 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1098 .child(
1099 Label::new(format!("Push your changes to {}", branch.name))
1100 .color(Color::Muted),
1101 ),
1102 )
1103 .child(div().child(render_push_button(
1104 self.focus_handle,
1105 "push".into(),
1106 ahead_count as u32,
1107 )))
1108 } else if branch_not_on_remote {
1109 this.child(
1110 v_flex()
1111 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1112 .child(
1113 Label::new(format!("Create {} on remote", branch.name))
1114 .color(Color::Muted),
1115 ),
1116 )
1117 .child(
1118 div().child(render_publish_button(self.focus_handle, "publish".into())),
1119 )
1120 } else {
1121 this.child(Label::new("Remote status unknown").color(Color::Muted))
1122 }
1123 })
1124 };
1125
1126 v_flex().size_full().items_center().justify_center().child(
1127 v_flex()
1128 .gap_1()
1129 .when(self.no_repo, |this| {
1130 // TODO: add git init
1131 this.text_center()
1132 .child(Label::new("No Repository").color(Color::Muted))
1133 })
1134 .map(|this| {
1135 if not_ahead_or_behind && self.current_branch.is_some() {
1136 this.text_center()
1137 .child(Label::new("No Changes").color(Color::Muted))
1138 } else {
1139 this.when_some(self.current_branch.as_ref(), |this, branch| {
1140 this.child(has_branch_container(&branch))
1141 })
1142 }
1143 }),
1144 )
1145 }
1146}
1147
1148// .when(self.can_push_and_pull, |this| {
1149// let remote_button = crate::render_remote_button(
1150// "project-diff-remote-button",
1151// &branch,
1152// self.focus_handle.clone(),
1153// false,
1154// );
1155
1156// match remote_button {
1157// Some(button) => {
1158// this.child(h_flex().justify_around().child(button))
1159// }
1160// None => this.child(
1161// h_flex()
1162// .justify_around()
1163// .child(Label::new("Remote up to date")),
1164// ),
1165// }
1166// }),
1167//
1168// // .map(|this| {
1169// this.child(h_flex().justify_around().mt_1().child(
1170// Button::new("project-diff-close-button", "Close").when_some(
1171// self.focus_handle.clone(),
1172// |this, focus_handle| {
1173// this.key_binding(KeyBinding::for_action_in(
1174// &CloseActiveItem::default(),
1175// &focus_handle,
1176// window,
1177// cx,
1178// ))
1179// .on_click(move |_, window, cx| {
1180// window.focus(&focus_handle);
1181// window
1182// .dispatch_action(Box::new(CloseActiveItem::default()), cx);
1183// })
1184// },
1185// ),
1186// ))
1187// }),
1188
1189mod preview {
1190 use git::repository::{
1191 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1192 };
1193 use ui::prelude::*;
1194
1195 use super::ProjectDiffEmptyState;
1196
1197 // View this component preview using `workspace: open component-preview`
1198 impl ComponentPreview for ProjectDiffEmptyState {
1199 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
1200 let unknown_upstream: Option<UpstreamTracking> = None;
1201 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1202 UpstreamTrackingStatus {
1203 ahead: 2,
1204 behind: 0,
1205 }
1206 .into(),
1207 );
1208
1209 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1210 UpstreamTrackingStatus {
1211 ahead: 0,
1212 behind: 0,
1213 }
1214 .into(),
1215 );
1216
1217 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1218 Branch {
1219 is_head: true,
1220 name: "some-branch".into(),
1221 upstream: upstream.map(|tracking| Upstream {
1222 ref_name: "origin/some-branch".into(),
1223 tracking,
1224 }),
1225 most_recent_commit: Some(CommitSummary {
1226 sha: "abc123".into(),
1227 subject: "Modify stuff".into(),
1228 commit_timestamp: 1710932954,
1229 has_parent: true,
1230 }),
1231 }
1232 }
1233
1234 let no_repo_state = ProjectDiffEmptyState {
1235 no_repo: true,
1236 can_push_and_pull: false,
1237 focus_handle: None,
1238 current_branch: None,
1239 };
1240
1241 let no_changes_state = ProjectDiffEmptyState {
1242 no_repo: false,
1243 can_push_and_pull: true,
1244 focus_handle: None,
1245 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1246 };
1247
1248 let ahead_of_upstream_state = ProjectDiffEmptyState {
1249 no_repo: false,
1250 can_push_and_pull: true,
1251 focus_handle: None,
1252 current_branch: Some(branch(ahead_of_upstream)),
1253 };
1254
1255 let unknown_upstream_state = ProjectDiffEmptyState {
1256 no_repo: false,
1257 can_push_and_pull: true,
1258 focus_handle: None,
1259 current_branch: Some(branch(unknown_upstream)),
1260 };
1261
1262 let (width, height) = (px(480.), px(320.));
1263
1264 v_flex()
1265 .gap_6()
1266 .children(vec![example_group(vec![
1267 single_example(
1268 "No Repo",
1269 div()
1270 .w(width)
1271 .h(height)
1272 .child(no_repo_state)
1273 .into_any_element(),
1274 ),
1275 single_example(
1276 "No Changes",
1277 div()
1278 .w(width)
1279 .h(height)
1280 .child(no_changes_state)
1281 .into_any_element(),
1282 ),
1283 single_example(
1284 "Unknown Upstream",
1285 div()
1286 .w(width)
1287 .h(height)
1288 .child(unknown_upstream_state)
1289 .into_any_element(),
1290 ),
1291 single_example(
1292 "Ahead of Remote",
1293 div()
1294 .w(width)
1295 .h(height)
1296 .child(ahead_of_upstream_state)
1297 .into_any_element(),
1298 ),
1299 ])
1300 .vertical()])
1301 .into_any_element()
1302 }
1303 }
1304}
1305
1306#[cfg(not(target_os = "windows"))]
1307#[cfg(test)]
1308mod tests {
1309 use std::path::Path;
1310
1311 use collections::HashMap;
1312 use db::indoc;
1313 use editor::test::editor_test_context::{assert_state_with_diff, EditorTestContext};
1314 use git::status::{StatusCode, TrackedStatus};
1315 use gpui::TestAppContext;
1316 use project::FakeFs;
1317 use serde_json::json;
1318 use settings::SettingsStore;
1319 use unindent::Unindent as _;
1320 use util::path;
1321
1322 use super::*;
1323
1324 #[ctor::ctor]
1325 fn init_logger() {
1326 env_logger::init();
1327 }
1328
1329 fn init_test(cx: &mut TestAppContext) {
1330 cx.update(|cx| {
1331 let store = SettingsStore::test(cx);
1332 cx.set_global(store);
1333 theme::init(theme::LoadThemes::JustBase, cx);
1334 language::init(cx);
1335 Project::init_settings(cx);
1336 workspace::init_settings(cx);
1337 editor::init(cx);
1338 crate::init(cx);
1339 });
1340 }
1341
1342 #[gpui::test]
1343 async fn test_save_after_restore(cx: &mut TestAppContext) {
1344 init_test(cx);
1345
1346 let fs = FakeFs::new(cx.executor());
1347 fs.insert_tree(
1348 path!("/project"),
1349 json!({
1350 ".git": {},
1351 "foo.txt": "FOO\n",
1352 }),
1353 )
1354 .await;
1355 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1356 let (workspace, cx) =
1357 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1358 let diff = cx.new_window_entity(|window, cx| {
1359 ProjectDiff::new(project.clone(), workspace, window, cx)
1360 });
1361 cx.run_until_parked();
1362
1363 fs.set_head_for_repo(
1364 path!("/project/.git").as_ref(),
1365 &[("foo.txt".into(), "foo\n".into())],
1366 );
1367 fs.set_index_for_repo(
1368 path!("/project/.git").as_ref(),
1369 &[("foo.txt".into(), "foo\n".into())],
1370 );
1371 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1372 state.statuses = HashMap::from_iter([(
1373 "foo.txt".into(),
1374 TrackedStatus {
1375 index_status: StatusCode::Unmodified,
1376 worktree_status: StatusCode::Modified,
1377 }
1378 .into(),
1379 )]);
1380 });
1381 cx.run_until_parked();
1382
1383 let editor = diff.update(cx, |diff, _| diff.editor.clone());
1384 assert_state_with_diff(
1385 &editor,
1386 cx,
1387 &"
1388 - foo
1389 + ˇFOO
1390 "
1391 .unindent(),
1392 );
1393
1394 editor.update_in(cx, |editor, window, cx| {
1395 editor.git_restore(&Default::default(), window, cx);
1396 });
1397 cx.run_until_parked();
1398
1399 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1400
1401 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1402 assert_eq!(text, "foo\n");
1403 }
1404
1405 #[gpui::test]
1406 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1407 init_test(cx);
1408
1409 let fs = FakeFs::new(cx.executor());
1410 fs.insert_tree(
1411 path!("/project"),
1412 json!({
1413 ".git": {},
1414 "bar": "BAR\n",
1415 "foo": "FOO\n",
1416 }),
1417 )
1418 .await;
1419 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1420 let (workspace, cx) =
1421 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1422 let diff = cx.new_window_entity(|window, cx| {
1423 ProjectDiff::new(project.clone(), workspace, window, cx)
1424 });
1425 cx.run_until_parked();
1426
1427 fs.set_head_for_repo(
1428 path!("/project/.git").as_ref(),
1429 &[
1430 ("bar".into(), "bar\n".into()),
1431 ("foo".into(), "foo\n".into()),
1432 ],
1433 );
1434 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1435 state.statuses = HashMap::from_iter([
1436 (
1437 "bar".into(),
1438 TrackedStatus {
1439 index_status: StatusCode::Unmodified,
1440 worktree_status: StatusCode::Modified,
1441 }
1442 .into(),
1443 ),
1444 (
1445 "foo".into(),
1446 TrackedStatus {
1447 index_status: StatusCode::Unmodified,
1448 worktree_status: StatusCode::Modified,
1449 }
1450 .into(),
1451 ),
1452 ]);
1453 });
1454 cx.run_until_parked();
1455
1456 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1457 diff.move_to_path(
1458 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("foo").into()),
1459 window,
1460 cx,
1461 );
1462 diff.editor.clone()
1463 });
1464 assert_state_with_diff(
1465 &editor,
1466 cx,
1467 &"
1468 - bar
1469 + BAR
1470
1471 - ˇfoo
1472 + FOO
1473 "
1474 .unindent(),
1475 );
1476
1477 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1478 diff.move_to_path(
1479 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("bar").into()),
1480 window,
1481 cx,
1482 );
1483 diff.editor.clone()
1484 });
1485 assert_state_with_diff(
1486 &editor,
1487 cx,
1488 &"
1489 - ˇbar
1490 + BAR
1491
1492 - foo
1493 + FOO
1494 "
1495 .unindent(),
1496 );
1497 }
1498
1499 #[gpui::test]
1500 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1501 init_test(cx);
1502
1503 let fs = FakeFs::new(cx.executor());
1504 fs.insert_tree(
1505 path!("/project"),
1506 json!({
1507 ".git": {},
1508 "foo": "modified\n",
1509 }),
1510 )
1511 .await;
1512 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1513 let (workspace, cx) =
1514 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1515 let buffer = project
1516 .update(cx, |project, cx| {
1517 project.open_local_buffer(path!("/project/foo"), cx)
1518 })
1519 .await
1520 .unwrap();
1521 let buffer_editor = cx.new_window_entity(|window, cx| {
1522 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1523 });
1524 let diff = cx.new_window_entity(|window, cx| {
1525 ProjectDiff::new(project.clone(), workspace, window, cx)
1526 });
1527 cx.run_until_parked();
1528
1529 fs.set_head_for_repo(
1530 path!("/project/.git").as_ref(),
1531 &[("foo".into(), "original\n".into())],
1532 );
1533 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
1534 state.statuses = HashMap::from_iter([(
1535 "foo".into(),
1536 TrackedStatus {
1537 index_status: StatusCode::Unmodified,
1538 worktree_status: StatusCode::Modified,
1539 }
1540 .into(),
1541 )]);
1542 });
1543 cx.run_until_parked();
1544
1545 let diff_editor = diff.update(cx, |diff, _| diff.editor.clone());
1546
1547 assert_state_with_diff(
1548 &diff_editor,
1549 cx,
1550 &"
1551 - original
1552 + ˇmodified
1553 "
1554 .unindent(),
1555 );
1556
1557 let prev_buffer_hunks =
1558 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1559 let snapshot = buffer_editor.snapshot(window, cx);
1560 let snapshot = &snapshot.buffer_snapshot;
1561 let prev_buffer_hunks = buffer_editor
1562 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1563 .collect::<Vec<_>>();
1564 buffer_editor.git_restore(&Default::default(), window, cx);
1565 prev_buffer_hunks
1566 });
1567 assert_eq!(prev_buffer_hunks.len(), 1);
1568 cx.run_until_parked();
1569
1570 let new_buffer_hunks =
1571 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1572 let snapshot = buffer_editor.snapshot(window, cx);
1573 let snapshot = &snapshot.buffer_snapshot;
1574 let new_buffer_hunks = buffer_editor
1575 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1576 .collect::<Vec<_>>();
1577 buffer_editor.git_restore(&Default::default(), window, cx);
1578 new_buffer_hunks
1579 });
1580 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1581
1582 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1583 buffer_editor.set_text("different\n", window, cx);
1584 buffer_editor.save(false, project.clone(), window, cx)
1585 })
1586 .await
1587 .unwrap();
1588
1589 cx.run_until_parked();
1590
1591 assert_state_with_diff(
1592 &diff_editor,
1593 cx,
1594 &"
1595 - original
1596 + ˇdifferent
1597 "
1598 .unindent(),
1599 );
1600 }
1601
1602 use crate::project_diff::{self, ProjectDiff};
1603
1604 #[gpui::test]
1605 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1606 init_test(cx);
1607
1608 let fs = FakeFs::new(cx.executor());
1609 fs.insert_tree(
1610 "/a",
1611 json!({
1612 ".git":{},
1613 "a.txt": "created\n",
1614 "b.txt": "really changed\n",
1615 "c.txt": "unchanged\n"
1616 }),
1617 )
1618 .await;
1619
1620 fs.set_git_content_for_repo(
1621 Path::new("/a/.git"),
1622 &[
1623 ("b.txt".into(), "before\n".to_string(), None),
1624 ("c.txt".into(), "unchanged\n".to_string(), None),
1625 ("d.txt".into(), "deleted\n".to_string(), None),
1626 ],
1627 );
1628
1629 let project = Project::test(fs, [Path::new("/a")], cx).await;
1630 let (workspace, cx) =
1631 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1632
1633 cx.run_until_parked();
1634
1635 cx.focus(&workspace);
1636 cx.update(|window, cx| {
1637 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1638 });
1639
1640 cx.run_until_parked();
1641
1642 let item = workspace.update(cx, |workspace, cx| {
1643 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1644 });
1645 cx.focus(&item);
1646 let editor = item.update(cx, |item, _| item.editor.clone());
1647
1648 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1649
1650 cx.assert_excerpts_with_selections(indoc!(
1651 "
1652 [EXCERPT]
1653 before
1654 really changed
1655 [EXCERPT]
1656 [FOLDED]
1657 [EXCERPT]
1658 ˇcreated
1659 "
1660 ));
1661
1662 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1663
1664 cx.assert_excerpts_with_selections(indoc!(
1665 "
1666 [EXCERPT]
1667 before
1668 really changed
1669 [EXCERPT]
1670 ˇ[FOLDED]
1671 [EXCERPT]
1672 created
1673 "
1674 ));
1675
1676 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1677
1678 cx.assert_excerpts_with_selections(indoc!(
1679 "
1680 [EXCERPT]
1681 ˇbefore
1682 really changed
1683 [EXCERPT]
1684 [FOLDED]
1685 [EXCERPT]
1686 created
1687 "
1688 ));
1689 }
1690}