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 ) -> Option<Entity<Self>>
629 where
630 Self: Sized,
631 {
632 let workspace = self.workspace.upgrade()?;
633 Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
634 }
635
636 fn is_dirty(&self, cx: &App) -> bool {
637 self.multibuffer.read(cx).is_dirty(cx)
638 }
639
640 fn has_conflict(&self, cx: &App) -> bool {
641 self.multibuffer.read(cx).has_conflict(cx)
642 }
643
644 fn can_save(&self, _: &App) -> bool {
645 true
646 }
647
648 fn save(
649 &mut self,
650 options: SaveOptions,
651 project: Entity<Project>,
652 window: &mut Window,
653 cx: &mut Context<Self>,
654 ) -> Task<Result<()>> {
655 self.editor.save(options, project, window, cx)
656 }
657
658 fn save_as(
659 &mut self,
660 _: Entity<Project>,
661 _: ProjectPath,
662 _window: &mut Window,
663 _: &mut Context<Self>,
664 ) -> Task<Result<()>> {
665 unreachable!()
666 }
667
668 fn reload(
669 &mut self,
670 project: Entity<Project>,
671 window: &mut Window,
672 cx: &mut Context<Self>,
673 ) -> Task<Result<()>> {
674 self.editor.reload(project, window, cx)
675 }
676
677 fn act_as_type<'a>(
678 &'a self,
679 type_id: TypeId,
680 self_handle: &'a Entity<Self>,
681 _: &'a App,
682 ) -> Option<AnyView> {
683 if type_id == TypeId::of::<Self>() {
684 Some(self_handle.to_any())
685 } else if type_id == TypeId::of::<Editor>() {
686 Some(self.editor.to_any())
687 } else {
688 None
689 }
690 }
691
692 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
693 ToolbarItemLocation::PrimaryLeft
694 }
695
696 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
697 self.editor.breadcrumbs(theme, cx)
698 }
699
700 fn added_to_workspace(
701 &mut self,
702 workspace: &mut Workspace,
703 window: &mut Window,
704 cx: &mut Context<Self>,
705 ) {
706 self.editor.update(cx, |editor, cx| {
707 editor.added_to_workspace(workspace, window, cx)
708 });
709 }
710}
711
712impl Render for ProjectDiff {
713 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
714 let is_empty = self.multibuffer.read(cx).is_empty();
715
716 div()
717 .track_focus(&self.focus_handle)
718 .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
719 .bg(cx.theme().colors().editor_background)
720 .flex()
721 .items_center()
722 .justify_center()
723 .size_full()
724 .when(is_empty, |el| {
725 let remote_button = if let Some(panel) = self
726 .workspace
727 .upgrade()
728 .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
729 {
730 panel.update(cx, |panel, cx| panel.render_remote_button(cx))
731 } else {
732 None
733 };
734 let keybinding_focus_handle = self.focus_handle(cx);
735 el.child(
736 v_flex()
737 .gap_1()
738 .child(
739 h_flex()
740 .justify_around()
741 .child(Label::new("No uncommitted changes")),
742 )
743 .map(|el| match remote_button {
744 Some(button) => el.child(h_flex().justify_around().child(button)),
745 None => el.child(
746 h_flex()
747 .justify_around()
748 .child(Label::new("Remote up to date")),
749 ),
750 })
751 .child(
752 h_flex().justify_around().mt_1().child(
753 Button::new("project-diff-close-button", "Close")
754 // .style(ButtonStyle::Transparent)
755 .key_binding(KeyBinding::for_action_in(
756 &CloseActiveItem::default(),
757 &keybinding_focus_handle,
758 window,
759 cx,
760 ))
761 .on_click(move |_, window, cx| {
762 window.focus(&keybinding_focus_handle);
763 window.dispatch_action(
764 Box::new(CloseActiveItem::default()),
765 cx,
766 );
767 }),
768 ),
769 ),
770 )
771 })
772 .when(!is_empty, |el| el.child(self.editor.clone()))
773 }
774}
775
776impl SerializableItem for ProjectDiff {
777 fn serialized_item_kind() -> &'static str {
778 "ProjectDiff"
779 }
780
781 fn cleanup(
782 _: workspace::WorkspaceId,
783 _: Vec<workspace::ItemId>,
784 _: &mut Window,
785 _: &mut App,
786 ) -> Task<Result<()>> {
787 Task::ready(Ok(()))
788 }
789
790 fn deserialize(
791 _project: Entity<Project>,
792 workspace: WeakEntity<Workspace>,
793 _workspace_id: workspace::WorkspaceId,
794 _item_id: workspace::ItemId,
795 window: &mut Window,
796 cx: &mut App,
797 ) -> Task<Result<Entity<Self>>> {
798 window.spawn(cx, async move |cx| {
799 workspace.update_in(cx, |workspace, window, cx| {
800 let workspace_handle = cx.entity();
801 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
802 })
803 })
804 }
805
806 fn serialize(
807 &mut self,
808 _workspace: &mut Workspace,
809 _item_id: workspace::ItemId,
810 _closing: bool,
811 _window: &mut Window,
812 _cx: &mut Context<Self>,
813 ) -> Option<Task<Result<()>>> {
814 None
815 }
816
817 fn should_serialize(&self, _: &Self::Event) -> bool {
818 false
819 }
820}
821
822pub struct ProjectDiffToolbar {
823 project_diff: Option<WeakEntity<ProjectDiff>>,
824 workspace: WeakEntity<Workspace>,
825}
826
827impl ProjectDiffToolbar {
828 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
829 Self {
830 project_diff: None,
831 workspace: workspace.weak_handle(),
832 }
833 }
834
835 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
836 self.project_diff.as_ref()?.upgrade()
837 }
838
839 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
840 if let Some(project_diff) = self.project_diff(cx) {
841 project_diff.focus_handle(cx).focus(window);
842 }
843 let action = action.boxed_clone();
844 cx.defer(move |cx| {
845 cx.dispatch_action(action.as_ref());
846 })
847 }
848
849 fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
850 self.workspace
851 .update(cx, |workspace, cx| {
852 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
853 panel.update(cx, |panel, cx| {
854 panel.stage_all(&Default::default(), window, cx);
855 });
856 }
857 })
858 .ok();
859 }
860
861 fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
862 self.workspace
863 .update(cx, |workspace, cx| {
864 let Some(panel) = workspace.panel::<GitPanel>(cx) else {
865 return;
866 };
867 panel.update(cx, |panel, cx| {
868 panel.unstage_all(&Default::default(), window, cx);
869 });
870 })
871 .ok();
872 }
873}
874
875impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
876
877impl ToolbarItemView for ProjectDiffToolbar {
878 fn set_active_pane_item(
879 &mut self,
880 active_pane_item: Option<&dyn ItemHandle>,
881 _: &mut Window,
882 cx: &mut Context<Self>,
883 ) -> ToolbarItemLocation {
884 self.project_diff = active_pane_item
885 .and_then(|item| item.act_as::<ProjectDiff>(cx))
886 .map(|entity| entity.downgrade());
887 if self.project_diff.is_some() {
888 ToolbarItemLocation::PrimaryRight
889 } else {
890 ToolbarItemLocation::Hidden
891 }
892 }
893
894 fn pane_focus_update(
895 &mut self,
896 _pane_focused: bool,
897 _window: &mut Window,
898 _cx: &mut Context<Self>,
899 ) {
900 }
901}
902
903struct ButtonStates {
904 stage: bool,
905 unstage: bool,
906 prev_next: bool,
907 selection: bool,
908 stage_all: bool,
909 unstage_all: bool,
910}
911
912impl Render for ProjectDiffToolbar {
913 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
914 let Some(project_diff) = self.project_diff(cx) else {
915 return div();
916 };
917 let focus_handle = project_diff.focus_handle(cx);
918 let button_states = project_diff.read(cx).button_states(cx);
919
920 h_group_xl()
921 .my_neg_1()
922 .py_1()
923 .items_center()
924 .flex_wrap()
925 .justify_between()
926 .child(
927 h_group_sm()
928 .when(button_states.selection, |el| {
929 el.child(
930 Button::new("stage", "Toggle Staged")
931 .tooltip(Tooltip::for_action_title_in(
932 "Toggle Staged",
933 &ToggleStaged,
934 &focus_handle,
935 ))
936 .disabled(!button_states.stage && !button_states.unstage)
937 .on_click(cx.listener(|this, _, window, cx| {
938 this.dispatch_action(&ToggleStaged, window, cx)
939 })),
940 )
941 })
942 .when(!button_states.selection, |el| {
943 el.child(
944 Button::new("stage", "Stage")
945 .tooltip(Tooltip::for_action_title_in(
946 "Stage and go to next hunk",
947 &StageAndNext,
948 &focus_handle,
949 ))
950 .on_click(cx.listener(|this, _, window, cx| {
951 this.dispatch_action(&StageAndNext, window, cx)
952 })),
953 )
954 .child(
955 Button::new("unstage", "Unstage")
956 .tooltip(Tooltip::for_action_title_in(
957 "Unstage and go to next hunk",
958 &UnstageAndNext,
959 &focus_handle,
960 ))
961 .on_click(cx.listener(|this, _, window, cx| {
962 this.dispatch_action(&UnstageAndNext, window, cx)
963 })),
964 )
965 }),
966 )
967 // n.b. the only reason these arrows are here is because we don't
968 // support "undo" for staging so we need a way to go back.
969 .child(
970 h_group_sm()
971 .child(
972 IconButton::new("up", IconName::ArrowUp)
973 .shape(ui::IconButtonShape::Square)
974 .tooltip(Tooltip::for_action_title_in(
975 "Go to previous hunk",
976 &GoToPreviousHunk,
977 &focus_handle,
978 ))
979 .disabled(!button_states.prev_next)
980 .on_click(cx.listener(|this, _, window, cx| {
981 this.dispatch_action(&GoToPreviousHunk, window, cx)
982 })),
983 )
984 .child(
985 IconButton::new("down", IconName::ArrowDown)
986 .shape(ui::IconButtonShape::Square)
987 .tooltip(Tooltip::for_action_title_in(
988 "Go to next hunk",
989 &GoToHunk,
990 &focus_handle,
991 ))
992 .disabled(!button_states.prev_next)
993 .on_click(cx.listener(|this, _, window, cx| {
994 this.dispatch_action(&GoToHunk, window, cx)
995 })),
996 ),
997 )
998 .child(vertical_divider())
999 .child(
1000 h_group_sm()
1001 .when(
1002 button_states.unstage_all && !button_states.stage_all,
1003 |el| {
1004 el.child(
1005 Button::new("unstage-all", "Unstage All")
1006 .tooltip(Tooltip::for_action_title_in(
1007 "Unstage all changes",
1008 &UnstageAll,
1009 &focus_handle,
1010 ))
1011 .on_click(cx.listener(|this, _, window, cx| {
1012 this.unstage_all(window, cx)
1013 })),
1014 )
1015 },
1016 )
1017 .when(
1018 !button_states.unstage_all || button_states.stage_all,
1019 |el| {
1020 el.child(
1021 // todo make it so that changing to say "Unstaged"
1022 // doesn't change the position.
1023 div().child(
1024 Button::new("stage-all", "Stage All")
1025 .disabled(!button_states.stage_all)
1026 .tooltip(Tooltip::for_action_title_in(
1027 "Stage all changes",
1028 &StageAll,
1029 &focus_handle,
1030 ))
1031 .on_click(cx.listener(|this, _, window, cx| {
1032 this.stage_all(window, cx)
1033 })),
1034 ),
1035 )
1036 },
1037 )
1038 .child(
1039 Button::new("commit", "Commit")
1040 .tooltip(Tooltip::for_action_title_in(
1041 "Commit",
1042 &Commit,
1043 &focus_handle,
1044 ))
1045 .on_click(cx.listener(|this, _, window, cx| {
1046 this.dispatch_action(&Commit, window, cx);
1047 })),
1048 ),
1049 )
1050 }
1051}
1052
1053#[derive(IntoElement, RegisterComponent)]
1054pub struct ProjectDiffEmptyState {
1055 pub no_repo: bool,
1056 pub can_push_and_pull: bool,
1057 pub focus_handle: Option<FocusHandle>,
1058 pub current_branch: Option<Branch>,
1059 // has_pending_commits: bool,
1060 // ahead_of_remote: bool,
1061 // no_git_repository: bool,
1062}
1063
1064impl RenderOnce for ProjectDiffEmptyState {
1065 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1066 let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1067 matches!(self.current_branch, Some(Branch {
1068 upstream:
1069 Some(Upstream {
1070 tracking:
1071 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1072 ahead, behind, ..
1073 }),
1074 ..
1075 }),
1076 ..
1077 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1078 };
1079
1080 let change_count = |current_branch: &Branch| -> (usize, usize) {
1081 match current_branch {
1082 Branch {
1083 upstream:
1084 Some(Upstream {
1085 tracking:
1086 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1087 ahead, behind, ..
1088 }),
1089 ..
1090 }),
1091 ..
1092 } => (*ahead as usize, *behind as usize),
1093 _ => (0, 0),
1094 }
1095 };
1096
1097 let not_ahead_or_behind = status_against_remote(0, 0);
1098 let ahead_of_remote = status_against_remote(1, 0);
1099 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1100 branch.upstream.is_none()
1101 } else {
1102 false
1103 };
1104
1105 let has_branch_container = |branch: &Branch| {
1106 h_flex()
1107 .max_w(px(420.))
1108 .bg(cx.theme().colors().text.opacity(0.05))
1109 .border_1()
1110 .border_color(cx.theme().colors().border)
1111 .rounded_sm()
1112 .gap_8()
1113 .px_6()
1114 .py_4()
1115 .map(|this| {
1116 if ahead_of_remote {
1117 let ahead_count = change_count(branch).0;
1118 let ahead_string = format!("{} Commits Ahead", ahead_count);
1119 this.child(
1120 v_flex()
1121 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1122 .child(
1123 Label::new(format!("Push your changes to {}", branch.name()))
1124 .color(Color::Muted),
1125 ),
1126 )
1127 .child(div().child(render_push_button(
1128 self.focus_handle,
1129 "push".into(),
1130 ahead_count as u32,
1131 )))
1132 } else if branch_not_on_remote {
1133 this.child(
1134 v_flex()
1135 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1136 .child(
1137 Label::new(format!("Create {} on remote", branch.name()))
1138 .color(Color::Muted),
1139 ),
1140 )
1141 .child(
1142 div().child(render_publish_button(self.focus_handle, "publish".into())),
1143 )
1144 } else {
1145 this.child(Label::new("Remote status unknown").color(Color::Muted))
1146 }
1147 })
1148 };
1149
1150 v_flex().size_full().items_center().justify_center().child(
1151 v_flex()
1152 .gap_1()
1153 .when(self.no_repo, |this| {
1154 // TODO: add git init
1155 this.text_center()
1156 .child(Label::new("No Repository").color(Color::Muted))
1157 })
1158 .map(|this| {
1159 if not_ahead_or_behind && self.current_branch.is_some() {
1160 this.text_center()
1161 .child(Label::new("No Changes").color(Color::Muted))
1162 } else {
1163 this.when_some(self.current_branch.as_ref(), |this, branch| {
1164 this.child(has_branch_container(branch))
1165 })
1166 }
1167 }),
1168 )
1169 }
1170}
1171
1172mod preview {
1173 use git::repository::{
1174 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1175 };
1176 use ui::prelude::*;
1177
1178 use super::ProjectDiffEmptyState;
1179
1180 // View this component preview using `workspace: open component-preview`
1181 impl Component for ProjectDiffEmptyState {
1182 fn scope() -> ComponentScope {
1183 ComponentScope::VersionControl
1184 }
1185
1186 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1187 let unknown_upstream: Option<UpstreamTracking> = None;
1188 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1189 UpstreamTrackingStatus {
1190 ahead: 2,
1191 behind: 0,
1192 }
1193 .into(),
1194 );
1195
1196 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1197 UpstreamTrackingStatus {
1198 ahead: 0,
1199 behind: 0,
1200 }
1201 .into(),
1202 );
1203
1204 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1205 Branch {
1206 is_head: true,
1207 ref_name: "some-branch".into(),
1208 upstream: upstream.map(|tracking| Upstream {
1209 ref_name: "origin/some-branch".into(),
1210 tracking,
1211 }),
1212 most_recent_commit: Some(CommitSummary {
1213 sha: "abc123".into(),
1214 subject: "Modify stuff".into(),
1215 commit_timestamp: 1710932954,
1216 author_name: "John Doe".into(),
1217 has_parent: true,
1218 }),
1219 }
1220 }
1221
1222 let no_repo_state = ProjectDiffEmptyState {
1223 no_repo: true,
1224 can_push_and_pull: false,
1225 focus_handle: None,
1226 current_branch: None,
1227 };
1228
1229 let no_changes_state = ProjectDiffEmptyState {
1230 no_repo: false,
1231 can_push_and_pull: true,
1232 focus_handle: None,
1233 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1234 };
1235
1236 let ahead_of_upstream_state = ProjectDiffEmptyState {
1237 no_repo: false,
1238 can_push_and_pull: true,
1239 focus_handle: None,
1240 current_branch: Some(branch(ahead_of_upstream)),
1241 };
1242
1243 let unknown_upstream_state = ProjectDiffEmptyState {
1244 no_repo: false,
1245 can_push_and_pull: true,
1246 focus_handle: None,
1247 current_branch: Some(branch(unknown_upstream)),
1248 };
1249
1250 let (width, height) = (px(480.), px(320.));
1251
1252 Some(
1253 v_flex()
1254 .gap_6()
1255 .children(vec![
1256 example_group(vec![
1257 single_example(
1258 "No Repo",
1259 div()
1260 .w(width)
1261 .h(height)
1262 .child(no_repo_state)
1263 .into_any_element(),
1264 ),
1265 single_example(
1266 "No Changes",
1267 div()
1268 .w(width)
1269 .h(height)
1270 .child(no_changes_state)
1271 .into_any_element(),
1272 ),
1273 single_example(
1274 "Unknown Upstream",
1275 div()
1276 .w(width)
1277 .h(height)
1278 .child(unknown_upstream_state)
1279 .into_any_element(),
1280 ),
1281 single_example(
1282 "Ahead of Remote",
1283 div()
1284 .w(width)
1285 .h(height)
1286 .child(ahead_of_upstream_state)
1287 .into_any_element(),
1288 ),
1289 ])
1290 .vertical(),
1291 ])
1292 .into_any_element(),
1293 )
1294 }
1295 }
1296}
1297
1298fn merge_anchor_ranges<'a>(
1299 left: impl 'a + Iterator<Item = Range<Anchor>>,
1300 right: impl 'a + Iterator<Item = Range<Anchor>>,
1301 snapshot: &'a language::BufferSnapshot,
1302) -> impl 'a + Iterator<Item = Range<Anchor>> {
1303 let mut left = left.fuse().peekable();
1304 let mut right = right.fuse().peekable();
1305
1306 std::iter::from_fn(move || {
1307 let Some(left_range) = left.peek() else {
1308 return right.next();
1309 };
1310 let Some(right_range) = right.peek() else {
1311 return left.next();
1312 };
1313
1314 let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1315 left.next().unwrap()
1316 } else {
1317 right.next().unwrap()
1318 };
1319
1320 // Extend the basic range while there's overlap with a range from either stream.
1321 loop {
1322 if let Some(left_range) = left
1323 .peek()
1324 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1325 .cloned()
1326 {
1327 left.next();
1328 next_range.end = left_range.end;
1329 } else if let Some(right_range) = right
1330 .peek()
1331 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1332 .cloned()
1333 {
1334 right.next();
1335 next_range.end = right_range.end;
1336 } else {
1337 break;
1338 }
1339 }
1340
1341 Some(next_range)
1342 })
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use db::indoc;
1348 use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1349 use git::status::{UnmergedStatus, UnmergedStatusCode};
1350 use gpui::TestAppContext;
1351 use project::FakeFs;
1352 use serde_json::json;
1353 use settings::SettingsStore;
1354 use std::path::Path;
1355 use unindent::Unindent as _;
1356 use util::{path, rel_path::rel_path};
1357
1358 use super::*;
1359
1360 #[ctor::ctor]
1361 fn init_logger() {
1362 zlog::init_test();
1363 }
1364
1365 fn init_test(cx: &mut TestAppContext) {
1366 cx.update(|cx| {
1367 let store = SettingsStore::test(cx);
1368 cx.set_global(store);
1369 theme::init(theme::LoadThemes::JustBase, cx);
1370 language::init(cx);
1371 Project::init_settings(cx);
1372 workspace::init_settings(cx);
1373 editor::init(cx);
1374 crate::init(cx);
1375 });
1376 }
1377
1378 #[gpui::test]
1379 async fn test_save_after_restore(cx: &mut TestAppContext) {
1380 init_test(cx);
1381
1382 let fs = FakeFs::new(cx.executor());
1383 fs.insert_tree(
1384 path!("/project"),
1385 json!({
1386 ".git": {},
1387 "foo.txt": "FOO\n",
1388 }),
1389 )
1390 .await;
1391 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1392 let (workspace, cx) =
1393 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1394 let diff = cx.new_window_entity(|window, cx| {
1395 ProjectDiff::new(project.clone(), workspace, window, cx)
1396 });
1397 cx.run_until_parked();
1398
1399 fs.set_head_for_repo(
1400 path!("/project/.git").as_ref(),
1401 &[("foo.txt", "foo\n".into())],
1402 "deadbeef",
1403 );
1404 fs.set_index_for_repo(
1405 path!("/project/.git").as_ref(),
1406 &[("foo.txt", "foo\n".into())],
1407 );
1408 cx.run_until_parked();
1409
1410 let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1411 assert_state_with_diff(
1412 &editor,
1413 cx,
1414 &"
1415 - foo
1416 + ˇFOO
1417 "
1418 .unindent(),
1419 );
1420
1421 editor.update_in(cx, |editor, window, cx| {
1422 editor.git_restore(&Default::default(), window, cx);
1423 });
1424 cx.run_until_parked();
1425
1426 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1427
1428 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1429 assert_eq!(text, "foo\n");
1430 }
1431
1432 #[gpui::test]
1433 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1434 init_test(cx);
1435
1436 let fs = FakeFs::new(cx.executor());
1437 fs.insert_tree(
1438 path!("/project"),
1439 json!({
1440 ".git": {},
1441 "bar": "BAR\n",
1442 "foo": "FOO\n",
1443 }),
1444 )
1445 .await;
1446 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1447 let (workspace, cx) =
1448 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1449 let diff = cx.new_window_entity(|window, cx| {
1450 ProjectDiff::new(project.clone(), workspace, window, cx)
1451 });
1452 cx.run_until_parked();
1453
1454 fs.set_head_and_index_for_repo(
1455 path!("/project/.git").as_ref(),
1456 &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1457 );
1458 cx.run_until_parked();
1459
1460 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1461 diff.move_to_path(
1462 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("foo").into_arc()),
1463 window,
1464 cx,
1465 );
1466 diff.editor.clone()
1467 });
1468 assert_state_with_diff(
1469 &editor,
1470 cx,
1471 &"
1472 - bar
1473 + BAR
1474
1475 - ˇfoo
1476 + FOO
1477 "
1478 .unindent(),
1479 );
1480
1481 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1482 diff.move_to_path(
1483 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("bar").into_arc()),
1484 window,
1485 cx,
1486 );
1487 diff.editor.clone()
1488 });
1489 assert_state_with_diff(
1490 &editor,
1491 cx,
1492 &"
1493 - ˇbar
1494 + BAR
1495
1496 - foo
1497 + FOO
1498 "
1499 .unindent(),
1500 );
1501 }
1502
1503 #[gpui::test]
1504 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1505 init_test(cx);
1506
1507 let fs = FakeFs::new(cx.executor());
1508 fs.insert_tree(
1509 path!("/project"),
1510 json!({
1511 ".git": {},
1512 "foo": "modified\n",
1513 }),
1514 )
1515 .await;
1516 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1517 let (workspace, cx) =
1518 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1519 let buffer = project
1520 .update(cx, |project, cx| {
1521 project.open_local_buffer(path!("/project/foo"), cx)
1522 })
1523 .await
1524 .unwrap();
1525 let buffer_editor = cx.new_window_entity(|window, cx| {
1526 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1527 });
1528 let diff = cx.new_window_entity(|window, cx| {
1529 ProjectDiff::new(project.clone(), workspace, window, cx)
1530 });
1531 cx.run_until_parked();
1532
1533 fs.set_head_for_repo(
1534 path!("/project/.git").as_ref(),
1535 &[("foo", "original\n".into())],
1536 "deadbeef",
1537 );
1538 cx.run_until_parked();
1539
1540 let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1541
1542 assert_state_with_diff(
1543 &diff_editor,
1544 cx,
1545 &"
1546 - original
1547 + ˇmodified
1548 "
1549 .unindent(),
1550 );
1551
1552 let prev_buffer_hunks =
1553 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1554 let snapshot = buffer_editor.snapshot(window, cx);
1555 let snapshot = &snapshot.buffer_snapshot();
1556 let prev_buffer_hunks = buffer_editor
1557 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1558 .collect::<Vec<_>>();
1559 buffer_editor.git_restore(&Default::default(), window, cx);
1560 prev_buffer_hunks
1561 });
1562 assert_eq!(prev_buffer_hunks.len(), 1);
1563 cx.run_until_parked();
1564
1565 let new_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 buffer_editor
1570 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1571 .collect::<Vec<_>>()
1572 });
1573 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1574
1575 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1576 buffer_editor.set_text("different\n", window, cx);
1577 buffer_editor.save(
1578 SaveOptions {
1579 format: false,
1580 autosave: false,
1581 },
1582 project.clone(),
1583 window,
1584 cx,
1585 )
1586 })
1587 .await
1588 .unwrap();
1589
1590 cx.run_until_parked();
1591
1592 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1593 buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1594 });
1595
1596 assert_state_with_diff(
1597 &buffer_editor,
1598 cx,
1599 &"
1600 - original
1601 + different
1602 ˇ"
1603 .unindent(),
1604 );
1605
1606 assert_state_with_diff(
1607 &diff_editor,
1608 cx,
1609 &"
1610 - original
1611 + different
1612 ˇ"
1613 .unindent(),
1614 );
1615 }
1616
1617 use crate::{
1618 conflict_view::resolve_conflict,
1619 project_diff::{self, ProjectDiff},
1620 };
1621
1622 #[gpui::test]
1623 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1624 init_test(cx);
1625
1626 let fs = FakeFs::new(cx.executor());
1627 fs.insert_tree(
1628 path!("/a"),
1629 json!({
1630 ".git": {},
1631 "a.txt": "created\n",
1632 "b.txt": "really changed\n",
1633 "c.txt": "unchanged\n"
1634 }),
1635 )
1636 .await;
1637
1638 fs.set_head_and_index_for_repo(
1639 Path::new(path!("/a/.git")),
1640 &[
1641 ("b.txt", "before\n".to_string()),
1642 ("c.txt", "unchanged\n".to_string()),
1643 ("d.txt", "deleted\n".to_string()),
1644 ],
1645 );
1646
1647 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1648 let (workspace, cx) =
1649 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1650
1651 cx.run_until_parked();
1652
1653 cx.focus(&workspace);
1654 cx.update(|window, cx| {
1655 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1656 });
1657
1658 cx.run_until_parked();
1659
1660 let item = workspace.update(cx, |workspace, cx| {
1661 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1662 });
1663 cx.focus(&item);
1664 let editor = item.read_with(cx, |item, _| item.editor.clone());
1665
1666 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1667
1668 cx.assert_excerpts_with_selections(indoc!(
1669 "
1670 [EXCERPT]
1671 before
1672 really changed
1673 [EXCERPT]
1674 [FOLDED]
1675 [EXCERPT]
1676 ˇcreated
1677 "
1678 ));
1679
1680 cx.dispatch_action(editor::actions::GoToPreviousHunk);
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
1709 #[gpui::test]
1710 async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1711 init_test(cx);
1712
1713 let git_contents = indoc! {r#"
1714 #[rustfmt::skip]
1715 fn main() {
1716 let x = 0.0; // this line will be removed
1717 // 1
1718 // 2
1719 // 3
1720 let y = 0.0; // this line will be removed
1721 // 1
1722 // 2
1723 // 3
1724 let arr = [
1725 0.0, // this line will be removed
1726 0.0, // this line will be removed
1727 0.0, // this line will be removed
1728 0.0, // this line will be removed
1729 ];
1730 }
1731 "#};
1732 let buffer_contents = indoc! {"
1733 #[rustfmt::skip]
1734 fn main() {
1735 // 1
1736 // 2
1737 // 3
1738 // 1
1739 // 2
1740 // 3
1741 let arr = [
1742 ];
1743 }
1744 "};
1745
1746 let fs = FakeFs::new(cx.executor());
1747 fs.insert_tree(
1748 path!("/a"),
1749 json!({
1750 ".git": {},
1751 "main.rs": buffer_contents,
1752 }),
1753 )
1754 .await;
1755
1756 fs.set_head_and_index_for_repo(
1757 Path::new(path!("/a/.git")),
1758 &[("main.rs", git_contents.to_owned())],
1759 );
1760
1761 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1762 let (workspace, cx) =
1763 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1764
1765 cx.run_until_parked();
1766
1767 cx.focus(&workspace);
1768 cx.update(|window, cx| {
1769 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1770 });
1771
1772 cx.run_until_parked();
1773
1774 let item = workspace.update(cx, |workspace, cx| {
1775 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1776 });
1777 cx.focus(&item);
1778 let editor = item.read_with(cx, |item, _| item.editor.clone());
1779
1780 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1781
1782 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1783
1784 cx.dispatch_action(editor::actions::GoToHunk);
1785 cx.dispatch_action(editor::actions::GoToHunk);
1786 cx.dispatch_action(git::Restore);
1787 cx.dispatch_action(editor::actions::MoveToBeginning);
1788
1789 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1790 }
1791
1792 #[gpui::test]
1793 async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1794 init_test(cx);
1795
1796 let fs = FakeFs::new(cx.executor());
1797 fs.insert_tree(
1798 path!("/project"),
1799 json!({
1800 ".git": {},
1801 "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1802 }),
1803 )
1804 .await;
1805 fs.set_status_for_repo(
1806 Path::new(path!("/project/.git")),
1807 &[(
1808 "foo",
1809 UnmergedStatus {
1810 first_head: UnmergedStatusCode::Updated,
1811 second_head: UnmergedStatusCode::Updated,
1812 }
1813 .into(),
1814 )],
1815 );
1816 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1817 let (workspace, cx) =
1818 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1819 let diff = cx.new_window_entity(|window, cx| {
1820 ProjectDiff::new(project.clone(), workspace, window, cx)
1821 });
1822 cx.run_until_parked();
1823
1824 cx.update(|window, cx| {
1825 let editor = diff.read(cx).editor.clone();
1826 let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1827 assert_eq!(excerpt_ids.len(), 1);
1828 let excerpt_id = excerpt_ids[0];
1829 let buffer = editor
1830 .read(cx)
1831 .buffer()
1832 .read(cx)
1833 .all_buffers()
1834 .into_iter()
1835 .next()
1836 .unwrap();
1837 let buffer_id = buffer.read(cx).remote_id();
1838 let conflict_set = diff
1839 .read(cx)
1840 .editor
1841 .read(cx)
1842 .addon::<ConflictAddon>()
1843 .unwrap()
1844 .conflict_set(buffer_id)
1845 .unwrap();
1846 assert!(conflict_set.read(cx).has_conflict);
1847 let snapshot = conflict_set.read(cx).snapshot();
1848 assert_eq!(snapshot.conflicts.len(), 1);
1849
1850 let ours_range = snapshot.conflicts[0].ours.clone();
1851
1852 resolve_conflict(
1853 editor.downgrade(),
1854 excerpt_id,
1855 snapshot.conflicts[0].clone(),
1856 vec![ours_range],
1857 window,
1858 cx,
1859 )
1860 })
1861 .await;
1862
1863 let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1864 let contents = String::from_utf8(contents).unwrap();
1865 assert_eq!(contents, "ours\n");
1866 }
1867
1868 #[gpui::test]
1869 async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
1870 init_test(cx);
1871
1872 let fs = FakeFs::new(cx.executor());
1873 fs.insert_tree(
1874 path!("/project"),
1875 json!({
1876 ".git": {},
1877 "foo.txt": "
1878 one
1879 two
1880 three
1881 four
1882 five
1883 six
1884 seven
1885 eight
1886 nine
1887 ten
1888 ELEVEN
1889 twelve
1890 ".unindent()
1891 }),
1892 )
1893 .await;
1894 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1895 let (workspace, cx) =
1896 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1897 let diff = cx.new_window_entity(|window, cx| {
1898 ProjectDiff::new(project.clone(), workspace, window, cx)
1899 });
1900 cx.run_until_parked();
1901
1902 fs.set_head_and_index_for_repo(
1903 Path::new(path!("/project/.git")),
1904 &[(
1905 "foo.txt",
1906 "
1907 one
1908 two
1909 three
1910 four
1911 five
1912 six
1913 seven
1914 eight
1915 nine
1916 ten
1917 eleven
1918 twelve
1919 "
1920 .unindent(),
1921 )],
1922 );
1923 cx.run_until_parked();
1924
1925 let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1926
1927 assert_state_with_diff(
1928 &editor,
1929 cx,
1930 &"
1931 ˇnine
1932 ten
1933 - eleven
1934 + ELEVEN
1935 twelve
1936 "
1937 .unindent(),
1938 );
1939
1940 let buffer = project
1941 .update(cx, |project, cx| {
1942 project.open_local_buffer(path!("/project/foo.txt"), cx)
1943 })
1944 .await
1945 .unwrap();
1946 buffer.update(cx, |buffer, cx| {
1947 buffer.edit_via_marked_text(
1948 &"
1949 one
1950 «TWO»
1951 three
1952 four
1953 five
1954 six
1955 seven
1956 eight
1957 nine
1958 ten
1959 ELEVEN
1960 twelve
1961 "
1962 .unindent(),
1963 None,
1964 cx,
1965 );
1966 });
1967 project
1968 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
1969 .await
1970 .unwrap();
1971 cx.run_until_parked();
1972
1973 assert_state_with_diff(
1974 &editor,
1975 cx,
1976 &"
1977 one
1978 - two
1979 + TWO
1980 three
1981 four
1982 five
1983 ˇnine
1984 ten
1985 - eleven
1986 + ELEVEN
1987 twelve
1988 "
1989 .unindent(),
1990 );
1991 }
1992}