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