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