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