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