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);
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);
452 let conflicts = conflict_addon
453 .conflict_set(snapshot.remote_id())
454 .map(|conflict_set| conflict_set.read(cx).snapshot().conflicts)
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);
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 matches!(self.current_branch, Some(Branch {
1074 upstream:
1075 Some(Upstream {
1076 tracking:
1077 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1078 ahead, behind, ..
1079 }),
1080 ..
1081 }),
1082 ..
1083 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1084 };
1085
1086 let change_count = |current_branch: &Branch| -> (usize, usize) {
1087 match current_branch {
1088 Branch {
1089 upstream:
1090 Some(Upstream {
1091 tracking:
1092 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1093 ahead, behind, ..
1094 }),
1095 ..
1096 }),
1097 ..
1098 } => (*ahead as usize, *behind as usize),
1099 _ => (0, 0),
1100 }
1101 };
1102
1103 let not_ahead_or_behind = status_against_remote(0, 0);
1104 let ahead_of_remote = status_against_remote(1, 0);
1105 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1106 branch.upstream.is_none()
1107 } else {
1108 false
1109 };
1110
1111 let has_branch_container = |branch: &Branch| {
1112 h_flex()
1113 .max_w(px(420.))
1114 .bg(cx.theme().colors().text.opacity(0.05))
1115 .border_1()
1116 .border_color(cx.theme().colors().border)
1117 .rounded_sm()
1118 .gap_8()
1119 .px_6()
1120 .py_4()
1121 .map(|this| {
1122 if ahead_of_remote {
1123 let ahead_count = change_count(branch).0;
1124 let ahead_string = format!("{} Commits Ahead", ahead_count);
1125 this.child(
1126 v_flex()
1127 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1128 .child(
1129 Label::new(format!("Push your changes to {}", branch.name()))
1130 .color(Color::Muted),
1131 ),
1132 )
1133 .child(div().child(render_push_button(
1134 self.focus_handle,
1135 "push".into(),
1136 ahead_count as u32,
1137 )))
1138 } else if branch_not_on_remote {
1139 this.child(
1140 v_flex()
1141 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1142 .child(
1143 Label::new(format!("Create {} on remote", branch.name()))
1144 .color(Color::Muted),
1145 ),
1146 )
1147 .child(
1148 div().child(render_publish_button(self.focus_handle, "publish".into())),
1149 )
1150 } else {
1151 this.child(Label::new("Remote status unknown").color(Color::Muted))
1152 }
1153 })
1154 };
1155
1156 v_flex().size_full().items_center().justify_center().child(
1157 v_flex()
1158 .gap_1()
1159 .when(self.no_repo, |this| {
1160 // TODO: add git init
1161 this.text_center()
1162 .child(Label::new("No Repository").color(Color::Muted))
1163 })
1164 .map(|this| {
1165 if not_ahead_or_behind && self.current_branch.is_some() {
1166 this.text_center()
1167 .child(Label::new("No Changes").color(Color::Muted))
1168 } else {
1169 this.when_some(self.current_branch.as_ref(), |this, branch| {
1170 this.child(has_branch_container(branch))
1171 })
1172 }
1173 }),
1174 )
1175 }
1176}
1177
1178mod preview {
1179 use git::repository::{
1180 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1181 };
1182 use ui::prelude::*;
1183
1184 use super::ProjectDiffEmptyState;
1185
1186 // View this component preview using `workspace: open component-preview`
1187 impl Component for ProjectDiffEmptyState {
1188 fn scope() -> ComponentScope {
1189 ComponentScope::VersionControl
1190 }
1191
1192 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1193 let unknown_upstream: Option<UpstreamTracking> = None;
1194 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1195 UpstreamTrackingStatus {
1196 ahead: 2,
1197 behind: 0,
1198 }
1199 .into(),
1200 );
1201
1202 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1203 UpstreamTrackingStatus {
1204 ahead: 0,
1205 behind: 0,
1206 }
1207 .into(),
1208 );
1209
1210 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1211 Branch {
1212 is_head: true,
1213 ref_name: "some-branch".into(),
1214 upstream: upstream.map(|tracking| Upstream {
1215 ref_name: "origin/some-branch".into(),
1216 tracking,
1217 }),
1218 most_recent_commit: Some(CommitSummary {
1219 sha: "abc123".into(),
1220 subject: "Modify stuff".into(),
1221 commit_timestamp: 1710932954,
1222 has_parent: true,
1223 }),
1224 }
1225 }
1226
1227 let no_repo_state = ProjectDiffEmptyState {
1228 no_repo: true,
1229 can_push_and_pull: false,
1230 focus_handle: None,
1231 current_branch: None,
1232 };
1233
1234 let no_changes_state = ProjectDiffEmptyState {
1235 no_repo: false,
1236 can_push_and_pull: true,
1237 focus_handle: None,
1238 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1239 };
1240
1241 let ahead_of_upstream_state = ProjectDiffEmptyState {
1242 no_repo: false,
1243 can_push_and_pull: true,
1244 focus_handle: None,
1245 current_branch: Some(branch(ahead_of_upstream)),
1246 };
1247
1248 let unknown_upstream_state = ProjectDiffEmptyState {
1249 no_repo: false,
1250 can_push_and_pull: true,
1251 focus_handle: None,
1252 current_branch: Some(branch(unknown_upstream)),
1253 };
1254
1255 let (width, height) = (px(480.), px(320.));
1256
1257 Some(
1258 v_flex()
1259 .gap_6()
1260 .children(vec![
1261 example_group(vec![
1262 single_example(
1263 "No Repo",
1264 div()
1265 .w(width)
1266 .h(height)
1267 .child(no_repo_state)
1268 .into_any_element(),
1269 ),
1270 single_example(
1271 "No Changes",
1272 div()
1273 .w(width)
1274 .h(height)
1275 .child(no_changes_state)
1276 .into_any_element(),
1277 ),
1278 single_example(
1279 "Unknown Upstream",
1280 div()
1281 .w(width)
1282 .h(height)
1283 .child(unknown_upstream_state)
1284 .into_any_element(),
1285 ),
1286 single_example(
1287 "Ahead of Remote",
1288 div()
1289 .w(width)
1290 .h(height)
1291 .child(ahead_of_upstream_state)
1292 .into_any_element(),
1293 ),
1294 ])
1295 .vertical(),
1296 ])
1297 .into_any_element(),
1298 )
1299 }
1300 }
1301}
1302
1303fn merge_anchor_ranges<'a>(
1304 left: impl 'a + Iterator<Item = Range<Anchor>>,
1305 right: impl 'a + Iterator<Item = Range<Anchor>>,
1306 snapshot: &'a language::BufferSnapshot,
1307) -> impl 'a + Iterator<Item = Range<Anchor>> {
1308 let mut left = left.fuse().peekable();
1309 let mut right = right.fuse().peekable();
1310
1311 std::iter::from_fn(move || {
1312 let Some(left_range) = left.peek() else {
1313 return right.next();
1314 };
1315 let Some(right_range) = right.peek() else {
1316 return left.next();
1317 };
1318
1319 let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1320 left.next().unwrap()
1321 } else {
1322 right.next().unwrap()
1323 };
1324
1325 // Extend the basic range while there's overlap with a range from either stream.
1326 loop {
1327 if let Some(left_range) = left
1328 .peek()
1329 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1330 .cloned()
1331 {
1332 left.next();
1333 next_range.end = left_range.end;
1334 } else if let Some(right_range) = right
1335 .peek()
1336 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1337 .cloned()
1338 {
1339 right.next();
1340 next_range.end = right_range.end;
1341 } else {
1342 break;
1343 }
1344 }
1345
1346 Some(next_range)
1347 })
1348}
1349
1350#[cfg(not(target_os = "windows"))]
1351#[cfg(test)]
1352mod tests {
1353 use db::indoc;
1354 use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1355 use git::status::{UnmergedStatus, UnmergedStatusCode};
1356 use gpui::TestAppContext;
1357 use project::FakeFs;
1358 use serde_json::json;
1359 use settings::SettingsStore;
1360 use std::path::Path;
1361 use unindent::Unindent as _;
1362 use util::path;
1363
1364 use super::*;
1365
1366 #[ctor::ctor]
1367 fn init_logger() {
1368 zlog::init_test();
1369 }
1370
1371 fn init_test(cx: &mut TestAppContext) {
1372 cx.update(|cx| {
1373 let store = SettingsStore::test(cx);
1374 cx.set_global(store);
1375 theme::init(theme::LoadThemes::JustBase, cx);
1376 language::init(cx);
1377 Project::init_settings(cx);
1378 workspace::init_settings(cx);
1379 editor::init(cx);
1380 crate::init(cx);
1381 });
1382 }
1383
1384 #[gpui::test]
1385 async fn test_save_after_restore(cx: &mut TestAppContext) {
1386 init_test(cx);
1387
1388 let fs = FakeFs::new(cx.executor());
1389 fs.insert_tree(
1390 path!("/project"),
1391 json!({
1392 ".git": {},
1393 "foo.txt": "FOO\n",
1394 }),
1395 )
1396 .await;
1397 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1398 let (workspace, cx) =
1399 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1400 let diff = cx.new_window_entity(|window, cx| {
1401 ProjectDiff::new(project.clone(), workspace, window, cx)
1402 });
1403 cx.run_until_parked();
1404
1405 fs.set_head_for_repo(
1406 path!("/project/.git").as_ref(),
1407 &[("foo.txt".into(), "foo\n".into())],
1408 "deadbeef",
1409 );
1410 fs.set_index_for_repo(
1411 path!("/project/.git").as_ref(),
1412 &[("foo.txt".into(), "foo\n".into())],
1413 );
1414 cx.run_until_parked();
1415
1416 let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1417 assert_state_with_diff(
1418 &editor,
1419 cx,
1420 &"
1421 - foo
1422 + ˇFOO
1423 "
1424 .unindent(),
1425 );
1426
1427 editor.update_in(cx, |editor, window, cx| {
1428 editor.git_restore(&Default::default(), window, cx);
1429 });
1430 cx.run_until_parked();
1431
1432 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1433
1434 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1435 assert_eq!(text, "foo\n");
1436 }
1437
1438 #[gpui::test]
1439 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1440 init_test(cx);
1441
1442 let fs = FakeFs::new(cx.executor());
1443 fs.insert_tree(
1444 path!("/project"),
1445 json!({
1446 ".git": {},
1447 "bar": "BAR\n",
1448 "foo": "FOO\n",
1449 }),
1450 )
1451 .await;
1452 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1453 let (workspace, cx) =
1454 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1455 let diff = cx.new_window_entity(|window, cx| {
1456 ProjectDiff::new(project.clone(), workspace, window, cx)
1457 });
1458 cx.run_until_parked();
1459
1460 fs.set_head_and_index_for_repo(
1461 path!("/project/.git").as_ref(),
1462 &[
1463 ("bar".into(), "bar\n".into()),
1464 ("foo".into(), "foo\n".into()),
1465 ],
1466 );
1467 cx.run_until_parked();
1468
1469 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1470 diff.move_to_path(
1471 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("foo").into()),
1472 window,
1473 cx,
1474 );
1475 diff.editor.clone()
1476 });
1477 assert_state_with_diff(
1478 &editor,
1479 cx,
1480 &"
1481 - bar
1482 + BAR
1483
1484 - ˇfoo
1485 + FOO
1486 "
1487 .unindent(),
1488 );
1489
1490 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1491 diff.move_to_path(
1492 PathKey::namespaced(TRACKED_NAMESPACE, Path::new("bar").into()),
1493 window,
1494 cx,
1495 );
1496 diff.editor.clone()
1497 });
1498 assert_state_with_diff(
1499 &editor,
1500 cx,
1501 &"
1502 - ˇbar
1503 + BAR
1504
1505 - foo
1506 + FOO
1507 "
1508 .unindent(),
1509 );
1510 }
1511
1512 #[gpui::test]
1513 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1514 init_test(cx);
1515
1516 let fs = FakeFs::new(cx.executor());
1517 fs.insert_tree(
1518 path!("/project"),
1519 json!({
1520 ".git": {},
1521 "foo": "modified\n",
1522 }),
1523 )
1524 .await;
1525 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1526 let (workspace, cx) =
1527 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1528 let buffer = project
1529 .update(cx, |project, cx| {
1530 project.open_local_buffer(path!("/project/foo"), cx)
1531 })
1532 .await
1533 .unwrap();
1534 let buffer_editor = cx.new_window_entity(|window, cx| {
1535 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1536 });
1537 let diff = cx.new_window_entity(|window, cx| {
1538 ProjectDiff::new(project.clone(), workspace, window, cx)
1539 });
1540 cx.run_until_parked();
1541
1542 fs.set_head_for_repo(
1543 path!("/project/.git").as_ref(),
1544 &[("foo".into(), "original\n".into())],
1545 "deadbeef",
1546 );
1547 cx.run_until_parked();
1548
1549 let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1550
1551 assert_state_with_diff(
1552 &diff_editor,
1553 cx,
1554 &"
1555 - original
1556 + ˇmodified
1557 "
1558 .unindent(),
1559 );
1560
1561 let prev_buffer_hunks =
1562 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1563 let snapshot = buffer_editor.snapshot(window, cx);
1564 let snapshot = &snapshot.buffer_snapshot;
1565 let prev_buffer_hunks = buffer_editor
1566 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1567 .collect::<Vec<_>>();
1568 buffer_editor.git_restore(&Default::default(), window, cx);
1569 prev_buffer_hunks
1570 });
1571 assert_eq!(prev_buffer_hunks.len(), 1);
1572 cx.run_until_parked();
1573
1574 let new_buffer_hunks =
1575 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1576 let snapshot = buffer_editor.snapshot(window, cx);
1577 let snapshot = &snapshot.buffer_snapshot;
1578 buffer_editor
1579 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1580 .collect::<Vec<_>>()
1581 });
1582 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1583
1584 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1585 buffer_editor.set_text("different\n", window, cx);
1586 buffer_editor.save(
1587 SaveOptions {
1588 format: false,
1589 autosave: false,
1590 },
1591 project.clone(),
1592 window,
1593 cx,
1594 )
1595 })
1596 .await
1597 .unwrap();
1598
1599 cx.run_until_parked();
1600
1601 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1602 buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1603 });
1604
1605 assert_state_with_diff(
1606 &buffer_editor,
1607 cx,
1608 &"
1609 - original
1610 + different
1611 ˇ"
1612 .unindent(),
1613 );
1614
1615 assert_state_with_diff(
1616 &diff_editor,
1617 cx,
1618 &"
1619 - original
1620 + different
1621 ˇ"
1622 .unindent(),
1623 );
1624 }
1625
1626 use crate::{
1627 conflict_view::resolve_conflict,
1628 project_diff::{self, ProjectDiff},
1629 };
1630
1631 #[gpui::test]
1632 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1633 init_test(cx);
1634
1635 let fs = FakeFs::new(cx.executor());
1636 fs.insert_tree(
1637 "/a",
1638 json!({
1639 ".git": {},
1640 "a.txt": "created\n",
1641 "b.txt": "really changed\n",
1642 "c.txt": "unchanged\n"
1643 }),
1644 )
1645 .await;
1646
1647 fs.set_git_content_for_repo(
1648 Path::new("/a/.git"),
1649 &[
1650 ("b.txt".into(), "before\n".to_string(), None),
1651 ("c.txt".into(), "unchanged\n".to_string(), None),
1652 ("d.txt".into(), "deleted\n".to_string(), None),
1653 ],
1654 );
1655
1656 let project = Project::test(fs, [Path::new("/a")], cx).await;
1657 let (workspace, cx) =
1658 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1659
1660 cx.run_until_parked();
1661
1662 cx.focus(&workspace);
1663 cx.update(|window, cx| {
1664 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1665 });
1666
1667 cx.run_until_parked();
1668
1669 let item = workspace.update(cx, |workspace, cx| {
1670 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1671 });
1672 cx.focus(&item);
1673 let editor = item.read_with(cx, |item, _| item.editor.clone());
1674
1675 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1676
1677 cx.assert_excerpts_with_selections(indoc!(
1678 "
1679 [EXCERPT]
1680 before
1681 really changed
1682 [EXCERPT]
1683 [FOLDED]
1684 [EXCERPT]
1685 ˇcreated
1686 "
1687 ));
1688
1689 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1690
1691 cx.assert_excerpts_with_selections(indoc!(
1692 "
1693 [EXCERPT]
1694 before
1695 really changed
1696 [EXCERPT]
1697 ˇ[FOLDED]
1698 [EXCERPT]
1699 created
1700 "
1701 ));
1702
1703 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1704
1705 cx.assert_excerpts_with_selections(indoc!(
1706 "
1707 [EXCERPT]
1708 ˇbefore
1709 really changed
1710 [EXCERPT]
1711 [FOLDED]
1712 [EXCERPT]
1713 created
1714 "
1715 ));
1716 }
1717
1718 #[gpui::test]
1719 async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1720 init_test(cx);
1721
1722 let git_contents = indoc! {r#"
1723 #[rustfmt::skip]
1724 fn main() {
1725 let x = 0.0; // this line will be removed
1726 // 1
1727 // 2
1728 // 3
1729 let y = 0.0; // this line will be removed
1730 // 1
1731 // 2
1732 // 3
1733 let arr = [
1734 0.0, // this line will be removed
1735 0.0, // this line will be removed
1736 0.0, // this line will be removed
1737 0.0, // this line will be removed
1738 ];
1739 }
1740 "#};
1741 let buffer_contents = indoc! {"
1742 #[rustfmt::skip]
1743 fn main() {
1744 // 1
1745 // 2
1746 // 3
1747 // 1
1748 // 2
1749 // 3
1750 let arr = [
1751 ];
1752 }
1753 "};
1754
1755 let fs = FakeFs::new(cx.executor());
1756 fs.insert_tree(
1757 "/a",
1758 json!({
1759 ".git": {},
1760 "main.rs": buffer_contents,
1761 }),
1762 )
1763 .await;
1764
1765 fs.set_git_content_for_repo(
1766 Path::new("/a/.git"),
1767 &[("main.rs".into(), git_contents.to_owned(), None)],
1768 );
1769
1770 let project = Project::test(fs, [Path::new("/a")], cx).await;
1771 let (workspace, cx) =
1772 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1773
1774 cx.run_until_parked();
1775
1776 cx.focus(&workspace);
1777 cx.update(|window, cx| {
1778 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1779 });
1780
1781 cx.run_until_parked();
1782
1783 let item = workspace.update(cx, |workspace, cx| {
1784 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1785 });
1786 cx.focus(&item);
1787 let editor = item.read_with(cx, |item, _| item.editor.clone());
1788
1789 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1790
1791 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1792
1793 cx.dispatch_action(editor::actions::GoToHunk);
1794 cx.dispatch_action(editor::actions::GoToHunk);
1795 cx.dispatch_action(git::Restore);
1796 cx.dispatch_action(editor::actions::MoveToBeginning);
1797
1798 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1799 }
1800
1801 #[gpui::test]
1802 async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1803 init_test(cx);
1804
1805 let fs = FakeFs::new(cx.executor());
1806 fs.insert_tree(
1807 path!("/project"),
1808 json!({
1809 ".git": {},
1810 "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1811 }),
1812 )
1813 .await;
1814 fs.set_status_for_repo(
1815 Path::new(path!("/project/.git")),
1816 &[(
1817 Path::new("foo"),
1818 UnmergedStatus {
1819 first_head: UnmergedStatusCode::Updated,
1820 second_head: UnmergedStatusCode::Updated,
1821 }
1822 .into(),
1823 )],
1824 );
1825 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1826 let (workspace, cx) =
1827 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1828 let diff = cx.new_window_entity(|window, cx| {
1829 ProjectDiff::new(project.clone(), workspace, window, cx)
1830 });
1831 cx.run_until_parked();
1832
1833 cx.update(|window, cx| {
1834 let editor = diff.read(cx).editor.clone();
1835 let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1836 assert_eq!(excerpt_ids.len(), 1);
1837 let excerpt_id = excerpt_ids[0];
1838 let buffer = editor
1839 .read(cx)
1840 .buffer()
1841 .read(cx)
1842 .all_buffers()
1843 .into_iter()
1844 .next()
1845 .unwrap();
1846 let buffer_id = buffer.read(cx).remote_id();
1847 let conflict_set = diff
1848 .read(cx)
1849 .editor
1850 .read(cx)
1851 .addon::<ConflictAddon>()
1852 .unwrap()
1853 .conflict_set(buffer_id)
1854 .unwrap();
1855 assert!(conflict_set.read(cx).has_conflict);
1856 let snapshot = conflict_set.read(cx).snapshot();
1857 assert_eq!(snapshot.conflicts.len(), 1);
1858
1859 let ours_range = snapshot.conflicts[0].ours.clone();
1860
1861 resolve_conflict(
1862 editor.downgrade(),
1863 excerpt_id,
1864 snapshot.conflicts[0].clone(),
1865 vec![ours_range],
1866 window,
1867 cx,
1868 )
1869 })
1870 .await;
1871
1872 let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1873 let contents = String::from_utf8(contents).unwrap();
1874 assert_eq!(contents, "ours\n");
1875 }
1876}