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