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