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