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