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