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