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