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 .disabled(
951 !button_states.prev_next
952 && !button_states.stage_all
953 && !button_states.unstage_all,
954 )
955 .on_click(cx.listener(|this, _, window, cx| {
956 this.dispatch_action(&StageAndNext, window, cx)
957 })),
958 )
959 .child(
960 Button::new("unstage", "Unstage")
961 .tooltip(Tooltip::for_action_title_in(
962 "Unstage and go to next hunk",
963 &UnstageAndNext,
964 &focus_handle,
965 ))
966 .disabled(
967 !button_states.prev_next
968 && !button_states.stage_all
969 && !button_states.unstage_all,
970 )
971 .on_click(cx.listener(|this, _, window, cx| {
972 this.dispatch_action(&UnstageAndNext, window, cx)
973 })),
974 )
975 }),
976 )
977 // n.b. the only reason these arrows are here is because we don't
978 // support "undo" for staging so we need a way to go back.
979 .child(
980 h_group_sm()
981 .child(
982 IconButton::new("up", IconName::ArrowUp)
983 .shape(ui::IconButtonShape::Square)
984 .tooltip(Tooltip::for_action_title_in(
985 "Go to previous hunk",
986 &GoToPreviousHunk,
987 &focus_handle,
988 ))
989 .disabled(!button_states.prev_next)
990 .on_click(cx.listener(|this, _, window, cx| {
991 this.dispatch_action(&GoToPreviousHunk, window, cx)
992 })),
993 )
994 .child(
995 IconButton::new("down", IconName::ArrowDown)
996 .shape(ui::IconButtonShape::Square)
997 .tooltip(Tooltip::for_action_title_in(
998 "Go to next hunk",
999 &GoToHunk,
1000 &focus_handle,
1001 ))
1002 .disabled(!button_states.prev_next)
1003 .on_click(cx.listener(|this, _, window, cx| {
1004 this.dispatch_action(&GoToHunk, window, cx)
1005 })),
1006 ),
1007 )
1008 .child(vertical_divider())
1009 .child(
1010 h_group_sm()
1011 .when(
1012 button_states.unstage_all && !button_states.stage_all,
1013 |el| {
1014 el.child(
1015 Button::new("unstage-all", "Unstage All")
1016 .tooltip(Tooltip::for_action_title_in(
1017 "Unstage all changes",
1018 &UnstageAll,
1019 &focus_handle,
1020 ))
1021 .on_click(cx.listener(|this, _, window, cx| {
1022 this.unstage_all(window, cx)
1023 })),
1024 )
1025 },
1026 )
1027 .when(
1028 !button_states.unstage_all || button_states.stage_all,
1029 |el| {
1030 el.child(
1031 // todo make it so that changing to say "Unstaged"
1032 // doesn't change the position.
1033 div().child(
1034 Button::new("stage-all", "Stage All")
1035 .disabled(!button_states.stage_all)
1036 .tooltip(Tooltip::for_action_title_in(
1037 "Stage all changes",
1038 &StageAll,
1039 &focus_handle,
1040 ))
1041 .on_click(cx.listener(|this, _, window, cx| {
1042 this.stage_all(window, cx)
1043 })),
1044 ),
1045 )
1046 },
1047 )
1048 .child(
1049 Button::new("commit", "Commit")
1050 .tooltip(Tooltip::for_action_title_in(
1051 "Commit",
1052 &Commit,
1053 &focus_handle,
1054 ))
1055 .on_click(cx.listener(|this, _, window, cx| {
1056 this.dispatch_action(&Commit, window, cx);
1057 })),
1058 ),
1059 )
1060 }
1061}
1062
1063#[derive(IntoElement, RegisterComponent)]
1064pub struct ProjectDiffEmptyState {
1065 pub no_repo: bool,
1066 pub can_push_and_pull: bool,
1067 pub focus_handle: Option<FocusHandle>,
1068 pub current_branch: Option<Branch>,
1069 // has_pending_commits: bool,
1070 // ahead_of_remote: bool,
1071 // no_git_repository: bool,
1072}
1073
1074impl RenderOnce for ProjectDiffEmptyState {
1075 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1076 let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1077 matches!(self.current_branch, Some(Branch {
1078 upstream:
1079 Some(Upstream {
1080 tracking:
1081 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1082 ahead, behind, ..
1083 }),
1084 ..
1085 }),
1086 ..
1087 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1088 };
1089
1090 let change_count = |current_branch: &Branch| -> (usize, usize) {
1091 match current_branch {
1092 Branch {
1093 upstream:
1094 Some(Upstream {
1095 tracking:
1096 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1097 ahead, behind, ..
1098 }),
1099 ..
1100 }),
1101 ..
1102 } => (*ahead as usize, *behind as usize),
1103 _ => (0, 0),
1104 }
1105 };
1106
1107 let not_ahead_or_behind = status_against_remote(0, 0);
1108 let ahead_of_remote = status_against_remote(1, 0);
1109 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1110 branch.upstream.is_none()
1111 } else {
1112 false
1113 };
1114
1115 let has_branch_container = |branch: &Branch| {
1116 h_flex()
1117 .max_w(px(420.))
1118 .bg(cx.theme().colors().text.opacity(0.05))
1119 .border_1()
1120 .border_color(cx.theme().colors().border)
1121 .rounded_sm()
1122 .gap_8()
1123 .px_6()
1124 .py_4()
1125 .map(|this| {
1126 if ahead_of_remote {
1127 let ahead_count = change_count(branch).0;
1128 let ahead_string = format!("{} Commits Ahead", ahead_count);
1129 this.child(
1130 v_flex()
1131 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1132 .child(
1133 Label::new(format!("Push your changes to {}", branch.name()))
1134 .color(Color::Muted),
1135 ),
1136 )
1137 .child(div().child(render_push_button(
1138 self.focus_handle,
1139 "push".into(),
1140 ahead_count as u32,
1141 )))
1142 } else if branch_not_on_remote {
1143 this.child(
1144 v_flex()
1145 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1146 .child(
1147 Label::new(format!("Create {} on remote", branch.name()))
1148 .color(Color::Muted),
1149 ),
1150 )
1151 .child(
1152 div().child(render_publish_button(self.focus_handle, "publish".into())),
1153 )
1154 } else {
1155 this.child(Label::new("Remote status unknown").color(Color::Muted))
1156 }
1157 })
1158 };
1159
1160 v_flex().size_full().items_center().justify_center().child(
1161 v_flex()
1162 .gap_1()
1163 .when(self.no_repo, |this| {
1164 // TODO: add git init
1165 this.text_center()
1166 .child(Label::new("No Repository").color(Color::Muted))
1167 })
1168 .map(|this| {
1169 if not_ahead_or_behind && self.current_branch.is_some() {
1170 this.text_center()
1171 .child(Label::new("No Changes").color(Color::Muted))
1172 } else {
1173 this.when_some(self.current_branch.as_ref(), |this, branch| {
1174 this.child(has_branch_container(branch))
1175 })
1176 }
1177 }),
1178 )
1179 }
1180}
1181
1182mod preview {
1183 use git::repository::{
1184 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1185 };
1186 use ui::prelude::*;
1187
1188 use super::ProjectDiffEmptyState;
1189
1190 // View this component preview using `workspace: open component-preview`
1191 impl Component for ProjectDiffEmptyState {
1192 fn scope() -> ComponentScope {
1193 ComponentScope::VersionControl
1194 }
1195
1196 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1197 let unknown_upstream: Option<UpstreamTracking> = None;
1198 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1199 UpstreamTrackingStatus {
1200 ahead: 2,
1201 behind: 0,
1202 }
1203 .into(),
1204 );
1205
1206 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1207 UpstreamTrackingStatus {
1208 ahead: 0,
1209 behind: 0,
1210 }
1211 .into(),
1212 );
1213
1214 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1215 Branch {
1216 is_head: true,
1217 ref_name: "some-branch".into(),
1218 upstream: upstream.map(|tracking| Upstream {
1219 ref_name: "origin/some-branch".into(),
1220 tracking,
1221 }),
1222 most_recent_commit: Some(CommitSummary {
1223 sha: "abc123".into(),
1224 subject: "Modify stuff".into(),
1225 commit_timestamp: 1710932954,
1226 author_name: "John Doe".into(),
1227 has_parent: true,
1228 }),
1229 }
1230 }
1231
1232 let no_repo_state = ProjectDiffEmptyState {
1233 no_repo: true,
1234 can_push_and_pull: false,
1235 focus_handle: None,
1236 current_branch: None,
1237 };
1238
1239 let no_changes_state = ProjectDiffEmptyState {
1240 no_repo: false,
1241 can_push_and_pull: true,
1242 focus_handle: None,
1243 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1244 };
1245
1246 let ahead_of_upstream_state = ProjectDiffEmptyState {
1247 no_repo: false,
1248 can_push_and_pull: true,
1249 focus_handle: None,
1250 current_branch: Some(branch(ahead_of_upstream)),
1251 };
1252
1253 let unknown_upstream_state = ProjectDiffEmptyState {
1254 no_repo: false,
1255 can_push_and_pull: true,
1256 focus_handle: None,
1257 current_branch: Some(branch(unknown_upstream)),
1258 };
1259
1260 let (width, height) = (px(480.), px(320.));
1261
1262 Some(
1263 v_flex()
1264 .gap_6()
1265 .children(vec![
1266 example_group(vec![
1267 single_example(
1268 "No Repo",
1269 div()
1270 .w(width)
1271 .h(height)
1272 .child(no_repo_state)
1273 .into_any_element(),
1274 ),
1275 single_example(
1276 "No Changes",
1277 div()
1278 .w(width)
1279 .h(height)
1280 .child(no_changes_state)
1281 .into_any_element(),
1282 ),
1283 single_example(
1284 "Unknown Upstream",
1285 div()
1286 .w(width)
1287 .h(height)
1288 .child(unknown_upstream_state)
1289 .into_any_element(),
1290 ),
1291 single_example(
1292 "Ahead of Remote",
1293 div()
1294 .w(width)
1295 .h(height)
1296 .child(ahead_of_upstream_state)
1297 .into_any_element(),
1298 ),
1299 ])
1300 .vertical(),
1301 ])
1302 .into_any_element(),
1303 )
1304 }
1305 }
1306}
1307
1308fn merge_anchor_ranges<'a>(
1309 left: impl 'a + Iterator<Item = Range<Anchor>>,
1310 right: impl 'a + Iterator<Item = Range<Anchor>>,
1311 snapshot: &'a language::BufferSnapshot,
1312) -> impl 'a + Iterator<Item = Range<Anchor>> {
1313 let mut left = left.fuse().peekable();
1314 let mut right = right.fuse().peekable();
1315
1316 std::iter::from_fn(move || {
1317 let Some(left_range) = left.peek() else {
1318 return right.next();
1319 };
1320 let Some(right_range) = right.peek() else {
1321 return left.next();
1322 };
1323
1324 let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1325 left.next().unwrap()
1326 } else {
1327 right.next().unwrap()
1328 };
1329
1330 // Extend the basic range while there's overlap with a range from either stream.
1331 loop {
1332 if let Some(left_range) = left
1333 .peek()
1334 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1335 .cloned()
1336 {
1337 left.next();
1338 next_range.end = left_range.end;
1339 } else if let Some(right_range) = right
1340 .peek()
1341 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1342 .cloned()
1343 {
1344 right.next();
1345 next_range.end = right_range.end;
1346 } else {
1347 break;
1348 }
1349 }
1350
1351 Some(next_range)
1352 })
1353}
1354
1355#[cfg(test)]
1356mod tests {
1357 use db::indoc;
1358 use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1359 use git::status::{UnmergedStatus, UnmergedStatusCode};
1360 use gpui::TestAppContext;
1361 use project::FakeFs;
1362 use serde_json::json;
1363 use settings::SettingsStore;
1364 use std::path::Path;
1365 use unindent::Unindent as _;
1366 use util::{path, rel_path::rel_path};
1367
1368 use super::*;
1369
1370 #[ctor::ctor]
1371 fn init_logger() {
1372 zlog::init_test();
1373 }
1374
1375 fn init_test(cx: &mut TestAppContext) {
1376 cx.update(|cx| {
1377 let store = SettingsStore::test(cx);
1378 cx.set_global(store);
1379 theme::init(theme::LoadThemes::JustBase, cx);
1380 language::init(cx);
1381 Project::init_settings(cx);
1382 workspace::init_settings(cx);
1383 editor::init(cx);
1384 crate::init(cx);
1385 });
1386 }
1387
1388 #[gpui::test]
1389 async fn test_save_after_restore(cx: &mut TestAppContext) {
1390 init_test(cx);
1391
1392 let fs = FakeFs::new(cx.executor());
1393 fs.insert_tree(
1394 path!("/project"),
1395 json!({
1396 ".git": {},
1397 "foo.txt": "FOO\n",
1398 }),
1399 )
1400 .await;
1401 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1402 let (workspace, cx) =
1403 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1404 let diff = cx.new_window_entity(|window, cx| {
1405 ProjectDiff::new(project.clone(), workspace, window, cx)
1406 });
1407 cx.run_until_parked();
1408
1409 fs.set_head_for_repo(
1410 path!("/project/.git").as_ref(),
1411 &[("foo.txt", "foo\n".into())],
1412 "deadbeef",
1413 );
1414 fs.set_index_for_repo(
1415 path!("/project/.git").as_ref(),
1416 &[("foo.txt", "foo\n".into())],
1417 );
1418 cx.run_until_parked();
1419
1420 let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1421 assert_state_with_diff(
1422 &editor,
1423 cx,
1424 &"
1425 - foo
1426 + ˇFOO
1427 "
1428 .unindent(),
1429 );
1430
1431 editor.update_in(cx, |editor, window, cx| {
1432 editor.git_restore(&Default::default(), window, cx);
1433 });
1434 cx.run_until_parked();
1435
1436 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1437
1438 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1439 assert_eq!(text, "foo\n");
1440 }
1441
1442 #[gpui::test]
1443 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1444 init_test(cx);
1445
1446 let fs = FakeFs::new(cx.executor());
1447 fs.insert_tree(
1448 path!("/project"),
1449 json!({
1450 ".git": {},
1451 "bar": "BAR\n",
1452 "foo": "FOO\n",
1453 }),
1454 )
1455 .await;
1456 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1457 let (workspace, cx) =
1458 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1459 let diff = cx.new_window_entity(|window, cx| {
1460 ProjectDiff::new(project.clone(), workspace, window, cx)
1461 });
1462 cx.run_until_parked();
1463
1464 fs.set_head_and_index_for_repo(
1465 path!("/project/.git").as_ref(),
1466 &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1467 );
1468 cx.run_until_parked();
1469
1470 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1471 diff.move_to_path(
1472 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("foo").into_arc()),
1473 window,
1474 cx,
1475 );
1476 diff.editor.clone()
1477 });
1478 assert_state_with_diff(
1479 &editor,
1480 cx,
1481 &"
1482 - bar
1483 + BAR
1484
1485 - ˇfoo
1486 + FOO
1487 "
1488 .unindent(),
1489 );
1490
1491 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1492 diff.move_to_path(
1493 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("bar").into_arc()),
1494 window,
1495 cx,
1496 );
1497 diff.editor.clone()
1498 });
1499 assert_state_with_diff(
1500 &editor,
1501 cx,
1502 &"
1503 - ˇbar
1504 + BAR
1505
1506 - foo
1507 + FOO
1508 "
1509 .unindent(),
1510 );
1511 }
1512
1513 #[gpui::test]
1514 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1515 init_test(cx);
1516
1517 let fs = FakeFs::new(cx.executor());
1518 fs.insert_tree(
1519 path!("/project"),
1520 json!({
1521 ".git": {},
1522 "foo": "modified\n",
1523 }),
1524 )
1525 .await;
1526 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1527 let (workspace, cx) =
1528 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1529 let buffer = project
1530 .update(cx, |project, cx| {
1531 project.open_local_buffer(path!("/project/foo"), cx)
1532 })
1533 .await
1534 .unwrap();
1535 let buffer_editor = cx.new_window_entity(|window, cx| {
1536 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1537 });
1538 let diff = cx.new_window_entity(|window, cx| {
1539 ProjectDiff::new(project.clone(), workspace, window, cx)
1540 });
1541 cx.run_until_parked();
1542
1543 fs.set_head_for_repo(
1544 path!("/project/.git").as_ref(),
1545 &[("foo", "original\n".into())],
1546 "deadbeef",
1547 );
1548 cx.run_until_parked();
1549
1550 let diff_editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1551
1552 assert_state_with_diff(
1553 &diff_editor,
1554 cx,
1555 &"
1556 - original
1557 + ˇmodified
1558 "
1559 .unindent(),
1560 );
1561
1562 let prev_buffer_hunks =
1563 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1564 let snapshot = buffer_editor.snapshot(window, cx);
1565 let snapshot = &snapshot.buffer_snapshot();
1566 let prev_buffer_hunks = buffer_editor
1567 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1568 .collect::<Vec<_>>();
1569 buffer_editor.git_restore(&Default::default(), window, cx);
1570 prev_buffer_hunks
1571 });
1572 assert_eq!(prev_buffer_hunks.len(), 1);
1573 cx.run_until_parked();
1574
1575 let new_buffer_hunks =
1576 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1577 let snapshot = buffer_editor.snapshot(window, cx);
1578 let snapshot = &snapshot.buffer_snapshot();
1579 buffer_editor
1580 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1581 .collect::<Vec<_>>()
1582 });
1583 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1584
1585 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1586 buffer_editor.set_text("different\n", window, cx);
1587 buffer_editor.save(
1588 SaveOptions {
1589 format: false,
1590 autosave: false,
1591 },
1592 project.clone(),
1593 window,
1594 cx,
1595 )
1596 })
1597 .await
1598 .unwrap();
1599
1600 cx.run_until_parked();
1601
1602 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1603 buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1604 });
1605
1606 assert_state_with_diff(
1607 &buffer_editor,
1608 cx,
1609 &"
1610 - original
1611 + different
1612 ˇ"
1613 .unindent(),
1614 );
1615
1616 assert_state_with_diff(
1617 &diff_editor,
1618 cx,
1619 &"
1620 - original
1621 + different
1622 ˇ"
1623 .unindent(),
1624 );
1625 }
1626
1627 use crate::{
1628 conflict_view::resolve_conflict,
1629 project_diff::{self, ProjectDiff},
1630 };
1631
1632 #[gpui::test]
1633 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1634 init_test(cx);
1635
1636 let fs = FakeFs::new(cx.executor());
1637 fs.insert_tree(
1638 path!("/a"),
1639 json!({
1640 ".git": {},
1641 "a.txt": "created\n",
1642 "b.txt": "really changed\n",
1643 "c.txt": "unchanged\n"
1644 }),
1645 )
1646 .await;
1647
1648 fs.set_head_and_index_for_repo(
1649 Path::new(path!("/a/.git")),
1650 &[
1651 ("b.txt", "before\n".to_string()),
1652 ("c.txt", "unchanged\n".to_string()),
1653 ("d.txt", "deleted\n".to_string()),
1654 ],
1655 );
1656
1657 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1658 let (workspace, cx) =
1659 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1660
1661 cx.run_until_parked();
1662
1663 cx.focus(&workspace);
1664 cx.update(|window, cx| {
1665 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1666 });
1667
1668 cx.run_until_parked();
1669
1670 let item = workspace.update(cx, |workspace, cx| {
1671 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1672 });
1673 cx.focus(&item);
1674 let editor = item.read_with(cx, |item, _| item.editor.clone());
1675
1676 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1677
1678 cx.assert_excerpts_with_selections(indoc!(
1679 "
1680 [EXCERPT]
1681 before
1682 really changed
1683 [EXCERPT]
1684 [FOLDED]
1685 [EXCERPT]
1686 ˇcreated
1687 "
1688 ));
1689
1690 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1691
1692 cx.assert_excerpts_with_selections(indoc!(
1693 "
1694 [EXCERPT]
1695 before
1696 really changed
1697 [EXCERPT]
1698 ˇ[FOLDED]
1699 [EXCERPT]
1700 created
1701 "
1702 ));
1703
1704 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1705
1706 cx.assert_excerpts_with_selections(indoc!(
1707 "
1708 [EXCERPT]
1709 ˇbefore
1710 really changed
1711 [EXCERPT]
1712 [FOLDED]
1713 [EXCERPT]
1714 created
1715 "
1716 ));
1717 }
1718
1719 #[gpui::test]
1720 async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
1721 init_test(cx);
1722
1723 let git_contents = indoc! {r#"
1724 #[rustfmt::skip]
1725 fn main() {
1726 let x = 0.0; // this line will be removed
1727 // 1
1728 // 2
1729 // 3
1730 let y = 0.0; // this line will be removed
1731 // 1
1732 // 2
1733 // 3
1734 let arr = [
1735 0.0, // this line will be removed
1736 0.0, // this line will be removed
1737 0.0, // this line will be removed
1738 0.0, // this line will be removed
1739 ];
1740 }
1741 "#};
1742 let buffer_contents = indoc! {"
1743 #[rustfmt::skip]
1744 fn main() {
1745 // 1
1746 // 2
1747 // 3
1748 // 1
1749 // 2
1750 // 3
1751 let arr = [
1752 ];
1753 }
1754 "};
1755
1756 let fs = FakeFs::new(cx.executor());
1757 fs.insert_tree(
1758 path!("/a"),
1759 json!({
1760 ".git": {},
1761 "main.rs": buffer_contents,
1762 }),
1763 )
1764 .await;
1765
1766 fs.set_head_and_index_for_repo(
1767 Path::new(path!("/a/.git")),
1768 &[("main.rs", git_contents.to_owned())],
1769 );
1770
1771 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1772 let (workspace, cx) =
1773 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1774
1775 cx.run_until_parked();
1776
1777 cx.focus(&workspace);
1778 cx.update(|window, cx| {
1779 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1780 });
1781
1782 cx.run_until_parked();
1783
1784 let item = workspace.update(cx, |workspace, cx| {
1785 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1786 });
1787 cx.focus(&item);
1788 let editor = item.read_with(cx, |item, _| item.editor.clone());
1789
1790 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1791
1792 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1793
1794 cx.dispatch_action(editor::actions::GoToHunk);
1795 cx.dispatch_action(editor::actions::GoToHunk);
1796 cx.dispatch_action(git::Restore);
1797 cx.dispatch_action(editor::actions::MoveToBeginning);
1798
1799 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
1800 }
1801
1802 #[gpui::test]
1803 async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
1804 init_test(cx);
1805
1806 let fs = FakeFs::new(cx.executor());
1807 fs.insert_tree(
1808 path!("/project"),
1809 json!({
1810 ".git": {},
1811 "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
1812 }),
1813 )
1814 .await;
1815 fs.set_status_for_repo(
1816 Path::new(path!("/project/.git")),
1817 &[(
1818 "foo",
1819 UnmergedStatus {
1820 first_head: UnmergedStatusCode::Updated,
1821 second_head: UnmergedStatusCode::Updated,
1822 }
1823 .into(),
1824 )],
1825 );
1826 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1827 let (workspace, cx) =
1828 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1829 let diff = cx.new_window_entity(|window, cx| {
1830 ProjectDiff::new(project.clone(), workspace, window, cx)
1831 });
1832 cx.run_until_parked();
1833
1834 cx.update(|window, cx| {
1835 let editor = diff.read(cx).editor.clone();
1836 let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
1837 assert_eq!(excerpt_ids.len(), 1);
1838 let excerpt_id = excerpt_ids[0];
1839 let buffer = editor
1840 .read(cx)
1841 .buffer()
1842 .read(cx)
1843 .all_buffers()
1844 .into_iter()
1845 .next()
1846 .unwrap();
1847 let buffer_id = buffer.read(cx).remote_id();
1848 let conflict_set = diff
1849 .read(cx)
1850 .editor
1851 .read(cx)
1852 .addon::<ConflictAddon>()
1853 .unwrap()
1854 .conflict_set(buffer_id)
1855 .unwrap();
1856 assert!(conflict_set.read(cx).has_conflict);
1857 let snapshot = conflict_set.read(cx).snapshot();
1858 assert_eq!(snapshot.conflicts.len(), 1);
1859
1860 let ours_range = snapshot.conflicts[0].ours.clone();
1861
1862 resolve_conflict(
1863 editor.downgrade(),
1864 excerpt_id,
1865 snapshot.conflicts[0].clone(),
1866 vec![ours_range],
1867 window,
1868 cx,
1869 )
1870 })
1871 .await;
1872
1873 let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
1874 let contents = String::from_utf8(contents).unwrap();
1875 assert_eq!(contents, "ours\n");
1876 }
1877
1878 #[gpui::test]
1879 async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
1880 init_test(cx);
1881
1882 let fs = FakeFs::new(cx.executor());
1883 fs.insert_tree(
1884 path!("/project"),
1885 json!({
1886 ".git": {},
1887 "foo.txt": "
1888 one
1889 two
1890 three
1891 four
1892 five
1893 six
1894 seven
1895 eight
1896 nine
1897 ten
1898 ELEVEN
1899 twelve
1900 ".unindent()
1901 }),
1902 )
1903 .await;
1904 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1905 let (workspace, cx) =
1906 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1907 let diff = cx.new_window_entity(|window, cx| {
1908 ProjectDiff::new(project.clone(), workspace, window, cx)
1909 });
1910 cx.run_until_parked();
1911
1912 fs.set_head_and_index_for_repo(
1913 Path::new(path!("/project/.git")),
1914 &[(
1915 "foo.txt",
1916 "
1917 one
1918 two
1919 three
1920 four
1921 five
1922 six
1923 seven
1924 eight
1925 nine
1926 ten
1927 eleven
1928 twelve
1929 "
1930 .unindent(),
1931 )],
1932 );
1933 cx.run_until_parked();
1934
1935 let editor = diff.read_with(cx, |diff, _| diff.editor.clone());
1936
1937 assert_state_with_diff(
1938 &editor,
1939 cx,
1940 &"
1941 ˇnine
1942 ten
1943 - eleven
1944 + ELEVEN
1945 twelve
1946 "
1947 .unindent(),
1948 );
1949
1950 let buffer = project
1951 .update(cx, |project, cx| {
1952 project.open_local_buffer(path!("/project/foo.txt"), cx)
1953 })
1954 .await
1955 .unwrap();
1956 buffer.update(cx, |buffer, cx| {
1957 buffer.edit_via_marked_text(
1958 &"
1959 one
1960 «TWO»
1961 three
1962 four
1963 five
1964 six
1965 seven
1966 eight
1967 nine
1968 ten
1969 ELEVEN
1970 twelve
1971 "
1972 .unindent(),
1973 None,
1974 cx,
1975 );
1976 });
1977 project
1978 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
1979 .await
1980 .unwrap();
1981 cx.run_until_parked();
1982
1983 assert_state_with_diff(
1984 &editor,
1985 cx,
1986 &"
1987 one
1988 - two
1989 + TWO
1990 three
1991 four
1992 five
1993 ˇnine
1994 ten
1995 - eleven
1996 + ELEVEN
1997 twelve
1998 "
1999 .unindent(),
2000 );
2001 }
2002}