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