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 // TODO(split-diff) SplitEditor should be searchable
879 Some(Box::new(self.editor.read(cx).rhs_editor().clone()))
880 }
881
882 fn for_each_project_item(
883 &self,
884 cx: &App,
885 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
886 ) {
887 self.editor
888 .read(cx)
889 .rhs_editor()
890 .read(cx)
891 .for_each_project_item(cx, f)
892 }
893
894 fn set_nav_history(
895 &mut self,
896 nav_history: ItemNavHistory,
897 _: &mut Window,
898 cx: &mut Context<Self>,
899 ) {
900 self.editor.update(cx, |editor, cx| {
901 editor.rhs_editor().update(cx, |primary_editor, _| {
902 primary_editor.set_nav_history(Some(nav_history));
903 })
904 });
905 }
906
907 fn can_split(&self) -> bool {
908 true
909 }
910
911 fn clone_on_split(
912 &self,
913 _workspace_id: Option<workspace::WorkspaceId>,
914 window: &mut Window,
915 cx: &mut Context<Self>,
916 ) -> Task<Option<Entity<Self>>>
917 where
918 Self: Sized,
919 {
920 let Some(workspace) = self.workspace.upgrade() else {
921 return Task::ready(None);
922 };
923 Task::ready(Some(cx.new(|cx| {
924 ProjectDiff::new(self.project.clone(), workspace, window, cx)
925 })))
926 }
927
928 fn is_dirty(&self, cx: &App) -> bool {
929 self.multibuffer.read(cx).is_dirty(cx)
930 }
931
932 fn has_conflict(&self, cx: &App) -> bool {
933 self.multibuffer.read(cx).has_conflict(cx)
934 }
935
936 fn can_save(&self, _: &App) -> bool {
937 true
938 }
939
940 fn save(
941 &mut self,
942 options: SaveOptions,
943 project: Entity<Project>,
944 window: &mut Window,
945 cx: &mut Context<Self>,
946 ) -> Task<Result<()>> {
947 self.editor.update(cx, |editor, cx| {
948 editor.rhs_editor().update(cx, |primary_editor, cx| {
949 primary_editor.save(options, project, window, cx)
950 })
951 })
952 }
953
954 fn save_as(
955 &mut self,
956 _: Entity<Project>,
957 _: ProjectPath,
958 _window: &mut Window,
959 _: &mut Context<Self>,
960 ) -> Task<Result<()>> {
961 unreachable!()
962 }
963
964 fn reload(
965 &mut self,
966 project: Entity<Project>,
967 window: &mut Window,
968 cx: &mut Context<Self>,
969 ) -> Task<Result<()>> {
970 self.editor.update(cx, |editor, cx| {
971 editor.rhs_editor().update(cx, |primary_editor, cx| {
972 primary_editor.reload(project, window, cx)
973 })
974 })
975 }
976
977 fn act_as_type<'a>(
978 &'a self,
979 type_id: TypeId,
980 self_handle: &'a Entity<Self>,
981 cx: &'a App,
982 ) -> Option<gpui::AnyEntity> {
983 if type_id == TypeId::of::<Self>() {
984 Some(self_handle.clone().into())
985 } else if type_id == TypeId::of::<Editor>() {
986 Some(self.editor.read(cx).rhs_editor().clone().into())
987 } else if type_id == TypeId::of::<SplittableEditor>() {
988 Some(self.editor.clone().into())
989 } else {
990 None
991 }
992 }
993
994 fn added_to_workspace(
995 &mut self,
996 workspace: &mut Workspace,
997 window: &mut Window,
998 cx: &mut Context<Self>,
999 ) {
1000 self.editor.update(cx, |editor, cx| {
1001 editor.added_to_workspace(workspace, window, cx)
1002 });
1003 }
1004}
1005
1006impl Render for ProjectDiff {
1007 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1008 let is_empty = self.multibuffer.read(cx).is_empty();
1009
1010 div()
1011 .track_focus(&self.focus_handle)
1012 .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
1013 .bg(cx.theme().colors().editor_background)
1014 .flex()
1015 .items_center()
1016 .justify_center()
1017 .size_full()
1018 .when(is_empty, |el| {
1019 let remote_button = if let Some(panel) = self
1020 .workspace
1021 .upgrade()
1022 .and_then(|workspace| workspace.read(cx).panel::<GitPanel>(cx))
1023 {
1024 panel.update(cx, |panel, cx| panel.render_remote_button(cx))
1025 } else {
1026 None
1027 };
1028 let keybinding_focus_handle = self.focus_handle(cx);
1029 el.child(
1030 v_flex()
1031 .gap_1()
1032 .child(
1033 h_flex()
1034 .justify_around()
1035 .child(Label::new("No uncommitted changes")),
1036 )
1037 .map(|el| match remote_button {
1038 Some(button) => el.child(h_flex().justify_around().child(button)),
1039 None => el.child(
1040 h_flex()
1041 .justify_around()
1042 .child(Label::new("Remote up to date")),
1043 ),
1044 })
1045 .child(
1046 h_flex().justify_around().mt_1().child(
1047 Button::new("project-diff-close-button", "Close")
1048 // .style(ButtonStyle::Transparent)
1049 .key_binding(KeyBinding::for_action_in(
1050 &CloseActiveItem::default(),
1051 &keybinding_focus_handle,
1052 cx,
1053 ))
1054 .on_click(move |_, window, cx| {
1055 window.focus(&keybinding_focus_handle, cx);
1056 window.dispatch_action(
1057 Box::new(CloseActiveItem::default()),
1058 cx,
1059 );
1060 }),
1061 ),
1062 ),
1063 )
1064 })
1065 .when(!is_empty, |el| el.child(self.editor.clone()))
1066 }
1067}
1068
1069impl SerializableItem for ProjectDiff {
1070 fn serialized_item_kind() -> &'static str {
1071 "ProjectDiff"
1072 }
1073
1074 fn cleanup(
1075 _: workspace::WorkspaceId,
1076 _: Vec<workspace::ItemId>,
1077 _: &mut Window,
1078 _: &mut App,
1079 ) -> Task<Result<()>> {
1080 Task::ready(Ok(()))
1081 }
1082
1083 fn deserialize(
1084 project: Entity<Project>,
1085 workspace: WeakEntity<Workspace>,
1086 workspace_id: workspace::WorkspaceId,
1087 item_id: workspace::ItemId,
1088 window: &mut Window,
1089 cx: &mut App,
1090 ) -> Task<Result<Entity<Self>>> {
1091 window.spawn(cx, async move |cx| {
1092 let diff_base = persistence::PROJECT_DIFF_DB.get_diff_base(item_id, workspace_id)?;
1093
1094 let diff = cx.update(|window, cx| {
1095 let branch_diff = cx
1096 .new(|cx| branch_diff::BranchDiff::new(diff_base, project.clone(), window, cx));
1097 let workspace = workspace.upgrade().context("workspace gone")?;
1098 anyhow::Ok(
1099 cx.new(|cx| ProjectDiff::new_impl(branch_diff, project, workspace, window, cx)),
1100 )
1101 })??;
1102
1103 Ok(diff)
1104 })
1105 }
1106
1107 fn serialize(
1108 &mut self,
1109 workspace: &mut Workspace,
1110 item_id: workspace::ItemId,
1111 _closing: bool,
1112 _window: &mut Window,
1113 cx: &mut Context<Self>,
1114 ) -> Option<Task<Result<()>>> {
1115 let workspace_id = workspace.database_id()?;
1116 let diff_base = self.diff_base(cx).clone();
1117
1118 Some(cx.background_spawn({
1119 async move {
1120 persistence::PROJECT_DIFF_DB
1121 .save_diff_base(item_id, workspace_id, diff_base.clone())
1122 .await
1123 }
1124 }))
1125 }
1126
1127 fn should_serialize(&self, _: &Self::Event) -> bool {
1128 false
1129 }
1130}
1131
1132mod persistence {
1133
1134 use anyhow::Context as _;
1135 use db::{
1136 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
1137 sqlez_macros::sql,
1138 };
1139 use project::git_store::branch_diff::DiffBase;
1140 use workspace::{ItemId, WorkspaceDb, WorkspaceId};
1141
1142 pub struct ProjectDiffDb(ThreadSafeConnection);
1143
1144 impl Domain for ProjectDiffDb {
1145 const NAME: &str = stringify!(ProjectDiffDb);
1146
1147 const MIGRATIONS: &[&str] = &[sql!(
1148 CREATE TABLE project_diffs(
1149 workspace_id INTEGER,
1150 item_id INTEGER UNIQUE,
1151
1152 diff_base TEXT,
1153
1154 PRIMARY KEY(workspace_id, item_id),
1155 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
1156 ON DELETE CASCADE
1157 ) STRICT;
1158 )];
1159 }
1160
1161 db::static_connection!(PROJECT_DIFF_DB, ProjectDiffDb, [WorkspaceDb]);
1162
1163 impl ProjectDiffDb {
1164 pub async fn save_diff_base(
1165 &self,
1166 item_id: ItemId,
1167 workspace_id: WorkspaceId,
1168 diff_base: DiffBase,
1169 ) -> anyhow::Result<()> {
1170 self.write(move |connection| {
1171 let sql_stmt = sql!(
1172 INSERT OR REPLACE INTO project_diffs(item_id, workspace_id, diff_base) VALUES (?, ?, ?)
1173 );
1174 let diff_base_str = serde_json::to_string(&diff_base)?;
1175 let mut query = connection.exec_bound::<(ItemId, WorkspaceId, String)>(sql_stmt)?;
1176 query((item_id, workspace_id, diff_base_str)).context(format!(
1177 "exec_bound failed to execute or parse for: {}",
1178 sql_stmt
1179 ))
1180 })
1181 .await
1182 }
1183
1184 pub fn get_diff_base(
1185 &self,
1186 item_id: ItemId,
1187 workspace_id: WorkspaceId,
1188 ) -> anyhow::Result<DiffBase> {
1189 let sql_stmt =
1190 sql!(SELECT diff_base FROM project_diffs WHERE item_id = ?AND workspace_id = ?);
1191 let diff_base_str = self.select_row_bound::<(ItemId, WorkspaceId), String>(sql_stmt)?(
1192 (item_id, workspace_id),
1193 )
1194 .context(::std::format!(
1195 "Error in get_diff_base, select_row_bound failed to execute or parse for: {}",
1196 sql_stmt
1197 ))?;
1198 let Some(diff_base_str) = diff_base_str else {
1199 return Ok(DiffBase::Head);
1200 };
1201 serde_json::from_str(&diff_base_str).context("deserializing diff base")
1202 }
1203 }
1204}
1205
1206pub struct ProjectDiffToolbar {
1207 project_diff: Option<WeakEntity<ProjectDiff>>,
1208 workspace: WeakEntity<Workspace>,
1209}
1210
1211impl ProjectDiffToolbar {
1212 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
1213 Self {
1214 project_diff: None,
1215 workspace: workspace.weak_handle(),
1216 }
1217 }
1218
1219 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
1220 self.project_diff.as_ref()?.upgrade()
1221 }
1222
1223 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
1224 if let Some(project_diff) = self.project_diff(cx) {
1225 project_diff.focus_handle(cx).focus(window, cx);
1226 }
1227 let action = action.boxed_clone();
1228 cx.defer(move |cx| {
1229 cx.dispatch_action(action.as_ref());
1230 })
1231 }
1232
1233 fn stage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1234 self.workspace
1235 .update(cx, |workspace, cx| {
1236 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
1237 panel.update(cx, |panel, cx| {
1238 panel.stage_all(&Default::default(), window, cx);
1239 });
1240 }
1241 })
1242 .ok();
1243 }
1244
1245 fn unstage_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1246 self.workspace
1247 .update(cx, |workspace, cx| {
1248 let Some(panel) = workspace.panel::<GitPanel>(cx) else {
1249 return;
1250 };
1251 panel.update(cx, |panel, cx| {
1252 panel.unstage_all(&Default::default(), window, cx);
1253 });
1254 })
1255 .ok();
1256 }
1257}
1258
1259impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
1260
1261impl ToolbarItemView for ProjectDiffToolbar {
1262 fn set_active_pane_item(
1263 &mut self,
1264 active_pane_item: Option<&dyn ItemHandle>,
1265 _: &mut Window,
1266 cx: &mut Context<Self>,
1267 ) -> ToolbarItemLocation {
1268 self.project_diff = active_pane_item
1269 .and_then(|item| item.act_as::<ProjectDiff>(cx))
1270 .filter(|item| item.read(cx).diff_base(cx) == &DiffBase::Head)
1271 .map(|entity| entity.downgrade());
1272 if self.project_diff.is_some() {
1273 ToolbarItemLocation::PrimaryRight
1274 } else {
1275 ToolbarItemLocation::Hidden
1276 }
1277 }
1278
1279 fn pane_focus_update(
1280 &mut self,
1281 _pane_focused: bool,
1282 _window: &mut Window,
1283 _cx: &mut Context<Self>,
1284 ) {
1285 }
1286}
1287
1288struct ButtonStates {
1289 stage: bool,
1290 unstage: bool,
1291 prev_next: bool,
1292 selection: bool,
1293 stage_all: bool,
1294 unstage_all: bool,
1295}
1296
1297impl Render for ProjectDiffToolbar {
1298 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1299 let Some(project_diff) = self.project_diff(cx) else {
1300 return div();
1301 };
1302 let focus_handle = project_diff.focus_handle(cx);
1303 let button_states = project_diff.read(cx).button_states(cx);
1304 let review_count = project_diff.read(cx).total_review_comment_count();
1305
1306 h_group_xl()
1307 .my_neg_1()
1308 .py_1()
1309 .items_center()
1310 .flex_wrap()
1311 .justify_between()
1312 .child(
1313 h_group_sm()
1314 .when(button_states.selection, |el| {
1315 el.child(
1316 Button::new("stage", "Toggle Staged")
1317 .tooltip(Tooltip::for_action_title_in(
1318 "Toggle Staged",
1319 &ToggleStaged,
1320 &focus_handle,
1321 ))
1322 .disabled(!button_states.stage && !button_states.unstage)
1323 .on_click(cx.listener(|this, _, window, cx| {
1324 this.dispatch_action(&ToggleStaged, window, cx)
1325 })),
1326 )
1327 })
1328 .when(!button_states.selection, |el| {
1329 el.child(
1330 Button::new("stage", "Stage")
1331 .tooltip(Tooltip::for_action_title_in(
1332 "Stage and go to next hunk",
1333 &StageAndNext,
1334 &focus_handle,
1335 ))
1336 .disabled(
1337 !button_states.prev_next
1338 && !button_states.stage_all
1339 && !button_states.unstage_all,
1340 )
1341 .on_click(cx.listener(|this, _, window, cx| {
1342 this.dispatch_action(&StageAndNext, window, cx)
1343 })),
1344 )
1345 .child(
1346 Button::new("unstage", "Unstage")
1347 .tooltip(Tooltip::for_action_title_in(
1348 "Unstage and go to next hunk",
1349 &UnstageAndNext,
1350 &focus_handle,
1351 ))
1352 .disabled(
1353 !button_states.prev_next
1354 && !button_states.stage_all
1355 && !button_states.unstage_all,
1356 )
1357 .on_click(cx.listener(|this, _, window, cx| {
1358 this.dispatch_action(&UnstageAndNext, window, cx)
1359 })),
1360 )
1361 }),
1362 )
1363 // n.b. the only reason these arrows are here is because we don't
1364 // support "undo" for staging so we need a way to go back.
1365 .child(
1366 h_group_sm()
1367 .child(
1368 IconButton::new("up", IconName::ArrowUp)
1369 .shape(ui::IconButtonShape::Square)
1370 .tooltip(Tooltip::for_action_title_in(
1371 "Go to previous hunk",
1372 &GoToPreviousHunk,
1373 &focus_handle,
1374 ))
1375 .disabled(!button_states.prev_next)
1376 .on_click(cx.listener(|this, _, window, cx| {
1377 this.dispatch_action(&GoToPreviousHunk, window, cx)
1378 })),
1379 )
1380 .child(
1381 IconButton::new("down", IconName::ArrowDown)
1382 .shape(ui::IconButtonShape::Square)
1383 .tooltip(Tooltip::for_action_title_in(
1384 "Go to next hunk",
1385 &GoToHunk,
1386 &focus_handle,
1387 ))
1388 .disabled(!button_states.prev_next)
1389 .on_click(cx.listener(|this, _, window, cx| {
1390 this.dispatch_action(&GoToHunk, window, cx)
1391 })),
1392 ),
1393 )
1394 .child(vertical_divider())
1395 .child(
1396 h_group_sm()
1397 .when(
1398 button_states.unstage_all && !button_states.stage_all,
1399 |el| {
1400 el.child(
1401 Button::new("unstage-all", "Unstage All")
1402 .tooltip(Tooltip::for_action_title_in(
1403 "Unstage all changes",
1404 &UnstageAll,
1405 &focus_handle,
1406 ))
1407 .on_click(cx.listener(|this, _, window, cx| {
1408 this.unstage_all(window, cx)
1409 })),
1410 )
1411 },
1412 )
1413 .when(
1414 !button_states.unstage_all || button_states.stage_all,
1415 |el| {
1416 el.child(
1417 // todo make it so that changing to say "Unstaged"
1418 // doesn't change the position.
1419 div().child(
1420 Button::new("stage-all", "Stage All")
1421 .disabled(!button_states.stage_all)
1422 .tooltip(Tooltip::for_action_title_in(
1423 "Stage all changes",
1424 &StageAll,
1425 &focus_handle,
1426 ))
1427 .on_click(cx.listener(|this, _, window, cx| {
1428 this.stage_all(window, cx)
1429 })),
1430 ),
1431 )
1432 },
1433 )
1434 .child(
1435 Button::new("commit", "Commit")
1436 .tooltip(Tooltip::for_action_title_in(
1437 "Commit",
1438 &Commit,
1439 &focus_handle,
1440 ))
1441 .on_click(cx.listener(|this, _, window, cx| {
1442 this.dispatch_action(&Commit, window, cx);
1443 })),
1444 ),
1445 )
1446 // "Send Review to Agent" button (only shown when there are review comments)
1447 .when(review_count > 0, |el| {
1448 el.child(vertical_divider()).child(
1449 render_send_review_to_agent_button(review_count, &focus_handle).on_click(
1450 cx.listener(|this, _, window, cx| {
1451 this.dispatch_action(&SendReviewToAgent, window, cx)
1452 }),
1453 ),
1454 )
1455 })
1456 }
1457}
1458
1459fn render_send_review_to_agent_button(review_count: usize, focus_handle: &FocusHandle) -> Button {
1460 Button::new(
1461 "send-review",
1462 format!("Send Review to Agent ({})", review_count),
1463 )
1464 .icon(IconName::ZedAssistant)
1465 .icon_position(IconPosition::Start)
1466 .tooltip(Tooltip::for_action_title_in(
1467 "Send all review comments to the Agent panel",
1468 &SendReviewToAgent,
1469 focus_handle,
1470 ))
1471}
1472
1473pub struct BranchDiffToolbar {
1474 project_diff: Option<WeakEntity<ProjectDiff>>,
1475}
1476
1477impl BranchDiffToolbar {
1478 pub fn new(_: &mut Context<Self>) -> Self {
1479 Self { project_diff: None }
1480 }
1481
1482 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
1483 self.project_diff.as_ref()?.upgrade()
1484 }
1485
1486 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
1487 if let Some(project_diff) = self.project_diff(cx) {
1488 project_diff.focus_handle(cx).focus(window, cx);
1489 }
1490 let action = action.boxed_clone();
1491 cx.defer(move |cx| {
1492 cx.dispatch_action(action.as_ref());
1493 })
1494 }
1495}
1496
1497impl EventEmitter<ToolbarItemEvent> for BranchDiffToolbar {}
1498
1499impl ToolbarItemView for BranchDiffToolbar {
1500 fn set_active_pane_item(
1501 &mut self,
1502 active_pane_item: Option<&dyn ItemHandle>,
1503 _: &mut Window,
1504 cx: &mut Context<Self>,
1505 ) -> ToolbarItemLocation {
1506 self.project_diff = active_pane_item
1507 .and_then(|item| item.act_as::<ProjectDiff>(cx))
1508 .filter(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Merge { .. }))
1509 .map(|entity| entity.downgrade());
1510 if self.project_diff.is_some() {
1511 ToolbarItemLocation::PrimaryRight
1512 } else {
1513 ToolbarItemLocation::Hidden
1514 }
1515 }
1516
1517 fn pane_focus_update(
1518 &mut self,
1519 _pane_focused: bool,
1520 _window: &mut Window,
1521 _cx: &mut Context<Self>,
1522 ) {
1523 }
1524}
1525
1526impl Render for BranchDiffToolbar {
1527 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1528 let Some(project_diff) = self.project_diff(cx) else {
1529 return div();
1530 };
1531 let focus_handle = project_diff.focus_handle(cx);
1532 let review_count = project_diff.read(cx).total_review_comment_count();
1533
1534 h_group_xl()
1535 .my_neg_1()
1536 .py_1()
1537 .items_center()
1538 .flex_wrap()
1539 .justify_end()
1540 .when(review_count > 0, |el| {
1541 el.child(
1542 render_send_review_to_agent_button(review_count, &focus_handle).on_click(
1543 cx.listener(|this, _, window, cx| {
1544 this.dispatch_action(&SendReviewToAgent, window, cx)
1545 }),
1546 ),
1547 )
1548 })
1549 }
1550}
1551
1552#[derive(IntoElement, RegisterComponent)]
1553pub struct ProjectDiffEmptyState {
1554 pub no_repo: bool,
1555 pub can_push_and_pull: bool,
1556 pub focus_handle: Option<FocusHandle>,
1557 pub current_branch: Option<Branch>,
1558 // has_pending_commits: bool,
1559 // ahead_of_remote: bool,
1560 // no_git_repository: bool,
1561}
1562
1563impl RenderOnce for ProjectDiffEmptyState {
1564 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1565 let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
1566 matches!(self.current_branch, Some(Branch {
1567 upstream:
1568 Some(Upstream {
1569 tracking:
1570 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1571 ahead, behind, ..
1572 }),
1573 ..
1574 }),
1575 ..
1576 }) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
1577 };
1578
1579 let change_count = |current_branch: &Branch| -> (usize, usize) {
1580 match current_branch {
1581 Branch {
1582 upstream:
1583 Some(Upstream {
1584 tracking:
1585 UpstreamTracking::Tracked(UpstreamTrackingStatus {
1586 ahead, behind, ..
1587 }),
1588 ..
1589 }),
1590 ..
1591 } => (*ahead as usize, *behind as usize),
1592 _ => (0, 0),
1593 }
1594 };
1595
1596 let not_ahead_or_behind = status_against_remote(0, 0);
1597 let ahead_of_remote = status_against_remote(1, 0);
1598 let branch_not_on_remote = if let Some(branch) = self.current_branch.as_ref() {
1599 branch.upstream.is_none()
1600 } else {
1601 false
1602 };
1603
1604 let has_branch_container = |branch: &Branch| {
1605 h_flex()
1606 .max_w(px(420.))
1607 .bg(cx.theme().colors().text.opacity(0.05))
1608 .border_1()
1609 .border_color(cx.theme().colors().border)
1610 .rounded_sm()
1611 .gap_8()
1612 .px_6()
1613 .py_4()
1614 .map(|this| {
1615 if ahead_of_remote {
1616 let ahead_count = change_count(branch).0;
1617 let ahead_string = format!("{} Commits Ahead", ahead_count);
1618 this.child(
1619 v_flex()
1620 .child(Headline::new(ahead_string).size(HeadlineSize::Small))
1621 .child(
1622 Label::new(format!("Push your changes to {}", branch.name()))
1623 .color(Color::Muted),
1624 ),
1625 )
1626 .child(div().child(render_push_button(
1627 self.focus_handle,
1628 "push".into(),
1629 ahead_count as u32,
1630 )))
1631 } else if branch_not_on_remote {
1632 this.child(
1633 v_flex()
1634 .child(Headline::new("Publish Branch").size(HeadlineSize::Small))
1635 .child(
1636 Label::new(format!("Create {} on remote", branch.name()))
1637 .color(Color::Muted),
1638 ),
1639 )
1640 .child(
1641 div().child(render_publish_button(self.focus_handle, "publish".into())),
1642 )
1643 } else {
1644 this.child(Label::new("Remote status unknown").color(Color::Muted))
1645 }
1646 })
1647 };
1648
1649 v_flex().size_full().items_center().justify_center().child(
1650 v_flex()
1651 .gap_1()
1652 .when(self.no_repo, |this| {
1653 // TODO: add git init
1654 this.text_center()
1655 .child(Label::new("No Repository").color(Color::Muted))
1656 })
1657 .map(|this| {
1658 if not_ahead_or_behind && self.current_branch.is_some() {
1659 this.text_center()
1660 .child(Label::new("No Changes").color(Color::Muted))
1661 } else {
1662 this.when_some(self.current_branch.as_ref(), |this, branch| {
1663 this.child(has_branch_container(branch))
1664 })
1665 }
1666 }),
1667 )
1668 }
1669}
1670
1671mod preview {
1672 use git::repository::{
1673 Branch, CommitSummary, Upstream, UpstreamTracking, UpstreamTrackingStatus,
1674 };
1675 use ui::prelude::*;
1676
1677 use super::ProjectDiffEmptyState;
1678
1679 // View this component preview using `workspace: open component-preview`
1680 impl Component for ProjectDiffEmptyState {
1681 fn scope() -> ComponentScope {
1682 ComponentScope::VersionControl
1683 }
1684
1685 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1686 let unknown_upstream: Option<UpstreamTracking> = None;
1687 let ahead_of_upstream: Option<UpstreamTracking> = Some(
1688 UpstreamTrackingStatus {
1689 ahead: 2,
1690 behind: 0,
1691 }
1692 .into(),
1693 );
1694
1695 let not_ahead_or_behind_upstream: Option<UpstreamTracking> = Some(
1696 UpstreamTrackingStatus {
1697 ahead: 0,
1698 behind: 0,
1699 }
1700 .into(),
1701 );
1702
1703 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
1704 Branch {
1705 is_head: true,
1706 ref_name: "some-branch".into(),
1707 upstream: upstream.map(|tracking| Upstream {
1708 ref_name: "origin/some-branch".into(),
1709 tracking,
1710 }),
1711 most_recent_commit: Some(CommitSummary {
1712 sha: "abc123".into(),
1713 subject: "Modify stuff".into(),
1714 commit_timestamp: 1710932954,
1715 author_name: "John Doe".into(),
1716 has_parent: true,
1717 }),
1718 }
1719 }
1720
1721 let no_repo_state = ProjectDiffEmptyState {
1722 no_repo: true,
1723 can_push_and_pull: false,
1724 focus_handle: None,
1725 current_branch: None,
1726 };
1727
1728 let no_changes_state = ProjectDiffEmptyState {
1729 no_repo: false,
1730 can_push_and_pull: true,
1731 focus_handle: None,
1732 current_branch: Some(branch(not_ahead_or_behind_upstream)),
1733 };
1734
1735 let ahead_of_upstream_state = ProjectDiffEmptyState {
1736 no_repo: false,
1737 can_push_and_pull: true,
1738 focus_handle: None,
1739 current_branch: Some(branch(ahead_of_upstream)),
1740 };
1741
1742 let unknown_upstream_state = ProjectDiffEmptyState {
1743 no_repo: false,
1744 can_push_and_pull: true,
1745 focus_handle: None,
1746 current_branch: Some(branch(unknown_upstream)),
1747 };
1748
1749 let (width, height) = (px(480.), px(320.));
1750
1751 Some(
1752 v_flex()
1753 .gap_6()
1754 .children(vec![
1755 example_group(vec![
1756 single_example(
1757 "No Repo",
1758 div()
1759 .w(width)
1760 .h(height)
1761 .child(no_repo_state)
1762 .into_any_element(),
1763 ),
1764 single_example(
1765 "No Changes",
1766 div()
1767 .w(width)
1768 .h(height)
1769 .child(no_changes_state)
1770 .into_any_element(),
1771 ),
1772 single_example(
1773 "Unknown Upstream",
1774 div()
1775 .w(width)
1776 .h(height)
1777 .child(unknown_upstream_state)
1778 .into_any_element(),
1779 ),
1780 single_example(
1781 "Ahead of Remote",
1782 div()
1783 .w(width)
1784 .h(height)
1785 .child(ahead_of_upstream_state)
1786 .into_any_element(),
1787 ),
1788 ])
1789 .vertical(),
1790 ])
1791 .into_any_element(),
1792 )
1793 }
1794 }
1795}
1796
1797struct BranchDiffAddon {
1798 branch_diff: Entity<branch_diff::BranchDiff>,
1799}
1800
1801impl Addon for BranchDiffAddon {
1802 fn to_any(&self) -> &dyn std::any::Any {
1803 self
1804 }
1805
1806 fn override_status_for_buffer_id(
1807 &self,
1808 buffer_id: language::BufferId,
1809 cx: &App,
1810 ) -> Option<FileStatus> {
1811 self.branch_diff
1812 .read(cx)
1813 .status_for_buffer_id(buffer_id, cx)
1814 }
1815}
1816
1817#[cfg(test)]
1818mod tests {
1819 use collections::HashMap;
1820 use db::indoc;
1821 use editor::test::editor_test_context::{EditorTestContext, assert_state_with_diff};
1822 use git::status::{TrackedStatus, UnmergedStatus, UnmergedStatusCode};
1823 use gpui::TestAppContext;
1824 use project::FakeFs;
1825 use serde_json::json;
1826 use settings::SettingsStore;
1827 use std::path::Path;
1828 use unindent::Unindent as _;
1829 use util::{
1830 path,
1831 rel_path::{RelPath, rel_path},
1832 };
1833
1834 use super::*;
1835
1836 #[ctor::ctor]
1837 fn init_logger() {
1838 zlog::init_test();
1839 }
1840
1841 fn init_test(cx: &mut TestAppContext) {
1842 cx.update(|cx| {
1843 let store = SettingsStore::test(cx);
1844 cx.set_global(store);
1845 theme::init(theme::LoadThemes::JustBase, cx);
1846 editor::init(cx);
1847 crate::init(cx);
1848 });
1849 }
1850
1851 #[gpui::test]
1852 async fn test_save_after_restore(cx: &mut TestAppContext) {
1853 init_test(cx);
1854
1855 let fs = FakeFs::new(cx.executor());
1856 fs.insert_tree(
1857 path!("/project"),
1858 json!({
1859 ".git": {},
1860 "foo.txt": "FOO\n",
1861 }),
1862 )
1863 .await;
1864 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1865
1866 fs.set_head_for_repo(
1867 path!("/project/.git").as_ref(),
1868 &[("foo.txt", "foo\n".into())],
1869 "deadbeef",
1870 );
1871 fs.set_index_for_repo(
1872 path!("/project/.git").as_ref(),
1873 &[("foo.txt", "foo\n".into())],
1874 );
1875
1876 let (workspace, cx) =
1877 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1878 let diff = cx.new_window_entity(|window, cx| {
1879 ProjectDiff::new(project.clone(), workspace, window, cx)
1880 });
1881 cx.run_until_parked();
1882
1883 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).rhs_editor().clone());
1884 assert_state_with_diff(
1885 &editor,
1886 cx,
1887 &"
1888 - ˇfoo
1889 + FOO
1890 "
1891 .unindent(),
1892 );
1893
1894 editor
1895 .update_in(cx, |editor, window, cx| {
1896 editor.git_restore(&Default::default(), window, cx);
1897 editor.save(SaveOptions::default(), project.clone(), window, cx)
1898 })
1899 .await
1900 .unwrap();
1901 cx.run_until_parked();
1902
1903 assert_state_with_diff(&editor, cx, &"ˇ".unindent());
1904
1905 let text = String::from_utf8(fs.read_file_sync("/project/foo.txt").unwrap()).unwrap();
1906 assert_eq!(text, "foo\n");
1907 }
1908
1909 #[gpui::test]
1910 async fn test_scroll_to_beginning_with_deletion(cx: &mut TestAppContext) {
1911 init_test(cx);
1912
1913 let fs = FakeFs::new(cx.executor());
1914 fs.insert_tree(
1915 path!("/project"),
1916 json!({
1917 ".git": {},
1918 "bar": "BAR\n",
1919 "foo": "FOO\n",
1920 }),
1921 )
1922 .await;
1923 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1924 let (workspace, cx) =
1925 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1926 let diff = cx.new_window_entity(|window, cx| {
1927 ProjectDiff::new(project.clone(), workspace, window, cx)
1928 });
1929 cx.run_until_parked();
1930
1931 fs.set_head_and_index_for_repo(
1932 path!("/project/.git").as_ref(),
1933 &[("bar", "bar\n".into()), ("foo", "foo\n".into())],
1934 );
1935 cx.run_until_parked();
1936
1937 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1938 diff.move_to_path(
1939 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("foo").into_arc()),
1940 window,
1941 cx,
1942 );
1943 diff.editor.read(cx).rhs_editor().clone()
1944 });
1945 assert_state_with_diff(
1946 &editor,
1947 cx,
1948 &"
1949 - bar
1950 + BAR
1951
1952 - ˇfoo
1953 + FOO
1954 "
1955 .unindent(),
1956 );
1957
1958 let editor = cx.update_window_entity(&diff, |diff, window, cx| {
1959 diff.move_to_path(
1960 PathKey::with_sort_prefix(TRACKED_SORT_PREFIX, rel_path("bar").into_arc()),
1961 window,
1962 cx,
1963 );
1964 diff.editor.read(cx).rhs_editor().clone()
1965 });
1966 assert_state_with_diff(
1967 &editor,
1968 cx,
1969 &"
1970 - ˇbar
1971 + BAR
1972
1973 - foo
1974 + FOO
1975 "
1976 .unindent(),
1977 );
1978 }
1979
1980 #[gpui::test]
1981 async fn test_hunks_after_restore_then_modify(cx: &mut TestAppContext) {
1982 init_test(cx);
1983
1984 let fs = FakeFs::new(cx.executor());
1985 fs.insert_tree(
1986 path!("/project"),
1987 json!({
1988 ".git": {},
1989 "foo": "modified\n",
1990 }),
1991 )
1992 .await;
1993 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1994 let (workspace, cx) =
1995 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1996 fs.set_head_for_repo(
1997 path!("/project/.git").as_ref(),
1998 &[("foo", "original\n".into())],
1999 "deadbeef",
2000 );
2001
2002 let buffer = project
2003 .update(cx, |project, cx| {
2004 project.open_local_buffer(path!("/project/foo"), cx)
2005 })
2006 .await
2007 .unwrap();
2008 let buffer_editor = cx.new_window_entity(|window, cx| {
2009 Editor::for_buffer(buffer, Some(project.clone()), window, cx)
2010 });
2011 let diff = cx.new_window_entity(|window, cx| {
2012 ProjectDiff::new(project.clone(), workspace, window, cx)
2013 });
2014 cx.run_until_parked();
2015
2016 let diff_editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).rhs_editor().clone());
2017
2018 assert_state_with_diff(
2019 &diff_editor,
2020 cx,
2021 &"
2022 - ˇoriginal
2023 + modified
2024 "
2025 .unindent(),
2026 );
2027
2028 let prev_buffer_hunks =
2029 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2030 let snapshot = buffer_editor.snapshot(window, cx);
2031 let snapshot = &snapshot.buffer_snapshot();
2032 let prev_buffer_hunks = buffer_editor
2033 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
2034 .collect::<Vec<_>>();
2035 buffer_editor.git_restore(&Default::default(), window, cx);
2036 prev_buffer_hunks
2037 });
2038 assert_eq!(prev_buffer_hunks.len(), 1);
2039 cx.run_until_parked();
2040
2041 let new_buffer_hunks =
2042 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2043 let snapshot = buffer_editor.snapshot(window, cx);
2044 let snapshot = &snapshot.buffer_snapshot();
2045 buffer_editor
2046 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
2047 .collect::<Vec<_>>()
2048 });
2049 assert_eq!(new_buffer_hunks.as_slice(), &[]);
2050
2051 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2052 buffer_editor.set_text("different\n", window, cx);
2053 buffer_editor.save(
2054 SaveOptions {
2055 format: false,
2056 autosave: false,
2057 },
2058 project.clone(),
2059 window,
2060 cx,
2061 )
2062 })
2063 .await
2064 .unwrap();
2065
2066 cx.run_until_parked();
2067
2068 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2069 buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
2070 });
2071
2072 assert_state_with_diff(
2073 &buffer_editor,
2074 cx,
2075 &"
2076 - original
2077 + different
2078 ˇ"
2079 .unindent(),
2080 );
2081
2082 assert_state_with_diff(
2083 &diff_editor,
2084 cx,
2085 &"
2086 - ˇoriginal
2087 + different
2088 "
2089 .unindent(),
2090 );
2091 }
2092
2093 use crate::{
2094 conflict_view::resolve_conflict,
2095 project_diff::{self, ProjectDiff},
2096 };
2097
2098 #[gpui::test]
2099 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
2100 init_test(cx);
2101
2102 let fs = FakeFs::new(cx.executor());
2103 fs.insert_tree(
2104 path!("/a"),
2105 json!({
2106 ".git": {},
2107 "a.txt": "created\n",
2108 "b.txt": "really changed\n",
2109 "c.txt": "unchanged\n"
2110 }),
2111 )
2112 .await;
2113
2114 fs.set_head_and_index_for_repo(
2115 Path::new(path!("/a/.git")),
2116 &[
2117 ("b.txt", "before\n".to_string()),
2118 ("c.txt", "unchanged\n".to_string()),
2119 ("d.txt", "deleted\n".to_string()),
2120 ],
2121 );
2122
2123 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2124 let (workspace, cx) =
2125 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2126
2127 cx.run_until_parked();
2128
2129 cx.focus(&workspace);
2130 cx.update(|window, cx| {
2131 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2132 });
2133
2134 cx.run_until_parked();
2135
2136 let item = workspace.update(cx, |workspace, cx| {
2137 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2138 });
2139 cx.focus(&item);
2140 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).rhs_editor().clone());
2141
2142 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2143
2144 cx.assert_excerpts_with_selections(indoc!(
2145 "
2146 [EXCERPT]
2147 before
2148 really changed
2149 [EXCERPT]
2150 [FOLDED]
2151 [EXCERPT]
2152 ˇcreated
2153 "
2154 ));
2155
2156 cx.dispatch_action(editor::actions::GoToPreviousHunk);
2157
2158 cx.assert_excerpts_with_selections(indoc!(
2159 "
2160 [EXCERPT]
2161 before
2162 really changed
2163 [EXCERPT]
2164 ˇ[FOLDED]
2165 [EXCERPT]
2166 created
2167 "
2168 ));
2169
2170 cx.dispatch_action(editor::actions::GoToPreviousHunk);
2171
2172 cx.assert_excerpts_with_selections(indoc!(
2173 "
2174 [EXCERPT]
2175 ˇbefore
2176 really changed
2177 [EXCERPT]
2178 [FOLDED]
2179 [EXCERPT]
2180 created
2181 "
2182 ));
2183 }
2184
2185 #[gpui::test]
2186 async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
2187 init_test(cx);
2188
2189 let git_contents = indoc! {r#"
2190 #[rustfmt::skip]
2191 fn main() {
2192 let x = 0.0; // this line will be removed
2193 // 1
2194 // 2
2195 // 3
2196 let y = 0.0; // this line will be removed
2197 // 1
2198 // 2
2199 // 3
2200 let arr = [
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 0.0, // this line will be removed
2205 ];
2206 }
2207 "#};
2208 let buffer_contents = indoc! {"
2209 #[rustfmt::skip]
2210 fn main() {
2211 // 1
2212 // 2
2213 // 3
2214 // 1
2215 // 2
2216 // 3
2217 let arr = [
2218 ];
2219 }
2220 "};
2221
2222 let fs = FakeFs::new(cx.executor());
2223 fs.insert_tree(
2224 path!("/a"),
2225 json!({
2226 ".git": {},
2227 "main.rs": buffer_contents,
2228 }),
2229 )
2230 .await;
2231
2232 fs.set_head_and_index_for_repo(
2233 Path::new(path!("/a/.git")),
2234 &[("main.rs", git_contents.to_owned())],
2235 );
2236
2237 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2238 let (workspace, cx) =
2239 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2240
2241 cx.run_until_parked();
2242
2243 cx.focus(&workspace);
2244 cx.update(|window, cx| {
2245 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2246 });
2247
2248 cx.run_until_parked();
2249
2250 let item = workspace.update(cx, |workspace, cx| {
2251 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2252 });
2253 cx.focus(&item);
2254 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).rhs_editor().clone());
2255
2256 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2257
2258 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2259
2260 cx.dispatch_action(editor::actions::GoToHunk);
2261 cx.dispatch_action(editor::actions::GoToHunk);
2262 cx.dispatch_action(git::Restore);
2263 cx.dispatch_action(editor::actions::MoveToBeginning);
2264
2265 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2266 }
2267
2268 #[gpui::test]
2269 async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
2270 init_test(cx);
2271
2272 let fs = FakeFs::new(cx.executor());
2273 fs.insert_tree(
2274 path!("/project"),
2275 json!({
2276 ".git": {},
2277 "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
2278 }),
2279 )
2280 .await;
2281 fs.set_status_for_repo(
2282 Path::new(path!("/project/.git")),
2283 &[(
2284 "foo",
2285 UnmergedStatus {
2286 first_head: UnmergedStatusCode::Updated,
2287 second_head: UnmergedStatusCode::Updated,
2288 }
2289 .into(),
2290 )],
2291 );
2292 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2293 let (workspace, cx) =
2294 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2295 let diff = cx.new_window_entity(|window, cx| {
2296 ProjectDiff::new(project.clone(), workspace, window, cx)
2297 });
2298 cx.run_until_parked();
2299
2300 cx.update(|window, cx| {
2301 let editor = diff.read(cx).editor.read(cx).rhs_editor().clone();
2302 let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
2303 assert_eq!(excerpt_ids.len(), 1);
2304 let excerpt_id = excerpt_ids[0];
2305 let buffer = editor
2306 .read(cx)
2307 .buffer()
2308 .read(cx)
2309 .all_buffers()
2310 .into_iter()
2311 .next()
2312 .unwrap();
2313 let buffer_id = buffer.read(cx).remote_id();
2314 let conflict_set = diff
2315 .read(cx)
2316 .editor
2317 .read(cx)
2318 .rhs_editor()
2319 .read(cx)
2320 .addon::<ConflictAddon>()
2321 .unwrap()
2322 .conflict_set(buffer_id)
2323 .unwrap();
2324 assert!(conflict_set.read(cx).has_conflict);
2325 let snapshot = conflict_set.read(cx).snapshot();
2326 assert_eq!(snapshot.conflicts.len(), 1);
2327
2328 let ours_range = snapshot.conflicts[0].ours.clone();
2329
2330 resolve_conflict(
2331 editor.downgrade(),
2332 excerpt_id,
2333 snapshot.conflicts[0].clone(),
2334 vec![ours_range],
2335 window,
2336 cx,
2337 )
2338 })
2339 .await;
2340
2341 let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
2342 let contents = String::from_utf8(contents).unwrap();
2343 assert_eq!(contents, "ours\n");
2344 }
2345
2346 #[gpui::test]
2347 async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
2348 init_test(cx);
2349
2350 let fs = FakeFs::new(cx.executor());
2351 fs.insert_tree(
2352 path!("/project"),
2353 json!({
2354 ".git": {},
2355 "foo.txt": "
2356 one
2357 two
2358 three
2359 four
2360 five
2361 six
2362 seven
2363 eight
2364 nine
2365 ten
2366 ELEVEN
2367 twelve
2368 ".unindent()
2369 }),
2370 )
2371 .await;
2372 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2373 let (workspace, cx) =
2374 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2375 let diff = cx.new_window_entity(|window, cx| {
2376 ProjectDiff::new(project.clone(), workspace, window, cx)
2377 });
2378 cx.run_until_parked();
2379
2380 fs.set_head_and_index_for_repo(
2381 Path::new(path!("/project/.git")),
2382 &[(
2383 "foo.txt",
2384 "
2385 one
2386 two
2387 three
2388 four
2389 five
2390 six
2391 seven
2392 eight
2393 nine
2394 ten
2395 eleven
2396 twelve
2397 "
2398 .unindent(),
2399 )],
2400 );
2401 cx.run_until_parked();
2402
2403 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).rhs_editor().clone());
2404
2405 assert_state_with_diff(
2406 &editor,
2407 cx,
2408 &"
2409 ˇnine
2410 ten
2411 - eleven
2412 + ELEVEN
2413 twelve
2414 "
2415 .unindent(),
2416 );
2417
2418 // The project diff updates its excerpts when a new hunk appears in a buffer that already has a diff.
2419 let buffer = project
2420 .update(cx, |project, cx| {
2421 project.open_local_buffer(path!("/project/foo.txt"), cx)
2422 })
2423 .await
2424 .unwrap();
2425 buffer.update(cx, |buffer, cx| {
2426 buffer.edit_via_marked_text(
2427 &"
2428 one
2429 «TWO»
2430 three
2431 four
2432 five
2433 six
2434 seven
2435 eight
2436 nine
2437 ten
2438 ELEVEN
2439 twelve
2440 "
2441 .unindent(),
2442 None,
2443 cx,
2444 );
2445 });
2446 project
2447 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
2448 .await
2449 .unwrap();
2450 cx.run_until_parked();
2451
2452 assert_state_with_diff(
2453 &editor,
2454 cx,
2455 &"
2456 one
2457 - two
2458 + TWO
2459 three
2460 four
2461 five
2462 ˇnine
2463 ten
2464 - eleven
2465 + ELEVEN
2466 twelve
2467 "
2468 .unindent(),
2469 );
2470 }
2471
2472 #[gpui::test]
2473 async fn test_branch_diff(cx: &mut TestAppContext) {
2474 init_test(cx);
2475
2476 let fs = FakeFs::new(cx.executor());
2477 fs.insert_tree(
2478 path!("/project"),
2479 json!({
2480 ".git": {},
2481 "a.txt": "C",
2482 "b.txt": "new",
2483 "c.txt": "in-merge-base-and-work-tree",
2484 "d.txt": "created-in-head",
2485 }),
2486 )
2487 .await;
2488 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2489 let (workspace, cx) =
2490 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2491 let diff = cx
2492 .update(|window, cx| {
2493 ProjectDiff::new_with_default_branch(project.clone(), workspace, window, cx)
2494 })
2495 .await
2496 .unwrap();
2497 cx.run_until_parked();
2498
2499 fs.set_head_for_repo(
2500 Path::new(path!("/project/.git")),
2501 &[("a.txt", "B".into()), ("d.txt", "created-in-head".into())],
2502 "sha",
2503 );
2504 // fs.set_index_for_repo(dot_git, index_state);
2505 fs.set_merge_base_content_for_repo(
2506 Path::new(path!("/project/.git")),
2507 &[
2508 ("a.txt", "A".into()),
2509 ("c.txt", "in-merge-base-and-work-tree".into()),
2510 ],
2511 );
2512 cx.run_until_parked();
2513
2514 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).rhs_editor().clone());
2515
2516 assert_state_with_diff(
2517 &editor,
2518 cx,
2519 &"
2520 - A
2521 + ˇC
2522 + new
2523 + created-in-head"
2524 .unindent(),
2525 );
2526
2527 let statuses: HashMap<Arc<RelPath>, Option<FileStatus>> =
2528 editor.update(cx, |editor, cx| {
2529 editor
2530 .buffer()
2531 .read(cx)
2532 .all_buffers()
2533 .iter()
2534 .map(|buffer| {
2535 (
2536 buffer.read(cx).file().unwrap().path().clone(),
2537 editor.status_for_buffer_id(buffer.read(cx).remote_id(), cx),
2538 )
2539 })
2540 .collect()
2541 });
2542
2543 assert_eq!(
2544 statuses,
2545 HashMap::from_iter([
2546 (
2547 rel_path("a.txt").into_arc(),
2548 Some(FileStatus::Tracked(TrackedStatus {
2549 index_status: git::status::StatusCode::Modified,
2550 worktree_status: git::status::StatusCode::Modified
2551 }))
2552 ),
2553 (rel_path("b.txt").into_arc(), Some(FileStatus::Untracked)),
2554 (
2555 rel_path("d.txt").into_arc(),
2556 Some(FileStatus::Tracked(TrackedStatus {
2557 index_status: git::status::StatusCode::Added,
2558 worktree_status: git::status::StatusCode::Added
2559 }))
2560 )
2561 ])
2562 );
2563 }
2564
2565 #[gpui::test]
2566 async fn test_update_on_uncommit(cx: &mut TestAppContext) {
2567 init_test(cx);
2568
2569 let fs = FakeFs::new(cx.executor());
2570 fs.insert_tree(
2571 path!("/project"),
2572 json!({
2573 ".git": {},
2574 "README.md": "# My cool project\n".to_owned()
2575 }),
2576 )
2577 .await;
2578 fs.set_head_and_index_for_repo(
2579 Path::new(path!("/project/.git")),
2580 &[("README.md", "# My cool project\n".to_owned())],
2581 );
2582 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
2583 let worktree_id = project.read_with(cx, |project, cx| {
2584 project.worktrees(cx).next().unwrap().read(cx).id()
2585 });
2586 let (workspace, cx) =
2587 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2588 cx.run_until_parked();
2589
2590 let _editor = workspace
2591 .update_in(cx, |workspace, window, cx| {
2592 workspace.open_path((worktree_id, rel_path("README.md")), None, true, window, cx)
2593 })
2594 .await
2595 .unwrap()
2596 .downcast::<Editor>()
2597 .unwrap();
2598
2599 cx.focus(&workspace);
2600 cx.update(|window, cx| {
2601 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2602 });
2603 cx.run_until_parked();
2604 let item = workspace.update(cx, |workspace, cx| {
2605 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2606 });
2607 cx.focus(&item);
2608 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).rhs_editor().clone());
2609
2610 fs.set_head_and_index_for_repo(
2611 Path::new(path!("/project/.git")),
2612 &[(
2613 "README.md",
2614 "# My cool project\nDetails to come.\n".to_owned(),
2615 )],
2616 );
2617 cx.run_until_parked();
2618
2619 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2620
2621 cx.assert_excerpts_with_selections("[EXCERPT]\nˇ# My cool project\nDetails to come.\n");
2622 }
2623}