1use crate::{
2 conflict_view::ConflictAddon,
3 git_panel::{GitPanel, GitPanelAddon, GitStatusEntry},
4 git_panel_settings::GitPanelSettings,
5 remote_button::{render_publish_button, render_push_button},
6};
7use anyhow::{Context as _, Result, anyhow};
8use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
9use collections::{HashMap, HashSet};
10use editor::{
11 Addon, Editor, EditorEvent, SelectionEffects,
12 actions::{GoToHunk, GoToPreviousHunk},
13 multibuffer_context_lines,
14 scroll::Autoscroll,
15};
16use git::{
17 Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll, UnstageAndNext,
18 repository::{Branch, RepoPath, Upstream, UpstreamTracking, UpstreamTrackingStatus},
19 status::FileStatus,
20};
21use gpui::{
22 Action, AnyElement, App, AppContext as _, AsyncWindowContext, Entity, EventEmitter,
23 FocusHandle, Focusable, Render, Subscription, Task, WeakEntity, actions,
24};
25use language::{Anchor, Buffer, Capability, OffsetRangeExt};
26use multi_buffer::{MultiBuffer, PathKey};
27use project::{
28 Project, ProjectPath,
29 git_store::{
30 Repository,
31 branch_diff::{self, BranchDiffEvent, DiffBase},
32 },
33};
34use settings::{Settings, SettingsStore};
35use 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.as_ref().clone());
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, _, range)) = self.editor.read(cx).active_excerpt(cx) {
387 ranges = vec![multi_buffer::Anchor::range_in_buffer(excerpt_id, range)];
388 } else {
389 ranges = Vec::default();
390 }
391 }
392 let mut has_staged_hunks = false;
393 let mut has_unstaged_hunks = false;
394 for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
395 match hunk.secondary_status {
396 DiffHunkSecondaryStatus::HasSecondaryHunk
397 | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending => {
398 has_unstaged_hunks = true;
399 }
400 DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
401 has_staged_hunks = true;
402 has_unstaged_hunks = true;
403 }
404 DiffHunkSecondaryStatus::NoSecondaryHunk
405 | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending => {
406 has_staged_hunks = true;
407 }
408 }
409 }
410 let mut stage_all = false;
411 let mut unstage_all = false;
412 self.workspace
413 .read_with(cx, |workspace, cx| {
414 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
415 let git_panel = git_panel.read(cx);
416 stage_all = git_panel.can_stage_all();
417 unstage_all = git_panel.can_unstage_all();
418 }
419 })
420 .ok();
421
422 ButtonStates {
423 stage: has_unstaged_hunks,
424 unstage: has_staged_hunks,
425 prev_next,
426 selection,
427 stage_all,
428 unstage_all,
429 }
430 }
431
432 fn handle_editor_event(
433 &mut self,
434 editor: &Entity<Editor>,
435 event: &EditorEvent,
436 window: &mut Window,
437 cx: &mut Context<Self>,
438 ) {
439 if let EditorEvent::SelectionsChanged { local: true } = event {
440 let Some(project_path) = self.active_path(cx) else {
441 return;
442 };
443 self.workspace
444 .update(cx, |workspace, cx| {
445 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
446 git_panel.update(cx, |git_panel, cx| {
447 git_panel.select_entry_by_path(project_path, window, cx)
448 })
449 }
450 })
451 .ok();
452 }
453 if editor.focus_handle(cx).contains_focused(window, cx)
454 && self.multibuffer.read(cx).is_empty()
455 {
456 self.focus_handle.focus(window)
457 }
458 }
459
460 fn register_buffer(
461 &mut self,
462 path_key: PathKey,
463 file_status: FileStatus,
464 buffer: Entity<Buffer>,
465 diff: Entity<BufferDiff>,
466 window: &mut Window,
467 cx: &mut Context<Self>,
468 ) {
469 let subscription = cx.subscribe_in(&diff, window, move |this, _, _, window, cx| {
470 this._task = window.spawn(cx, {
471 let this = cx.weak_entity();
472 async |cx| Self::refresh(this, cx).await
473 })
474 });
475 self.buffer_diff_subscriptions
476 .insert(path_key.path.clone(), (diff.clone(), subscription));
477
478 let conflict_addon = self
479 .editor
480 .read(cx)
481 .addon::<ConflictAddon>()
482 .expect("project diff editor should have a conflict addon");
483
484 let snapshot = buffer.read(cx).snapshot();
485 let diff_read = diff.read(cx);
486 let diff_hunk_ranges = diff_read
487 .hunks_intersecting_range(
488 Anchor::min_max_range_for_buffer(diff_read.buffer_id),
489 &snapshot,
490 cx,
491 )
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
524 .select_ranges([multi_buffer::Anchor::min()..multi_buffer::Anchor::min()])
525 });
526 }
527 if is_excerpt_newly_added
528 && (file_status.is_deleted()
529 || (file_status.is_untracked()
530 && GitPanelSettings::get_global(cx).collapse_untracked_diff))
531 {
532 editor.fold_buffer(snapshot.text.remote_id(), cx)
533 }
534 });
535
536 if self.multibuffer.read(cx).is_empty()
537 && self
538 .editor
539 .read(cx)
540 .focus_handle(cx)
541 .contains_focused(window, cx)
542 {
543 self.focus_handle.focus(window);
544 } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
545 self.editor.update(cx, |editor, cx| {
546 editor.focus_handle(cx).focus(window);
547 });
548 }
549 if self.pending_scroll.as_ref() == Some(&path_key) {
550 self.move_to_path(path_key, window, cx);
551 }
552 }
553
554 pub async fn refresh(this: WeakEntity<Self>, cx: &mut AsyncWindowContext) -> Result<()> {
555 let mut path_keys = Vec::new();
556 let buffers_to_load = this.update(cx, |this, cx| {
557 let (repo, buffers_to_load) = this.branch_diff.update(cx, |branch_diff, cx| {
558 let load_buffers = branch_diff.load_buffers(cx);
559 (branch_diff.repo().cloned(), load_buffers)
560 });
561 let mut previous_paths = this.multibuffer.read(cx).paths().collect::<HashSet<_>>();
562
563 if let Some(repo) = repo {
564 let repo = repo.read(cx);
565
566 path_keys = Vec::with_capacity(buffers_to_load.len());
567 for entry in buffers_to_load.iter() {
568 let sort_prefix = sort_prefix(&repo, &entry.repo_path, entry.file_status, cx);
569 let path_key =
570 PathKey::with_sort_prefix(sort_prefix, entry.repo_path.as_ref().clone());
571 previous_paths.remove(&path_key);
572 path_keys.push(path_key)
573 }
574 }
575
576 this.multibuffer.update(cx, |multibuffer, cx| {
577 for path in previous_paths {
578 this.buffer_diff_subscriptions.remove(&path.path);
579 multibuffer.remove_excerpts_for_path(path, cx);
580 }
581 });
582 buffers_to_load
583 })?;
584
585 for (entry, path_key) in buffers_to_load.into_iter().zip(path_keys.into_iter()) {
586 if let Some((buffer, diff)) = entry.load.await.log_err() {
587 cx.update(|window, cx| {
588 this.update(cx, |this, cx| {
589 this.register_buffer(path_key, entry.file_status, buffer, diff, window, cx)
590 })
591 .ok();
592 })?;
593 }
594 }
595 this.update(cx, |this, cx| {
596 this.pending_scroll.take();
597 cx.notify();
598 })?;
599
600 Ok(())
601 }
602
603 #[cfg(any(test, feature = "test-support"))]
604 pub fn excerpt_paths(&self, cx: &App) -> Vec<std::sync::Arc<util::rel_path::RelPath>> {
605 self.multibuffer
606 .read(cx)
607 .excerpt_paths()
608 .map(|key| key.path.clone())
609 .collect()
610 }
611}
612
613fn sort_prefix(repo: &Repository, repo_path: &RepoPath, status: FileStatus, cx: &App) -> u64 {
614 if GitPanelSettings::get_global(cx).sort_by_path {
615 TRACKED_SORT_PREFIX
616 } else if repo.had_conflict_on_last_merge_head_change(repo_path) {
617 CONFLICT_SORT_PREFIX
618 } else if status.is_created() {
619 NEW_SORT_PREFIX
620 } else {
621 TRACKED_SORT_PREFIX
622 }
623}
624
625impl EventEmitter<EditorEvent> for ProjectDiff {}
626
627impl Focusable for ProjectDiff {
628 fn focus_handle(&self, cx: &App) -> FocusHandle {
629 if self.multibuffer.read(cx).is_empty() {
630 self.focus_handle.clone()
631 } else {
632 self.editor.focus_handle(cx)
633 }
634 }
635}
636
637impl Item for ProjectDiff {
638 type Event = EditorEvent;
639
640 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
641 Some(Icon::new(IconName::GitBranch).color(Color::Muted))
642 }
643
644 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
645 Editor::to_item_events(event, f)
646 }
647
648 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
649 self.editor
650 .update(cx, |editor, cx| editor.deactivated(window, cx));
651 }
652
653 fn navigate(
654 &mut self,
655 data: Box<dyn Any>,
656 window: &mut Window,
657 cx: &mut Context<Self>,
658 ) -> bool {
659 self.editor
660 .update(cx, |editor, cx| editor.navigate(data, window, cx))
661 }
662
663 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
664 Some("Project Diff".into())
665 }
666
667 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
668 Label::new(self.tab_content_text(0, cx))
669 .color(if params.selected {
670 Color::Default
671 } else {
672 Color::Muted
673 })
674 .into_any_element()
675 }
676
677 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
678 match self.branch_diff.read(cx).diff_base() {
679 DiffBase::Head => "Uncommitted Changes".into(),
680 DiffBase::Merge { base_ref } => format!("Changes since {}", base_ref).into(),
681 }
682 }
683
684 fn telemetry_event_text(&self) -> Option<&'static str> {
685 Some("Project Diff Opened")
686 }
687
688 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
689 Some(Box::new(self.editor.clone()))
690 }
691
692 fn for_each_project_item(
693 &self,
694 cx: &App,
695 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
696 ) {
697 self.editor.for_each_project_item(cx, f)
698 }
699
700 fn set_nav_history(
701 &mut self,
702 nav_history: ItemNavHistory,
703 _: &mut Window,
704 cx: &mut Context<Self>,
705 ) {
706 self.editor.update(cx, |editor, _| {
707 editor.set_nav_history(Some(nav_history));
708 });
709 }
710
711 fn can_split(&self) -> bool {
712 true
713 }
714
715 fn clone_on_split(
716 &self,
717 _workspace_id: Option<workspace::WorkspaceId>,
718 window: &mut Window,
719 cx: &mut Context<Self>,
720 ) -> Task<Option<Entity<Self>>>
721 where
722 Self: Sized,
723 {
724 let Some(workspace) = self.workspace.upgrade() else {
725 return Task::ready(None);
726 };
727 Task::ready(Some(cx.new(|cx| {
728 ProjectDiff::new(self.project.clone(), workspace, window, cx)
729 })))
730 }
731
732 fn is_dirty(&self, cx: &App) -> bool {
733 self.multibuffer.read(cx).is_dirty(cx)
734 }
735
736 fn has_conflict(&self, cx: &App) -> bool {
737 self.multibuffer.read(cx).has_conflict(cx)
738 }
739
740 fn can_save(&self, _: &App) -> bool {
741 true
742 }
743
744 fn save(
745 &mut self,
746 options: SaveOptions,
747 project: Entity<Project>,
748 window: &mut Window,
749 cx: &mut Context<Self>,
750 ) -> Task<Result<()>> {
751 self.editor.save(options, project, window, cx)
752 }
753
754 fn save_as(
755 &mut self,
756 _: Entity<Project>,
757 _: ProjectPath,
758 _window: &mut Window,
759 _: &mut Context<Self>,
760 ) -> Task<Result<()>> {
761 unreachable!()
762 }
763
764 fn reload(
765 &mut self,
766 project: Entity<Project>,
767 window: &mut Window,
768 cx: &mut Context<Self>,
769 ) -> Task<Result<()>> {
770 self.editor.reload(project, window, cx)
771 }
772
773 fn act_as_type<'a>(
774 &'a self,
775 type_id: TypeId,
776 self_handle: &'a Entity<Self>,
777 _: &'a App,
778 ) -> Option<gpui::AnyEntity> {
779 if type_id == TypeId::of::<Self>() {
780 Some(self_handle.clone().into())
781 } else if type_id == TypeId::of::<Editor>() {
782 Some(self.editor.clone().into())
783 } else {
784 None
785 }
786 }
787
788 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
789 ToolbarItemLocation::PrimaryLeft
790 }
791
792 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
793 self.editor.breadcrumbs(theme, cx)
794 }
795
796 fn added_to_workspace(
797 &mut self,
798 workspace: &mut Workspace,
799 window: &mut Window,
800 cx: &mut Context<Self>,
801 ) {
802 self.editor.update(cx, |editor, cx| {
803 editor.added_to_workspace(workspace, window, cx)
804 });
805 }
806}
807
808impl Render for ProjectDiff {
809 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
810 let is_empty = self.multibuffer.read(cx).is_empty();
811
812 div()
813 .track_focus(&self.focus_handle)
814 .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
815 .bg(cx.theme().colors().editor_background)
816 .flex()
817 .items_center()
818 .justify_center()
819 .size_full()
820 .when(is_empty, |el| {
821 let remote_button = if let Some(panel) = self
822 .workspace
823 .upgrade()
824 .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
825 {
826 panel.update(cx, |panel, cx| panel.render_remote_button(cx))
827 } else {
828 None
829 };
830 let keybinding_focus_handle = self.focus_handle(cx);
831 el.child(
832 v_flex()
833 .gap_1()
834 .child(
835 h_flex()
836 .justify_around()
837 .child(Label::new("No uncommitted changes")),
838 )
839 .map(|el| match remote_button {
840 Some(button) => el.child(h_flex().justify_around().child(button)),
841 None => el.child(
842 h_flex()
843 .justify_around()
844 .child(Label::new("Remote up to date")),
845 ),
846 })
847 .child(
848 h_flex().justify_around().mt_1().child(
849 Button::new("project-diff-close-button", "Close")
850 // .style(ButtonStyle::Transparent)
851 .key_binding(KeyBinding::for_action_in(
852 &CloseActiveItem::default(),
853 &keybinding_focus_handle,
854 cx,
855 ))
856 .on_click(move |_, window, cx| {
857 window.focus(&keybinding_focus_handle);
858 window.dispatch_action(
859 Box::new(CloseActiveItem::default()),
860 cx,
861 );
862 }),
863 ),
864 ),
865 )
866 })
867 .when(!is_empty, |el| el.child(self.editor.clone()))
868 }
869}
870
871impl SerializableItem for ProjectDiff {
872 fn serialized_item_kind() -> &'static str {
873 "ProjectDiff"
874 }
875
876 fn cleanup(
877 _: workspace::WorkspaceId,
878 _: Vec<workspace::ItemId>,
879 _: &mut Window,
880 _: &mut App,
881 ) -> Task<Result<()>> {
882 Task::ready(Ok(()))
883 }
884
885 fn deserialize(
886 project: Entity<Project>,
887 workspace: WeakEntity<Workspace>,
888 workspace_id: workspace::WorkspaceId,
889 item_id: workspace::ItemId,
890 window: &mut Window,
891 cx: &mut App,
892 ) -> Task<Result<Entity<Self>>> {
893 window.spawn(cx, async move |cx| {
894 let diff_base = persistence::PROJECT_DIFF_DB.get_diff_base(item_id, workspace_id)?;
895
896 let diff = cx.update(|window, cx| {
897 let branch_diff = cx
898 .new(|cx| branch_diff::BranchDiff::new(diff_base, project.clone(), window, cx));
899 let workspace = workspace.upgrade().context("workspace gone")?;
900 anyhow::Ok(
901 cx.new(|cx| ProjectDiff::new_impl(branch_diff, project, workspace, window, cx)),
902 )
903 })??;
904
905 Ok(diff)
906 })
907 }
908
909 fn serialize(
910 &mut self,
911 workspace: &mut Workspace,
912 item_id: workspace::ItemId,
913 _closing: bool,
914 _window: &mut Window,
915 cx: &mut Context<Self>,
916 ) -> Option<Task<Result<()>>> {
917 let workspace_id = workspace.database_id()?;
918 let diff_base = self.diff_base(cx).clone();
919
920 Some(cx.background_spawn({
921 async move {
922 persistence::PROJECT_DIFF_DB
923 .save_diff_base(item_id, workspace_id, diff_base.clone())
924 .await
925 }
926 }))
927 }
928
929 fn should_serialize(&self, _: &Self::Event) -> bool {
930 false
931 }
932}
933
934mod persistence {
935
936 use anyhow::Context as _;
937 use db::{
938 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
939 sqlez_macros::sql,
940 };
941 use project::git_store::branch_diff::DiffBase;
942 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
943
944 pub struct ProjectDiffDb(ThreadSafeConnection);
945
946 impl Domain for ProjectDiffDb {
947 const NAME: &str = stringify!(ProjectDiffDb);
948
949 const MIGRATIONS: &[&str] = &[sql!(
950 CREATE TABLE project_diffs(
951 workspace_id INTEGER,
952 item_id INTEGER UNIQUE,
953
954 diff_base TEXT,
955
956 PRIMARY KEY(workspace_id, item_id),
957 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
958 ON DELETE CASCADE
959 ) STRICT;
960 )];
961 }
962
963 db::static_connection!(PROJECT_DIFF_DB, ProjectDiffDb, [WorkspaceDb]);
964
965 impl ProjectDiffDb {
966 pub async fn save_diff_base(
967 &self,
968 item_id: ItemId,
969 workspace_id: WorkspaceId,
970 diff_base: DiffBase,
971 ) -> anyhow::Result<()> {
972 self.write(move |connection| {
973 let sql_stmt = sql!(
974 INSERT OR REPLACE INTO project_diffs(item_id, workspace_id, diff_base) VALUES (?, ?, ?)
975 );
976 let diff_base_str = serde_json::to_string(&diff_base)?;
977 let mut query = connection.exec_bound::<(ItemId, WorkspaceId, String)>(sql_stmt)?;
978 query((item_id, workspace_id, diff_base_str)).context(format!(
979 "exec_bound failed to execute or parse for: {}",
980 sql_stmt
981 ))
982 })
983 .await
984 }
985
986 pub fn get_diff_base(
987 &self,
988 item_id: ItemId,
989 workspace_id: WorkspaceId,
990 ) -> anyhow::Result<DiffBase> {
991 let sql_stmt =
992 sql!(SELECT diff_base FROM project_diffs WHERE item_id = ?AND workspace_id = ?);
993 let diff_base_str = self.select_row_bound::<(ItemId, WorkspaceId), String>(sql_stmt)?(
994 (item_id, workspace_id),
995 )
996 .context(::std::format!(
997 "Error in get_diff_base, select_row_bound failed to execute or parse for: {}",
998 sql_stmt
999 ))?;
1000 let Some(diff_base_str) = diff_base_str else {
1001 return Ok(DiffBase::Head);
1002 };
1003 serde_json::from_str(&diff_base_str).context("deserializing diff base")
1004 }
1005 }
1006}
1007
1008pub struct ProjectDiffToolbar {
1009 project_diff: Option<WeakEntity<ProjectDiff>>,
1010 workspace: WeakEntity<Workspace>,
1011}
1012
1013impl ProjectDiffToolbar {
1014 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
1015 Self {
1016 project_diff: None,
1017 workspace: workspace.weak_handle(),
1018 }
1019 }
1020
1021 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
1022 self.project_diff.as_ref()?.upgrade()
1023 }
1024
1025 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
1026 if let Some(project_diff) = self.project_diff(cx) {
1027 project_diff.focus_handle(cx).focus(window);
1028 }
1029 let action = action.boxed_clone();
1030 cx.defer(move |cx| {
1031 cx.dispatch_action(action.as_ref());
1032 })
1033 }
1034
1035 fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1036 self.workspace
1037 .update(cx, |workspace, cx| {
1038 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
1039 panel.update(cx, |panel, cx| {
1040 panel.stage_all(&Default::default(), window, cx);
1041 });
1042 }
1043 })
1044 .ok();
1045 }
1046
1047 fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1048 self.workspace
1049 .update(cx, |workspace, cx| {
1050 let Some(panel) = workspace.panel::<GitPanel>(cx) else {
1051 return;
1052 };
1053 panel.update(cx, |panel, cx| {
1054 panel.unstage_all(&Default::default(), window, cx);
1055 });
1056 })
1057 .ok();
1058 }
1059}
1060
1061impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
1062
1063impl ToolbarItemView for ProjectDiffToolbar {
1064 fn set_active_pane_item(
1065 &mut self,
1066 active_pane_item: Option<&dyn ItemHandle>,
1067 _: &mut Window,
1068 cx: &mut Context<Self>,
1069 ) -> ToolbarItemLocation {
1070 self.project_diff = active_pane_item
1071 .and_then(|item| item.act_as::<ProjectDiff>(cx))
1072 .filter(|item| item.read(cx).diff_base(cx) == &DiffBase::Head)
1073 .map(|entity| entity.downgrade());
1074 if self.project_diff.is_some() {
1075 ToolbarItemLocation::PrimaryRight
1076 } else {
1077 ToolbarItemLocation::Hidden
1078 }
1079 }
1080
1081 fn pane_focus_update(
1082 &mut self,
1083 _pane_focused: bool,
1084 _window: &mut Window,
1085 _cx: &mut Context<Self>,
1086 ) {
1087 }
1088}
1089
1090struct ButtonStates {
1091 stage: bool,
1092 unstage: bool,
1093 prev_next: bool,
1094 selection: bool,
1095 stage_all: bool,
1096 unstage_all: bool,
1097}
1098
1099impl Render for ProjectDiffToolbar {
1100 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1101 let Some(project_diff) = self.project_diff(cx) else {
1102 return div();
1103 };
1104 let focus_handle = project_diff.focus_handle(cx);
1105 let button_states = project_diff.read(cx).button_states(cx);
1106
1107 h_group_xl()
1108 .my_neg_1()
1109 .py_1()
1110 .items_center()
1111 .flex_wrap()
1112 .justify_between()
1113 .child(
1114 h_group_sm()
1115 .when(button_states.selection, |el| {
1116 el.child(
1117 Button::new("stage", "Toggle Staged")
1118 .tooltip(Tooltip::for_action_title_in(
1119 "Toggle Staged",
1120 &ToggleStaged,
1121 &focus_handle,
1122 ))
1123 .disabled(!button_states.stage && !button_states.unstage)
1124 .on_click(cx.listener(|this, _, window, cx| {
1125 this.dispatch_action(&ToggleStaged, window, cx)
1126 })),
1127 )
1128 })
1129 .when(!button_states.selection, |el| {
1130 el.child(
1131 Button::new("stage", "Stage")
1132 .tooltip(Tooltip::for_action_title_in(
1133 "Stage and go to next hunk",
1134 &StageAndNext,
1135 &focus_handle,
1136 ))
1137 .disabled(
1138 !button_states.prev_next
1139 && !button_states.stage_all
1140 && !button_states.unstage_all,
1141 )
1142 .on_click(cx.listener(|this, _, window, cx| {
1143 this.dispatch_action(&StageAndNext, window, cx)
1144 })),
1145 )
1146 .child(
1147 Button::new("unstage", "Unstage")
1148 .tooltip(Tooltip::for_action_title_in(
1149 "Unstage and go to next hunk",
1150 &UnstageAndNext,
1151 &focus_handle,
1152 ))
1153 .disabled(
1154 !button_states.prev_next
1155 && !button_states.stage_all
1156 && !button_states.unstage_all,
1157 )
1158 .on_click(cx.listener(|this, _, window, cx| {
1159 this.dispatch_action(&UnstageAndNext, window, cx)
1160 })),
1161 )
1162 }),
1163 )
1164 // n.b. the only reason these arrows are here is because we don't
1165 // support "undo" for staging so we need a way to go back.
1166 .child(
1167 h_group_sm()
1168 .child(
1169 IconButton::new("up", IconName::ArrowUp)
1170 .shape(ui::IconButtonShape::Square)
1171 .tooltip(Tooltip::for_action_title_in(
1172 "Go to previous hunk",
1173 &GoToPreviousHunk,
1174 &focus_handle,
1175 ))
1176 .disabled(!button_states.prev_next)
1177 .on_click(cx.listener(|this, _, window, cx| {
1178 this.dispatch_action(&GoToPreviousHunk, window, cx)
1179 })),
1180 )
1181 .child(
1182 IconButton::new("down", IconName::ArrowDown)
1183 .shape(ui::IconButtonShape::Square)
1184 .tooltip(Tooltip::for_action_title_in(
1185 "Go to next hunk",
1186 &GoToHunk,
1187 &focus_handle,
1188 ))
1189 .disabled(!button_states.prev_next)
1190 .on_click(cx.listener(|this, _, window, cx| {
1191 this.dispatch_action(&GoToHunk, window, cx)
1192 })),
1193 ),
1194 )
1195 .child(vertical_divider())
1196 .child(
1197 h_group_sm()
1198 .when(
1199 button_states.unstage_all && !button_states.stage_all,
1200 |el| {
1201 el.child(
1202 Button::new("unstage-all", "Unstage All")
1203 .tooltip(Tooltip::for_action_title_in(
1204 "Unstage all changes",
1205 &UnstageAll,
1206 &focus_handle,
1207 ))
1208 .on_click(cx.listener(|this, _, window, cx| {
1209 this.unstage_all(window, cx)
1210 })),
1211 )
1212 },
1213 )
1214 .when(
1215 !button_states.unstage_all || button_states.stage_all,
1216 |el| {
1217 el.child(
1218 // todo make it so that changing to say "Unstaged"
1219 // doesn't change the position.
1220 div().child(
1221 Button::new("stage-all", "Stage All")
1222 .disabled(!button_states.stage_all)
1223 .tooltip(Tooltip::for_action_title_in(
1224 "Stage all changes",
1225 &StageAll,
1226 &focus_handle,
1227 ))
1228 .on_click(cx.listener(|this, _, window, cx| {
1229 this.stage_all(window, cx)
1230 })),
1231 ),
1232 )
1233 },
1234 )
1235 .child(
1236 Button::new("commit", "Commit")
1237 .tooltip(Tooltip::for_action_title_in(
1238 "Commit",
1239 &Commit,
1240 &focus_handle,
1241 ))
1242 .on_click(cx.listener(|this, _, window, cx| {
1243 this.dispatch_action(&Commit, window, cx);
1244 })),
1245 ),
1246 )
1247 }
1248}
1249
1250#[derive(IntoElement, RegisterComponent)]
1251pub struct ProjectDiffEmptyState {
1252 pub no_repo: bool,
1253 pub can_push_and_pull: bool,
1254 pub focus_handle: Option<FocusHandle>,
1255 pub current_branch: Option<Branch>,
1256 // has_pending_commits: bool,
1257 // ahead_of_remote: bool,
1258 // no_git_repository: bool,
1259}
1260
1261impl RenderOnce for ProjectDiffEmptyState {
1262 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1263 let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1264 matches!(self.current_branch, Some(Branch {
1265 upstream:
1266 Some(Upstream {
1267 tracking:
1268 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1269 ahead, behind, ..
1270 }),
1271 ..
1272 }),
1273 ..
1274 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1275 };
1276
1277 let change_count = |current_branch: &Branch| -> (usize, usize) {
1278 match current_branch {
1279 Branch {
1280 upstream:
1281 Some(Upstream {
1282 tracking:
1283 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1284 ahead, behind, ..
1285 }),
1286 ..
1287 }),
1288 ..
1289 } => (*ahead as usize, *behind as usize),
1290 _ => (0, 0),
1291 }
1292 };
1293
1294 let not_ahead_or_behind = status_against_remote(0, 0);
1295 let ahead_of_remote = status_against_remote(1, 0);
1296 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1297 branch.upstream.is_none()
1298 } else {
1299 false
1300 };
1301
1302 let has_branch_container = |branch: &Branch| {
1303 h_flex()
1304 .max_w(px(420.))
1305 .bg(cx.theme().colors().text.opacity(0.05))
1306 .border_1()
1307 .border_color(cx.theme().colors().border)
1308 .rounded_sm()
1309 .gap_8()
1310 .px_6()
1311 .py_4()
1312 .map(|this| {
1313 if ahead_of_remote {
1314 let ahead_count = change_count(branch).0;
1315 let ahead_string = format!("{} Commits Ahead", ahead_count);
1316 this.child(
1317 v_flex()
1318 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1319 .child(
1320 Label::new(format!("Push your changes to {}", branch.name()))
1321 .color(Color::Muted),
1322 ),
1323 )
1324 .child(div().child(render_push_button(
1325 self.focus_handle,
1326 "push".into(),
1327 ahead_count as u32,
1328 )))
1329 } else if branch_not_on_remote {
1330 this.child(
1331 v_flex()
1332 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1333 .child(
1334 Label::new(format!("Create {} on remote", branch.name()))
1335 .color(Color::Muted),
1336 ),
1337 )
1338 .child(
1339 div().child(render_publish_button(self.focus_handle, "publish".into())),
1340 )
1341 } else {
1342 this.child(Label::new("Remote status unknown").color(Color::Muted))
1343 }
1344 })
1345 };
1346
1347 v_flex().size_full().items_center().justify_center().child(
1348 v_flex()
1349 .gap_1()
1350 .when(self.no_repo, |this| {
1351 // TODO: add git init
1352 this.text_center()
1353 .child(Label::new("No Repository").color(Color::Muted))
1354 })
1355 .map(|this| {
1356 if not_ahead_or_behind && self.current_branch.is_some() {
1357 this.text_center()
1358 .child(Label::new("No Changes").color(Color::Muted))
1359 } else {
1360 this.when_some(self.current_branch.as_ref(), |this, branch| {
1361 this.child(has_branch_container(branch))
1362 })
1363 }
1364 }),
1365 )
1366 }
1367}
1368
1369mod preview {
1370 use git::repository::{
1371 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1372 };
1373 use ui::prelude::*;
1374
1375 use super::ProjectDiffEmptyState;
1376
1377 // View this component preview using `workspace: open component-preview`
1378 impl Component for ProjectDiffEmptyState {
1379 fn scope() -> ComponentScope {
1380 ComponentScope::VersionControl
1381 }
1382
1383 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1384 let unknown_upstream: Option<UpstreamTracking> = None;
1385 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1386 UpstreamTrackingStatus {
1387 ahead: 2,
1388 behind: 0,
1389 }
1390 .into(),
1391 );
1392
1393 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1394 UpstreamTrackingStatus {
1395 ahead: 0,
1396 behind: 0,
1397 }
1398 .into(),
1399 );
1400
1401 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1402 Branch {
1403 is_head: true,
1404 ref_name: "some-branch".into(),
1405 upstream: upstream.map(|tracking| Upstream {
1406 ref_name: "origin/some-branch".into(),
1407 tracking,
1408 }),
1409 most_recent_commit: Some(CommitSummary {
1410 sha: "abc123".into(),
1411 subject: "Modify stuff".into(),
1412 commit_timestamp: 1710932954,
1413 author_name: "John Doe".into(),
1414 has_parent: true,
1415 }),
1416 }
1417 }
1418
1419 let no_repo_state = ProjectDiffEmptyState {
1420 no_repo: true,
1421 can_push_and_pull: false,
1422 focus_handle: None,
1423 current_branch: None,
1424 };
1425
1426 let no_changes_state = ProjectDiffEmptyState {
1427 no_repo: false,
1428 can_push_and_pull: true,
1429 focus_handle: None,
1430 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1431 };
1432
1433 let ahead_of_upstream_state = ProjectDiffEmptyState {
1434 no_repo: false,
1435 can_push_and_pull: true,
1436 focus_handle: None,
1437 current_branch: Some(branch(ahead_of_upstream)),
1438 };
1439
1440 let unknown_upstream_state = ProjectDiffEmptyState {
1441 no_repo: false,
1442 can_push_and_pull: true,
1443 focus_handle: None,
1444 current_branch: Some(branch(unknown_upstream)),
1445 };
1446
1447 let (width, height) = (px(480.), px(320.));
1448
1449 Some(
1450 v_flex()
1451 .gap_6()
1452 .children(vec![
1453 example_group(vec![
1454 single_example(
1455 "No Repo",
1456 div()
1457 .w(width)
1458 .h(height)
1459 .child(no_repo_state)
1460 .into_any_element(),
1461 ),
1462 single_example(
1463 "No Changes",
1464 div()
1465 .w(width)
1466 .h(height)
1467 .child(no_changes_state)
1468 .into_any_element(),
1469 ),
1470 single_example(
1471 "Unknown Upstream",
1472 div()
1473 .w(width)
1474 .h(height)
1475 .child(unknown_upstream_state)
1476 .into_any_element(),
1477 ),
1478 single_example(
1479 "Ahead of Remote",
1480 div()
1481 .w(width)
1482 .h(height)
1483 .child(ahead_of_upstream_state)
1484 .into_any_element(),
1485 ),
1486 ])
1487 .vertical(),
1488 ])
1489 .into_any_element(),
1490 )
1491 }
1492 }
1493}
1494
1495fn merge_anchor_ranges<'a>(
1496 left: impl 'a + Iterator<Item = Range<Anchor>>,
1497 right: impl 'a + Iterator<Item = Range<Anchor>>,
1498 snapshot: &'a language::BufferSnapshot,
1499) -> impl 'a + Iterator<Item = Range<Anchor>> {
1500 let mut left = left.fuse().peekable();
1501 let mut right = right.fuse().peekable();
1502
1503 std::iter::from_fn(move || {
1504 let Some(left_range) = left.peek() else {
1505 return right.next();
1506 };
1507 let Some(right_range) = right.peek() else {
1508 return left.next();
1509 };
1510
1511 let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
1512 left.next().unwrap()
1513 } else {
1514 right.next().unwrap()
1515 };
1516
1517 // Extend the basic range while there's overlap with a range from either stream.
1518 loop {
1519 if let Some(left_range) = left
1520 .peek()
1521 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1522 .cloned()
1523 {
1524 left.next();
1525 next_range.end = left_range.end;
1526 } else if let Some(right_range) = right
1527 .peek()
1528 .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
1529 .cloned()
1530 {
1531 right.next();
1532 next_range.end = right_range.end;
1533 } else {
1534 break;
1535 }
1536 }
1537
1538 Some(next_range)
1539 })
1540}
1541
1542struct BranchDiffAddon {
1543 branch_diff: Entity<branch_diff::BranchDiff>,
1544}
1545
1546impl Addon for BranchDiffAddon {
1547 fn to_any(&self) -> &dyn std::any::Any {
1548 self
1549 }
1550
1551 fn override_status_for_buffer_id(
1552 &self,
1553 buffer_id: language::BufferId,
1554 cx: &App,
1555 ) -> Option<FileStatus> {
1556 self.branch_diff
1557 .read(cx)
1558 .status_for_buffer_id(buffer_id, cx)
1559 }
1560}
1561
1562#[cfg(test)]
1563mod tests {
1564 use collections::HashMap;
1565 use db::indoc;
1566 use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1567 use git::status::{TrackedStatus, UnmergedStatus, UnmergedStatusCode};
1568 use gpui::TestAppContext;
1569 use project::FakeFs;
1570 use serde_json::json;
1571 use settings::SettingsStore;
1572 use std::path::Path;
1573 use unindent::Unindent as _;
1574 use util::{
1575 path,
1576 rel_path::{RelPath, rel_path},
1577 };
1578
1579 use super::*;
1580
1581 #[ctor::ctor]
1582 fn init_logger() {
1583 zlog::init_test();
1584 }
1585
1586 fn init_test(cx: &mut TestAppContext) {
1587 cx.update(|cx| {
1588 let store = SettingsStore::test(cx);
1589 cx.set_global(store);
1590 theme::init(theme::LoadThemes::JustBase, 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}