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