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