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