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