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