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());
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 // Tree view can only sort by path
720 if settings.sort_by_path || settings.tree_view {
721 TRACKED_SORT_PREFIX
722 } else if repo.had_conflict_on_last_merge_head_change(repo_path) {
723 CONFLICT_SORT_PREFIX
724 } else if status.is_created() {
725 NEW_SORT_PREFIX
726 } else {
727 TRACKED_SORT_PREFIX
728 }
729}
730
731impl EventEmitter<EditorEvent> for ProjectDiff {}
732
733impl Focusable for ProjectDiff {
734 fn focus_handle(&self, cx: &App) -> FocusHandle {
735 if self.multibuffer.read(cx).is_empty() {
736 self.focus_handle.clone()
737 } else {
738 self.editor.focus_handle(cx)
739 }
740 }
741}
742
743impl Item for ProjectDiff {
744 type Event = EditorEvent;
745
746 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
747 Some(Icon::new(IconName::GitBranch).color(Color::Muted))
748 }
749
750 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
751 Editor::to_item_events(event, f)
752 }
753
754 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
755 self.editor.update(cx, |editor, cx| {
756 editor.primary_editor().update(cx, |primary_editor, cx| {
757 primary_editor.deactivated(window, cx);
758 })
759 });
760 }
761
762 fn navigate(
763 &mut self,
764 data: Box<dyn Any>,
765 window: &mut Window,
766 cx: &mut Context<Self>,
767 ) -> bool {
768 self.editor.update(cx, |editor, cx| {
769 editor.primary_editor().update(cx, |primary_editor, cx| {
770 primary_editor.navigate(data, window, cx)
771 })
772 })
773 }
774
775 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
776 Some("Project Diff".into())
777 }
778
779 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
780 Label::new(self.tab_content_text(0, cx))
781 .color(if params.selected {
782 Color::Default
783 } else {
784 Color::Muted
785 })
786 .into_any_element()
787 }
788
789 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
790 match self.branch_diff.read(cx).diff_base() {
791 DiffBase::Head => "Uncommitted Changes".into(),
792 DiffBase::Merge { base_ref } => format!("Changes since {}", base_ref).into(),
793 }
794 }
795
796 fn telemetry_event_text(&self) -> Option<&'static str> {
797 Some("Project Diff Opened")
798 }
799
800 fn as_searchable(&self, _: &Entity<Self>, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
801 // TODO(split-diff) SplitEditor should be searchable
802 Some(Box::new(self.editor.read(cx).primary_editor().clone()))
803 }
804
805 fn for_each_project_item(
806 &self,
807 cx: &App,
808 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
809 ) {
810 self.editor
811 .read(cx)
812 .primary_editor()
813 .read(cx)
814 .for_each_project_item(cx, f)
815 }
816
817 fn set_nav_history(
818 &mut self,
819 nav_history: ItemNavHistory,
820 _: &mut Window,
821 cx: &mut Context<Self>,
822 ) {
823 self.editor.update(cx, |editor, cx| {
824 editor.primary_editor().update(cx, |primary_editor, _| {
825 primary_editor.set_nav_history(Some(nav_history));
826 })
827 });
828 }
829
830 fn can_split(&self) -> bool {
831 true
832 }
833
834 fn clone_on_split(
835 &self,
836 _workspace_id: Option<workspace::WorkspaceId>,
837 window: &mut Window,
838 cx: &mut Context<Self>,
839 ) -> Task<Option<Entity<Self>>>
840 where
841 Self: Sized,
842 {
843 let Some(workspace) = self.workspace.upgrade() else {
844 return Task::ready(None);
845 };
846 Task::ready(Some(cx.new(|cx| {
847 ProjectDiff::new(self.project.clone(), workspace, window, cx)
848 })))
849 }
850
851 fn is_dirty(&self, cx: &App) -> bool {
852 self.multibuffer.read(cx).is_dirty(cx)
853 }
854
855 fn has_conflict(&self, cx: &App) -> bool {
856 self.multibuffer.read(cx).has_conflict(cx)
857 }
858
859 fn can_save(&self, _: &App) -> bool {
860 true
861 }
862
863 fn save(
864 &mut self,
865 options: SaveOptions,
866 project: Entity<Project>,
867 window: &mut Window,
868 cx: &mut Context<Self>,
869 ) -> Task<Result<()>> {
870 self.editor.update(cx, |editor, cx| {
871 editor.primary_editor().update(cx, |primary_editor, cx| {
872 primary_editor.save(options, project, window, cx)
873 })
874 })
875 }
876
877 fn save_as(
878 &mut self,
879 _: Entity<Project>,
880 _: ProjectPath,
881 _window: &mut Window,
882 _: &mut Context<Self>,
883 ) -> Task<Result<()>> {
884 unreachable!()
885 }
886
887 fn reload(
888 &mut self,
889 project: Entity<Project>,
890 window: &mut Window,
891 cx: &mut Context<Self>,
892 ) -> Task<Result<()>> {
893 self.editor.update(cx, |editor, cx| {
894 editor.primary_editor().update(cx, |primary_editor, cx| {
895 primary_editor.reload(project, window, cx)
896 })
897 })
898 }
899
900 fn act_as_type<'a>(
901 &'a self,
902 type_id: TypeId,
903 self_handle: &'a Entity<Self>,
904 cx: &'a App,
905 ) -> Option<gpui::AnyEntity> {
906 if type_id == TypeId::of::<Self>() {
907 Some(self_handle.clone().into())
908 } else if type_id == TypeId::of::<Editor>() {
909 Some(self.editor.read(cx).primary_editor().clone().into())
910 } else {
911 None
912 }
913 }
914
915 fn added_to_workspace(
916 &mut self,
917 workspace: &mut Workspace,
918 window: &mut Window,
919 cx: &mut Context<Self>,
920 ) {
921 self.editor.update(cx, |editor, cx| {
922 editor.added_to_workspace(workspace, window, cx)
923 });
924 }
925}
926
927impl Render for ProjectDiff {
928 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
929 let is_empty = self.multibuffer.read(cx).is_empty();
930
931 div()
932 .track_focus(&self.focus_handle)
933 .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
934 .bg(cx.theme().colors().editor_background)
935 .flex()
936 .items_center()
937 .justify_center()
938 .size_full()
939 .when(is_empty, |el| {
940 let remote_button = if let Some(panel) = self
941 .workspace
942 .upgrade()
943 .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
944 {
945 panel.update(cx, |panel, cx| panel.render_remote_button(cx))
946 } else {
947 None
948 };
949 let keybinding_focus_handle = self.focus_handle(cx);
950 el.child(
951 v_flex()
952 .gap_1()
953 .child(
954 h_flex()
955 .justify_around()
956 .child(Label::new("No uncommitted changes")),
957 )
958 .map(|el| match remote_button {
959 Some(button) => el.child(h_flex().justify_around().child(button)),
960 None => el.child(
961 h_flex()
962 .justify_around()
963 .child(Label::new("Remote up to date")),
964 ),
965 })
966 .child(
967 h_flex().justify_around().mt_1().child(
968 Button::new("project-diff-close-button", "Close")
969 // .style(ButtonStyle::Transparent)
970 .key_binding(KeyBinding::for_action_in(
971 &CloseActiveItem::default(),
972 &keybinding_focus_handle,
973 cx,
974 ))
975 .on_click(move |_, window, cx| {
976 window.focus(&keybinding_focus_handle, cx);
977 window.dispatch_action(
978 Box::new(CloseActiveItem::default()),
979 cx,
980 );
981 }),
982 ),
983 ),
984 )
985 })
986 .when(!is_empty, |el| el.child(self.editor.clone()))
987 }
988}
989
990impl SerializableItem for ProjectDiff {
991 fn serialized_item_kind() -> &'static str {
992 "ProjectDiff"
993 }
994
995 fn cleanup(
996 _: workspace::WorkspaceId,
997 _: Vec<workspace::ItemId>,
998 _: &mut Window,
999 _: &mut App,
1000 ) -> Task<Result<()>> {
1001 Task::ready(Ok(()))
1002 }
1003
1004 fn deserialize(
1005 project: Entity<Project>,
1006 workspace: WeakEntity<Workspace>,
1007 workspace_id: workspace::WorkspaceId,
1008 item_id: workspace::ItemId,
1009 window: &mut Window,
1010 cx: &mut App,
1011 ) -> Task<Result<Entity<Self>>> {
1012 window.spawn(cx, async move |cx| {
1013 let diff_base = persistence::PROJECT_DIFF_DB.get_diff_base(item_id, workspace_id)?;
1014
1015 let diff = cx.update(|window, cx| {
1016 let branch_diff = cx
1017 .new(|cx| branch_diff::BranchDiff::new(diff_base, project.clone(), window, cx));
1018 let workspace = workspace.upgrade().context("workspace gone")?;
1019 anyhow::Ok(
1020 cx.new(|cx| ProjectDiff::new_impl(branch_diff, project, workspace, window, cx)),
1021 )
1022 })??;
1023
1024 Ok(diff)
1025 })
1026 }
1027
1028 fn serialize(
1029 &mut self,
1030 workspace: &mut Workspace,
1031 item_id: workspace::ItemId,
1032 _closing: bool,
1033 _window: &mut Window,
1034 cx: &mut Context<Self>,
1035 ) -> Option<Task<Result<()>>> {
1036 let workspace_id = workspace.database_id()?;
1037 let diff_base = self.diff_base(cx).clone();
1038
1039 Some(cx.background_spawn({
1040 async move {
1041 persistence::PROJECT_DIFF_DB
1042 .save_diff_base(item_id, workspace_id, diff_base.clone())
1043 .await
1044 }
1045 }))
1046 }
1047
1048 fn should_serialize(&self, _: &Self::Event) -> bool {
1049 false
1050 }
1051}
1052
1053mod persistence {
1054
1055 use anyhow::Context as _;
1056 use db::{
1057 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
1058 sqlez_macros::sql,
1059 };
1060 use project::git_store::branch_diff::DiffBase;
1061 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
1062
1063 pub struct ProjectDiffDb(ThreadSafeConnection);
1064
1065 impl Domain for ProjectDiffDb {
1066 const NAME: &str = stringify!(ProjectDiffDb);
1067
1068 const MIGRATIONS: &[&str] = &[sql!(
1069 CREATE TABLE project_diffs(
1070 workspace_id INTEGER,
1071 item_id INTEGER UNIQUE,
1072
1073 diff_base TEXT,
1074
1075 PRIMARY KEY(workspace_id, item_id),
1076 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
1077 ON DELETE CASCADE
1078 ) STRICT;
1079 )];
1080 }
1081
1082 db::static_connection!(PROJECT_DIFF_DB, ProjectDiffDb, [WorkspaceDb]);
1083
1084 impl ProjectDiffDb {
1085 pub async fn save_diff_base(
1086 &self,
1087 item_id: ItemId,
1088 workspace_id: WorkspaceId,
1089 diff_base: DiffBase,
1090 ) -> anyhow::Result<()> {
1091 self.write(move |connection| {
1092 let sql_stmt = sql!(
1093 INSERT OR REPLACE INTO project_diffs(item_id, workspace_id, diff_base) VALUES (?, ?, ?)
1094 );
1095 let diff_base_str = serde_json::to_string(&diff_base)?;
1096 let mut query = connection.exec_bound::<(ItemId, WorkspaceId, String)>(sql_stmt)?;
1097 query((item_id, workspace_id, diff_base_str)).context(format!(
1098 "exec_bound failed to execute or parse for: {}",
1099 sql_stmt
1100 ))
1101 })
1102 .await
1103 }
1104
1105 pub fn get_diff_base(
1106 &self,
1107 item_id: ItemId,
1108 workspace_id: WorkspaceId,
1109 ) -> anyhow::Result<DiffBase> {
1110 let sql_stmt =
1111 sql!(SELECT diff_base FROM project_diffs WHERE item_id = ?AND workspace_id = ?);
1112 let diff_base_str = self.select_row_bound::<(ItemId, WorkspaceId), String>(sql_stmt)?(
1113 (item_id, workspace_id),
1114 )
1115 .context(::std::format!(
1116 "Error in get_diff_base, select_row_bound failed to execute or parse for: {}",
1117 sql_stmt
1118 ))?;
1119 let Some(diff_base_str) = diff_base_str else {
1120 return Ok(DiffBase::Head);
1121 };
1122 serde_json::from_str(&diff_base_str).context("deserializing diff base")
1123 }
1124 }
1125}
1126
1127pub struct ProjectDiffToolbar {
1128 project_diff: Option<WeakEntity<ProjectDiff>>,
1129 workspace: WeakEntity<Workspace>,
1130}
1131
1132impl ProjectDiffToolbar {
1133 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
1134 Self {
1135 project_diff: None,
1136 workspace: workspace.weak_handle(),
1137 }
1138 }
1139
1140 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
1141 self.project_diff.as_ref()?.upgrade()
1142 }
1143
1144 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
1145 if let Some(project_diff) = self.project_diff(cx) {
1146 project_diff.focus_handle(cx).focus(window, cx);
1147 }
1148 let action = action.boxed_clone();
1149 cx.defer(move |cx| {
1150 cx.dispatch_action(action.as_ref());
1151 })
1152 }
1153
1154 fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1155 self.workspace
1156 .update(cx, |workspace, cx| {
1157 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
1158 panel.update(cx, |panel, cx| {
1159 panel.stage_all(&Default::default(), window, cx);
1160 });
1161 }
1162 })
1163 .ok();
1164 }
1165
1166 fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1167 self.workspace
1168 .update(cx, |workspace, cx| {
1169 let Some(panel) = workspace.panel::<GitPanel>(cx) else {
1170 return;
1171 };
1172 panel.update(cx, |panel, cx| {
1173 panel.unstage_all(&Default::default(), window, cx);
1174 });
1175 })
1176 .ok();
1177 }
1178}
1179
1180impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
1181
1182impl ToolbarItemView for ProjectDiffToolbar {
1183 fn set_active_pane_item(
1184 &mut self,
1185 active_pane_item: Option<&dyn ItemHandle>,
1186 _: &mut Window,
1187 cx: &mut Context<Self>,
1188 ) -> ToolbarItemLocation {
1189 self.project_diff = active_pane_item
1190 .and_then(|item| item.act_as::<ProjectDiff>(cx))
1191 .filter(|item| item.read(cx).diff_base(cx) == &DiffBase::Head)
1192 .map(|entity| entity.downgrade());
1193 if self.project_diff.is_some() {
1194 ToolbarItemLocation::PrimaryRight
1195 } else {
1196 ToolbarItemLocation::Hidden
1197 }
1198 }
1199
1200 fn pane_focus_update(
1201 &mut self,
1202 _pane_focused: bool,
1203 _window: &mut Window,
1204 _cx: &mut Context<Self>,
1205 ) {
1206 }
1207}
1208
1209struct ButtonStates {
1210 stage: bool,
1211 unstage: bool,
1212 prev_next: bool,
1213 selection: bool,
1214 stage_all: bool,
1215 unstage_all: bool,
1216}
1217
1218impl Render for ProjectDiffToolbar {
1219 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1220 let Some(project_diff) = self.project_diff(cx) else {
1221 return div();
1222 };
1223 let focus_handle = project_diff.focus_handle(cx);
1224 let button_states = project_diff.read(cx).button_states(cx);
1225
1226 h_group_xl()
1227 .my_neg_1()
1228 .py_1()
1229 .items_center()
1230 .flex_wrap()
1231 .justify_between()
1232 .child(
1233 h_group_sm()
1234 .when(button_states.selection, |el| {
1235 el.child(
1236 Button::new("stage", "Toggle Staged")
1237 .tooltip(Tooltip::for_action_title_in(
1238 "Toggle Staged",
1239 &ToggleStaged,
1240 &focus_handle,
1241 ))
1242 .disabled(!button_states.stage && !button_states.unstage)
1243 .on_click(cx.listener(|this, _, window, cx| {
1244 this.dispatch_action(&ToggleStaged, window, cx)
1245 })),
1246 )
1247 })
1248 .when(!button_states.selection, |el| {
1249 el.child(
1250 Button::new("stage", "Stage")
1251 .tooltip(Tooltip::for_action_title_in(
1252 "Stage and go to next hunk",
1253 &StageAndNext,
1254 &focus_handle,
1255 ))
1256 .disabled(
1257 !button_states.prev_next
1258 && !button_states.stage_all
1259 && !button_states.unstage_all,
1260 )
1261 .on_click(cx.listener(|this, _, window, cx| {
1262 this.dispatch_action(&StageAndNext, window, cx)
1263 })),
1264 )
1265 .child(
1266 Button::new("unstage", "Unstage")
1267 .tooltip(Tooltip::for_action_title_in(
1268 "Unstage and go to next hunk",
1269 &UnstageAndNext,
1270 &focus_handle,
1271 ))
1272 .disabled(
1273 !button_states.prev_next
1274 && !button_states.stage_all
1275 && !button_states.unstage_all,
1276 )
1277 .on_click(cx.listener(|this, _, window, cx| {
1278 this.dispatch_action(&UnstageAndNext, window, cx)
1279 })),
1280 )
1281 }),
1282 )
1283 // n.b. the only reason these arrows are here is because we don't
1284 // support "undo" for staging so we need a way to go back.
1285 .child(
1286 h_group_sm()
1287 .child(
1288 IconButton::new("up", IconName::ArrowUp)
1289 .shape(ui::IconButtonShape::Square)
1290 .tooltip(Tooltip::for_action_title_in(
1291 "Go to previous hunk",
1292 &GoToPreviousHunk,
1293 &focus_handle,
1294 ))
1295 .disabled(!button_states.prev_next)
1296 .on_click(cx.listener(|this, _, window, cx| {
1297 this.dispatch_action(&GoToPreviousHunk, window, cx)
1298 })),
1299 )
1300 .child(
1301 IconButton::new("down", IconName::ArrowDown)
1302 .shape(ui::IconButtonShape::Square)
1303 .tooltip(Tooltip::for_action_title_in(
1304 "Go to next hunk",
1305 &GoToHunk,
1306 &focus_handle,
1307 ))
1308 .disabled(!button_states.prev_next)
1309 .on_click(cx.listener(|this, _, window, cx| {
1310 this.dispatch_action(&GoToHunk, window, cx)
1311 })),
1312 ),
1313 )
1314 .child(vertical_divider())
1315 .child(
1316 h_group_sm()
1317 .when(
1318 button_states.unstage_all && !button_states.stage_all,
1319 |el| {
1320 el.child(
1321 Button::new("unstage-all", "Unstage All")
1322 .tooltip(Tooltip::for_action_title_in(
1323 "Unstage all changes",
1324 &UnstageAll,
1325 &focus_handle,
1326 ))
1327 .on_click(cx.listener(|this, _, window, cx| {
1328 this.unstage_all(window, cx)
1329 })),
1330 )
1331 },
1332 )
1333 .when(
1334 !button_states.unstage_all || button_states.stage_all,
1335 |el| {
1336 el.child(
1337 // todo make it so that changing to say "Unstaged"
1338 // doesn't change the position.
1339 div().child(
1340 Button::new("stage-all", "Stage All")
1341 .disabled(!button_states.stage_all)
1342 .tooltip(Tooltip::for_action_title_in(
1343 "Stage all changes",
1344 &StageAll,
1345 &focus_handle,
1346 ))
1347 .on_click(cx.listener(|this, _, window, cx| {
1348 this.stage_all(window, cx)
1349 })),
1350 ),
1351 )
1352 },
1353 )
1354 .child(
1355 Button::new("commit", "Commit")
1356 .tooltip(Tooltip::for_action_title_in(
1357 "Commit",
1358 &Commit,
1359 &focus_handle,
1360 ))
1361 .on_click(cx.listener(|this, _, window, cx| {
1362 this.dispatch_action(&Commit, window, cx);
1363 })),
1364 ),
1365 )
1366 }
1367}
1368
1369#[derive(IntoElement, RegisterComponent)]
1370pub struct ProjectDiffEmptyState {
1371 pub no_repo: bool,
1372 pub can_push_and_pull: bool,
1373 pub focus_handle: Option<FocusHandle>,
1374 pub current_branch: Option<Branch>,
1375 // has_pending_commits: bool,
1376 // ahead_of_remote: bool,
1377 // no_git_repository: bool,
1378}
1379
1380impl RenderOnce for ProjectDiffEmptyState {
1381 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1382 let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1383 matches!(self.current_branch, Some(Branch {
1384 upstream:
1385 Some(Upstream {
1386 tracking:
1387 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1388 ahead, behind, ..
1389 }),
1390 ..
1391 }),
1392 ..
1393 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1394 };
1395
1396 let change_count = |current_branch: &Branch| -> (usize, usize) {
1397 match current_branch {
1398 Branch {
1399 upstream:
1400 Some(Upstream {
1401 tracking:
1402 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1403 ahead, behind, ..
1404 }),
1405 ..
1406 }),
1407 ..
1408 } => (*ahead as usize, *behind as usize),
1409 _ => (0, 0),
1410 }
1411 };
1412
1413 let not_ahead_or_behind = status_against_remote(0, 0);
1414 let ahead_of_remote = status_against_remote(1, 0);
1415 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1416 branch.upstream.is_none()
1417 } else {
1418 false
1419 };
1420
1421 let has_branch_container = |branch: &Branch| {
1422 h_flex()
1423 .max_w(px(420.))
1424 .bg(cx.theme().colors().text.opacity(0.05))
1425 .border_1()
1426 .border_color(cx.theme().colors().border)
1427 .rounded_sm()
1428 .gap_8()
1429 .px_6()
1430 .py_4()
1431 .map(|this| {
1432 if ahead_of_remote {
1433 let ahead_count = change_count(branch).0;
1434 let ahead_string = format!("{} Commits Ahead", ahead_count);
1435 this.child(
1436 v_flex()
1437 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1438 .child(
1439 Label::new(format!("Push your changes to {}", branch.name()))
1440 .color(Color::Muted),
1441 ),
1442 )
1443 .child(div().child(render_push_button(
1444 self.focus_handle,
1445 "push".into(),
1446 ahead_count as u32,
1447 )))
1448 } else if branch_not_on_remote {
1449 this.child(
1450 v_flex()
1451 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1452 .child(
1453 Label::new(format!("Create {} on remote", branch.name()))
1454 .color(Color::Muted),
1455 ),
1456 )
1457 .child(
1458 div().child(render_publish_button(self.focus_handle, "publish".into())),
1459 )
1460 } else {
1461 this.child(Label::new("Remote status unknown").color(Color::Muted))
1462 }
1463 })
1464 };
1465
1466 v_flex().size_full().items_center().justify_center().child(
1467 v_flex()
1468 .gap_1()
1469 .when(self.no_repo, |this| {
1470 // TODO: add git init
1471 this.text_center()
1472 .child(Label::new("No Repository").color(Color::Muted))
1473 })
1474 .map(|this| {
1475 if not_ahead_or_behind && self.current_branch.is_some() {
1476 this.text_center()
1477 .child(Label::new("No Changes").color(Color::Muted))
1478 } else {
1479 this.when_some(self.current_branch.as_ref(), |this, branch| {
1480 this.child(has_branch_container(branch))
1481 })
1482 }
1483 }),
1484 )
1485 }
1486}
1487
1488mod preview {
1489 use git::repository::{
1490 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1491 };
1492 use ui::prelude::*;
1493
1494 use super::ProjectDiffEmptyState;
1495
1496 // View this component preview using `workspace: open component-preview`
1497 impl Component for ProjectDiffEmptyState {
1498 fn scope() -> ComponentScope {
1499 ComponentScope::VersionControl
1500 }
1501
1502 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1503 let unknown_upstream: Option<UpstreamTracking> = None;
1504 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1505 UpstreamTrackingStatus {
1506 ahead: 2,
1507 behind: 0,
1508 }
1509 .into(),
1510 );
1511
1512 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1513 UpstreamTrackingStatus {
1514 ahead: 0,
1515 behind: 0,
1516 }
1517 .into(),
1518 );
1519
1520 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1521 Branch {
1522 is_head: true,
1523 ref_name: "some-branch".into(),
1524 upstream: upstream.map(|tracking| Upstream {
1525 ref_name: "origin/some-branch".into(),
1526 tracking,
1527 }),
1528 most_recent_commit: Some(CommitSummary {
1529 sha: "abc123".into(),
1530 subject: "Modify stuff".into(),
1531 commit_timestamp: 1710932954,
1532 author_name: "John Doe".into(),
1533 has_parent: true,
1534 }),
1535 }
1536 }
1537
1538 let no_repo_state = ProjectDiffEmptyState {
1539 no_repo: true,
1540 can_push_and_pull: false,
1541 focus_handle: None,
1542 current_branch: None,
1543 };
1544
1545 let no_changes_state = ProjectDiffEmptyState {
1546 no_repo: false,
1547 can_push_and_pull: true,
1548 focus_handle: None,
1549 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1550 };
1551
1552 let ahead_of_upstream_state = ProjectDiffEmptyState {
1553 no_repo: false,
1554 can_push_and_pull: true,
1555 focus_handle: None,
1556 current_branch: Some(branch(ahead_of_upstream)),
1557 };
1558
1559 let unknown_upstream_state = ProjectDiffEmptyState {
1560 no_repo: false,
1561 can_push_and_pull: true,
1562 focus_handle: None,
1563 current_branch: Some(branch(unknown_upstream)),
1564 };
1565
1566 let (width, height) = (px(480.), px(320.));
1567
1568 Some(
1569 v_flex()
1570 .gap_6()
1571 .children(vec![
1572 example_group(vec![
1573 single_example(
1574 "No Repo",
1575 div()
1576 .w(width)
1577 .h(height)
1578 .child(no_repo_state)
1579 .into_any_element(),
1580 ),
1581 single_example(
1582 "No Changes",
1583 div()
1584 .w(width)
1585 .h(height)
1586 .child(no_changes_state)
1587 .into_any_element(),
1588 ),
1589 single_example(
1590 "Unknown Upstream",
1591 div()
1592 .w(width)
1593 .h(height)
1594 .child(unknown_upstream_state)
1595 .into_any_element(),
1596 ),
1597 single_example(
1598 "Ahead of Remote",
1599 div()
1600 .w(width)
1601 .h(height)
1602 .child(ahead_of_upstream_state)
1603 .into_any_element(),
1604 ),
1605 ])
1606 .vertical(),
1607 ])
1608 .into_any_element(),
1609 )
1610 }
1611 }
1612}
1613
1614struct BranchDiffAddon {
1615 branch_diff: Entity<branch_diff::BranchDiff>,
1616}
1617
1618impl Addon for BranchDiffAddon {
1619 fn to_any(&self) -> &dyn std::any::Any {
1620 self
1621 }
1622
1623 fn override_status_for_buffer_id(
1624 &self,
1625 buffer_id: language::BufferId,
1626 cx: &App,
1627 ) -> Option<FileStatus> {
1628 self.branch_diff
1629 .read(cx)
1630 .status_for_buffer_id(buffer_id, cx)
1631 }
1632}
1633
1634#[cfg(test)]
1635mod tests {
1636 use collections::HashMap;
1637 use db::indoc;
1638 use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1639 use git::status::{TrackedStatus, UnmergedStatus, UnmergedStatusCode};
1640 use gpui::TestAppContext;
1641 use project::FakeFs;
1642 use serde_json::json;
1643 use settings::SettingsStore;
1644 use std::path::Path;
1645 use unindent::Unindent as _;
1646 use util::{
1647 path,
1648 rel_path::{RelPath, rel_path},
1649 };
1650
1651 use super::*;
1652
1653 #[ctor::ctor]
1654 fn init_logger() {
1655 zlog::init_test();
1656 }
1657
1658 fn init_test(cx: &mut TestAppContext) {
1659 cx.update(|cx| {
1660 let store = SettingsStore::test(cx);
1661 cx.set_global(store);
1662 theme::init(theme::LoadThemes::JustBase, cx);
1663 editor::init(cx);
1664 crate::init(cx);
1665 });
1666 }
1667
1668 #[gpui::test]
1669 async fn test_save_after_restore(cx: &mut TestAppContext) {
1670 init_test(cx);
1671
1672 let fs = FakeFs::new(cx.executor());
1673 fs.insert_tree(
1674 path!("/project"),
1675 json!({
1676 ".git": {},
1677 "foo.txt": "FOO\n",
1678 }),
1679 )
1680 .await;
1681 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1682
1683 fs.set_head_for_repo(
1684 path!("/project/.git").as_ref(),
1685 &[("foo.txt", "foo\n".into())],
1686 "deadbeef",
1687 );
1688 fs.set_index_for_repo(
1689 path!("/project/.git").as_ref(),
1690 &[("foo.txt", "foo\n".into())],
1691 );
1692
1693 let (workspace, cx) =
1694 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1695 let diff = cx.new_window_entity(|window, cx| {
1696 ProjectDiff::new(project.clone(), workspace, window, cx)
1697 });
1698 cx.run_until_parked();
1699
1700 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
1701 assert_state_with_diff(
1702 &editor,
1703 cx,
1704 &"
1705 - ˇfoo
1706 + FOO
1707 "
1708 .unindent(),
1709 );
1710
1711 editor
1712 .update_in(cx, |editor, window, cx| {
1713 editor.git_restore(&Default::default(), window, cx);
1714 editor.save(SaveOptions::default(), project.clone(), window, cx)
1715 })
1716 .await
1717 .unwrap();
1718 cx.run_until_parked();
1719
1720 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1721
1722 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1723 assert_eq!(text, "foo\n");
1724 }
1725
1726 #[gpui::test]
1727 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1728 init_test(cx);
1729
1730 let fs = FakeFs::new(cx.executor());
1731 fs.insert_tree(
1732 path!("/project"),
1733 json!({
1734 ".git": {},
1735 "bar": "BAR\n",
1736 "foo": "FOO\n",
1737 }),
1738 )
1739 .await;
1740 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1741 let (workspace, cx) =
1742 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1743 let diff = cx.new_window_entity(|window, cx| {
1744 ProjectDiff::new(project.clone(), workspace, window, cx)
1745 });
1746 cx.run_until_parked();
1747
1748 fs.set_head_and_index_for_repo(
1749 path!("/project/.git").as_ref(),
1750 &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1751 );
1752 cx.run_until_parked();
1753
1754 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1755 diff.move_to_path(
1756 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("foo").into_arc()),
1757 window,
1758 cx,
1759 );
1760 diff.editor.read(cx).primary_editor().clone()
1761 });
1762 assert_state_with_diff(
1763 &editor,
1764 cx,
1765 &"
1766 - bar
1767 + BAR
1768
1769 - ˇfoo
1770 + FOO
1771 "
1772 .unindent(),
1773 );
1774
1775 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1776 diff.move_to_path(
1777 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("bar").into_arc()),
1778 window,
1779 cx,
1780 );
1781 diff.editor.read(cx).primary_editor().clone()
1782 });
1783 assert_state_with_diff(
1784 &editor,
1785 cx,
1786 &"
1787 - ˇbar
1788 + BAR
1789
1790 - foo
1791 + FOO
1792 "
1793 .unindent(),
1794 );
1795 }
1796
1797 #[gpui::test]
1798 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1799 init_test(cx);
1800
1801 let fs = FakeFs::new(cx.executor());
1802 fs.insert_tree(
1803 path!("/project"),
1804 json!({
1805 ".git": {},
1806 "foo": "modified\n",
1807 }),
1808 )
1809 .await;
1810 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1811 let (workspace, cx) =
1812 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1813 fs.set_head_for_repo(
1814 path!("/project/.git").as_ref(),
1815 &[("foo", "original\n".into())],
1816 "deadbeef",
1817 );
1818
1819 let buffer = project
1820 .update(cx, |project, cx| {
1821 project.open_local_buffer(path!("/project/foo"), cx)
1822 })
1823 .await
1824 .unwrap();
1825 let buffer_editor = cx.new_window_entity(|window, cx| {
1826 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
1827 });
1828 let diff = cx.new_window_entity(|window, cx| {
1829 ProjectDiff::new(project.clone(), workspace, window, cx)
1830 });
1831 cx.run_until_parked();
1832
1833 let diff_editor =
1834 diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
1835
1836 assert_state_with_diff(
1837 &diff_editor,
1838 cx,
1839 &"
1840 - ˇoriginal
1841 + modified
1842 "
1843 .unindent(),
1844 );
1845
1846 let prev_buffer_hunks =
1847 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1848 let snapshot = buffer_editor.snapshot(window, cx);
1849 let snapshot = &snapshot.buffer_snapshot();
1850 let prev_buffer_hunks = buffer_editor
1851 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1852 .collect::<Vec<_>>();
1853 buffer_editor.git_restore(&Default::default(), window, cx);
1854 prev_buffer_hunks
1855 });
1856 assert_eq!(prev_buffer_hunks.len(), 1);
1857 cx.run_until_parked();
1858
1859 let new_buffer_hunks =
1860 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1861 let snapshot = buffer_editor.snapshot(window, cx);
1862 let snapshot = &snapshot.buffer_snapshot();
1863 buffer_editor
1864 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
1865 .collect::<Vec<_>>()
1866 });
1867 assert_eq!(new_buffer_hunks.as_slice(), &[]);
1868
1869 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1870 buffer_editor.set_text("different\n", window, cx);
1871 buffer_editor.save(
1872 SaveOptions {
1873 format: false,
1874 autosave: false,
1875 },
1876 project.clone(),
1877 window,
1878 cx,
1879 )
1880 })
1881 .await
1882 .unwrap();
1883
1884 cx.run_until_parked();
1885
1886 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
1887 buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
1888 });
1889
1890 assert_state_with_diff(
1891 &buffer_editor,
1892 cx,
1893 &"
1894 - original
1895 + different
1896 ˇ"
1897 .unindent(),
1898 );
1899
1900 assert_state_with_diff(
1901 &diff_editor,
1902 cx,
1903 &"
1904 - ˇoriginal
1905 + different
1906 "
1907 .unindent(),
1908 );
1909 }
1910
1911 use crate::{
1912 conflict_view::resolve_conflict,
1913 project_diff::{self, ProjectDiff},
1914 };
1915
1916 #[gpui::test]
1917 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
1918 init_test(cx);
1919
1920 let fs = FakeFs::new(cx.executor());
1921 fs.insert_tree(
1922 path!("/a"),
1923 json!({
1924 ".git": {},
1925 "a.txt": "created\n",
1926 "b.txt": "really changed\n",
1927 "c.txt": "unchanged\n"
1928 }),
1929 )
1930 .await;
1931
1932 fs.set_head_and_index_for_repo(
1933 Path::new(path!("/a/.git")),
1934 &[
1935 ("b.txt", "before\n".to_string()),
1936 ("c.txt", "unchanged\n".to_string()),
1937 ("d.txt", "deleted\n".to_string()),
1938 ],
1939 );
1940
1941 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
1942 let (workspace, cx) =
1943 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1944
1945 cx.run_until_parked();
1946
1947 cx.focus(&workspace);
1948 cx.update(|window, cx| {
1949 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
1950 });
1951
1952 cx.run_until_parked();
1953
1954 let item = workspace.update(cx, |workspace, cx| {
1955 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
1956 });
1957 cx.focus(&item);
1958 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
1959
1960 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
1961
1962 cx.assert_excerpts_with_selections(indoc!(
1963 "
1964 [EXCERPT]
1965 before
1966 really changed
1967 [EXCERPT]
1968 [FOLDED]
1969 [EXCERPT]
1970 ˇcreated
1971 "
1972 ));
1973
1974 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1975
1976 cx.assert_excerpts_with_selections(indoc!(
1977 "
1978 [EXCERPT]
1979 before
1980 really changed
1981 [EXCERPT]
1982 ˇ[FOLDED]
1983 [EXCERPT]
1984 created
1985 "
1986 ));
1987
1988 cx.dispatch_action(editor::actions::GoToPreviousHunk);
1989
1990 cx.assert_excerpts_with_selections(indoc!(
1991 "
1992 [EXCERPT]
1993 ˇbefore
1994 really changed
1995 [EXCERPT]
1996 [FOLDED]
1997 [EXCERPT]
1998 created
1999 "
2000 ));
2001 }
2002
2003 #[gpui::test]
2004 async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
2005 init_test(cx);
2006
2007 let git_contents = indoc! {r#"
2008 #[rustfmt::skip]
2009 fn main() {
2010 let x = 0.0; // this line will be removed
2011 // 1
2012 // 2
2013 // 3
2014 let y = 0.0; // this line will be removed
2015 // 1
2016 // 2
2017 // 3
2018 let arr = [
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 0.0, // this line will be removed
2023 ];
2024 }
2025 "#};
2026 let buffer_contents = indoc! {"
2027 #[rustfmt::skip]
2028 fn main() {
2029 // 1
2030 // 2
2031 // 3
2032 // 1
2033 // 2
2034 // 3
2035 let arr = [
2036 ];
2037 }
2038 "};
2039
2040 let fs = FakeFs::new(cx.executor());
2041 fs.insert_tree(
2042 path!("/a"),
2043 json!({
2044 ".git": {},
2045 "main.rs": buffer_contents,
2046 }),
2047 )
2048 .await;
2049
2050 fs.set_head_and_index_for_repo(
2051 Path::new(path!("/a/.git")),
2052 &[("main.rs", git_contents.to_owned())],
2053 );
2054
2055 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2056 let (workspace, cx) =
2057 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2058
2059 cx.run_until_parked();
2060
2061 cx.focus(&workspace);
2062 cx.update(|window, cx| {
2063 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2064 });
2065
2066 cx.run_until_parked();
2067
2068 let item = workspace.update(cx, |workspace, cx| {
2069 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2070 });
2071 cx.focus(&item);
2072 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2073
2074 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2075
2076 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2077
2078 cx.dispatch_action(editor::actions::GoToHunk);
2079 cx.dispatch_action(editor::actions::GoToHunk);
2080 cx.dispatch_action(git::Restore);
2081 cx.dispatch_action(editor::actions::MoveToBeginning);
2082
2083 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2084 }
2085
2086 #[gpui::test]
2087 async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
2088 init_test(cx);
2089
2090 let fs = FakeFs::new(cx.executor());
2091 fs.insert_tree(
2092 path!("/project"),
2093 json!({
2094 ".git": {},
2095 "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
2096 }),
2097 )
2098 .await;
2099 fs.set_status_for_repo(
2100 Path::new(path!("/project/.git")),
2101 &[(
2102 "foo",
2103 UnmergedStatus {
2104 first_head: UnmergedStatusCode::Updated,
2105 second_head: UnmergedStatusCode::Updated,
2106 }
2107 .into(),
2108 )],
2109 );
2110 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2111 let (workspace, cx) =
2112 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2113 let diff = cx.new_window_entity(|window, cx| {
2114 ProjectDiff::new(project.clone(), workspace, window, cx)
2115 });
2116 cx.run_until_parked();
2117
2118 cx.update(|window, cx| {
2119 let editor = diff.read(cx).editor.read(cx).primary_editor().clone();
2120 let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
2121 assert_eq!(excerpt_ids.len(), 1);
2122 let excerpt_id = excerpt_ids[0];
2123 let buffer = editor
2124 .read(cx)
2125 .buffer()
2126 .read(cx)
2127 .all_buffers()
2128 .into_iter()
2129 .next()
2130 .unwrap();
2131 let buffer_id = buffer.read(cx).remote_id();
2132 let conflict_set = diff
2133 .read(cx)
2134 .editor
2135 .read(cx)
2136 .primary_editor()
2137 .read(cx)
2138 .addon::<ConflictAddon>()
2139 .unwrap()
2140 .conflict_set(buffer_id)
2141 .unwrap();
2142 assert!(conflict_set.read(cx).has_conflict);
2143 let snapshot = conflict_set.read(cx).snapshot();
2144 assert_eq!(snapshot.conflicts.len(), 1);
2145
2146 let ours_range = snapshot.conflicts[0].ours.clone();
2147
2148 resolve_conflict(
2149 editor.downgrade(),
2150 excerpt_id,
2151 snapshot.conflicts[0].clone(),
2152 vec![ours_range],
2153 window,
2154 cx,
2155 )
2156 })
2157 .await;
2158
2159 let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
2160 let contents = String::from_utf8(contents).unwrap();
2161 assert_eq!(contents, "ours\n");
2162 }
2163
2164 #[gpui::test]
2165 async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
2166 init_test(cx);
2167
2168 let fs = FakeFs::new(cx.executor());
2169 fs.insert_tree(
2170 path!("/project"),
2171 json!({
2172 ".git": {},
2173 "foo.txt": "
2174 one
2175 two
2176 three
2177 four
2178 five
2179 six
2180 seven
2181 eight
2182 nine
2183 ten
2184 ELEVEN
2185 twelve
2186 ".unindent()
2187 }),
2188 )
2189 .await;
2190 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2191 let (workspace, cx) =
2192 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2193 let diff = cx.new_window_entity(|window, cx| {
2194 ProjectDiff::new(project.clone(), workspace, window, cx)
2195 });
2196 cx.run_until_parked();
2197
2198 fs.set_head_and_index_for_repo(
2199 Path::new(path!("/project/.git")),
2200 &[(
2201 "foo.txt",
2202 "
2203 one
2204 two
2205 three
2206 four
2207 five
2208 six
2209 seven
2210 eight
2211 nine
2212 ten
2213 eleven
2214 twelve
2215 "
2216 .unindent(),
2217 )],
2218 );
2219 cx.run_until_parked();
2220
2221 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2222
2223 assert_state_with_diff(
2224 &editor,
2225 cx,
2226 &"
2227 ˇnine
2228 ten
2229 - eleven
2230 + ELEVEN
2231 twelve
2232 "
2233 .unindent(),
2234 );
2235
2236 // The project diff updates its excerpts when a new hunk appears in a buffer that already has a diff.
2237 let buffer = project
2238 .update(cx, |project, cx| {
2239 project.open_local_buffer(path!("/project/foo.txt"), cx)
2240 })
2241 .await
2242 .unwrap();
2243 buffer.update(cx, |buffer, cx| {
2244 buffer.edit_via_marked_text(
2245 &"
2246 one
2247 «TWO»
2248 three
2249 four
2250 five
2251 six
2252 seven
2253 eight
2254 nine
2255 ten
2256 ELEVEN
2257 twelve
2258 "
2259 .unindent(),
2260 None,
2261 cx,
2262 );
2263 });
2264 project
2265 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
2266 .await
2267 .unwrap();
2268 cx.run_until_parked();
2269
2270 assert_state_with_diff(
2271 &editor,
2272 cx,
2273 &"
2274 one
2275 - two
2276 + TWO
2277 three
2278 four
2279 five
2280 ˇnine
2281 ten
2282 - eleven
2283 + ELEVEN
2284 twelve
2285 "
2286 .unindent(),
2287 );
2288 }
2289
2290 #[gpui::test]
2291 async fn test_branch_diff(cx: &mut TestAppContext) {
2292 init_test(cx);
2293
2294 let fs = FakeFs::new(cx.executor());
2295 fs.insert_tree(
2296 path!("/project"),
2297 json!({
2298 ".git": {},
2299 "a.txt": "C",
2300 "b.txt": "new",
2301 "c.txt": "in-merge-base-and-work-tree",
2302 "d.txt": "created-in-head",
2303 }),
2304 )
2305 .await;
2306 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2307 let (workspace, cx) =
2308 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2309 let diff = cx
2310 .update(|window, cx| {
2311 ProjectDiff::new_with_default_branch(project.clone(), workspace, window, cx)
2312 })
2313 .await
2314 .unwrap();
2315 cx.run_until_parked();
2316
2317 fs.set_head_for_repo(
2318 Path::new(path!("/project/.git")),
2319 &[("a.txt", "B".into()), ("d.txt", "created-in-head".into())],
2320 "sha",
2321 );
2322 // fs.set_index_for_repo(dot_git, index_state);
2323 fs.set_merge_base_content_for_repo(
2324 Path::new(path!("/project/.git")),
2325 &[
2326 ("a.txt", "A".into()),
2327 ("c.txt", "in-merge-base-and-work-tree".into()),
2328 ],
2329 );
2330 cx.run_until_parked();
2331
2332 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2333
2334 assert_state_with_diff(
2335 &editor,
2336 cx,
2337 &"
2338 - A
2339 + ˇC
2340 + new
2341 + created-in-head"
2342 .unindent(),
2343 );
2344
2345 let statuses: HashMap<Arc<RelPath>, Option<FileStatus>> =
2346 editor.update(cx, |editor, cx| {
2347 editor
2348 .buffer()
2349 .read(cx)
2350 .all_buffers()
2351 .iter()
2352 .map(|buffer| {
2353 (
2354 buffer.read(cx).file().unwrap().path().clone(),
2355 editor.status_for_buffer_id(buffer.read(cx).remote_id(), cx),
2356 )
2357 })
2358 .collect()
2359 });
2360
2361 assert_eq!(
2362 statuses,
2363 HashMap::from_iter([
2364 (
2365 rel_path("a.txt").into_arc(),
2366 Some(FileStatus::Tracked(TrackedStatus {
2367 index_status: git::status::StatusCode::Modified,
2368 worktree_status: git::status::StatusCode::Modified
2369 }))
2370 ),
2371 (rel_path("b.txt").into_arc(), Some(FileStatus::Untracked)),
2372 (
2373 rel_path("d.txt").into_arc(),
2374 Some(FileStatus::Tracked(TrackedStatus {
2375 index_status: git::status::StatusCode::Added,
2376 worktree_status: git::status::StatusCode::Added
2377 }))
2378 )
2379 ])
2380 );
2381 }
2382
2383 #[gpui::test]
2384 async fn test_update_on_uncommit(cx: &mut TestAppContext) {
2385 init_test(cx);
2386
2387 let fs = FakeFs::new(cx.executor());
2388 fs.insert_tree(
2389 path!("/project"),
2390 json!({
2391 ".git": {},
2392 "README.md": "# My cool project\n".to_owned()
2393 }),
2394 )
2395 .await;
2396 fs.set_head_and_index_for_repo(
2397 Path::new(path!("/project/.git")),
2398 &[("README.md", "# My cool project\n".to_owned())],
2399 );
2400 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
2401 let worktree_id = project.read_with(cx, |project, cx| {
2402 project.worktrees(cx).next().unwrap().read(cx).id()
2403 });
2404 let (workspace, cx) =
2405 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2406 cx.run_until_parked();
2407
2408 let _editor = workspace
2409 .update_in(cx, |workspace, window, cx| {
2410 workspace.open_path((worktree_id, rel_path("README.md")), None, true, window, cx)
2411 })
2412 .await
2413 .unwrap()
2414 .downcast::<Editor>()
2415 .unwrap();
2416
2417 cx.focus(&workspace);
2418 cx.update(|window, cx| {
2419 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2420 });
2421 cx.run_until_parked();
2422 let item = workspace.update(cx, |workspace, cx| {
2423 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2424 });
2425 cx.focus(&item);
2426 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2427
2428 fs.set_head_and_index_for_repo(
2429 Path::new(path!("/project/.git")),
2430 &[(
2431 "README.md",
2432 "# My cool project\nDetails to come.\n".to_owned(),
2433 )],
2434 );
2435 cx.run_until_parked();
2436
2437 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2438
2439 cx.assert_excerpts_with_selections("[EXCERPT]\nˇ# My cool project\nDetails to come.\n");
2440 }
2441}