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