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};
16use git::{
17 Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll, UnstageAndNext,
18 repository::{Branch, RepoPath, Upstream, UpstreamTracking, UpstreamTrackingStatus},
19 status::FileStatus,
20};
21use gpui::{
22 Action, AnyElement, App, AppContext as _, AsyncWindowContext, Entity, EventEmitter,
23 FocusHandle, Focusable, Render, Subscription, Task, WeakEntity, actions,
24};
25use language::{Anchor, Buffer, Capability, OffsetRangeExt};
26use multi_buffer::{MultiBuffer, PathKey};
27use project::{
28 Project, ProjectPath,
29 git_store::{
30 Repository,
31 branch_diff::{self, BranchDiffEvent, DiffBase},
32 },
33};
34use settings::{Settings, SettingsStore};
35use smol::future::yield_now;
36use std::any::{Any, TypeId};
37use std::sync::Arc;
38use theme::ActiveTheme;
39use ui::{KeyBinding, Tooltip, prelude::*, vertical_divider};
40use util::{ResultExt as _, rel_path::RelPath};
41use workspace::{
42 CloseActiveItem, ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation,
43 ToolbarItemView, Workspace,
44 item::{Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},
45 notifications::NotifyTaskExt,
46 searchable::SearchableItemHandle,
47};
48use ztracing::instrument;
49
50actions!(
51 git,
52 [
53 /// Shows the diff between the working directory and the index.
54 Diff,
55 /// Adds files to the git staging area.
56 Add,
57 /// Shows the diff between the working directory and your default
58 /// branch (typically main or master).
59 BranchDiff,
60 LeaderAndFollower,
61 ]
62);
63
64pub struct ProjectDiff {
65 project: Entity<Project>,
66 multibuffer: Entity<MultiBuffer>,
67 branch_diff: Entity<branch_diff::BranchDiff>,
68 editor: Entity<SplittableEditor>,
69 buffer_diff_subscriptions: HashMap<Arc<RelPath>, (Entity<BufferDiff>, Subscription)>,
70 workspace: WeakEntity<Workspace>,
71 focus_handle: FocusHandle,
72 pending_scroll: Option<PathKey>,
73 review_comment_count: usize,
74 _task: Task<Result<()>>,
75 _subscription: Subscription,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum RefreshReason {
80 DiffChanged,
81 StatusesChanged,
82 EditorSaved,
83}
84
85const CONFLICT_SORT_PREFIX: u64 = 1;
86const TRACKED_SORT_PREFIX: u64 = 2;
87const NEW_SORT_PREFIX: u64 = 3;
88
89impl ProjectDiff {
90 pub(crate) fn register(workspace: &mut Workspace, cx: &mut Context<Workspace>) {
91 workspace.register_action(Self::deploy);
92 workspace.register_action(Self::deploy_branch_diff);
93 workspace.register_action(|workspace, _: &Add, window, cx| {
94 Self::deploy(workspace, &Diff, window, cx);
95 });
96 workspace::register_serializable_item::<ProjectDiff>(cx);
97 }
98
99 fn deploy(
100 workspace: &mut Workspace,
101 _: &Diff,
102 window: &mut Window,
103 cx: &mut Context<Workspace>,
104 ) {
105 Self::deploy_at(workspace, None, window, cx)
106 }
107
108 fn deploy_branch_diff(
109 workspace: &mut Workspace,
110 _: &BranchDiff,
111 window: &mut Window,
112 cx: &mut Context<Workspace>,
113 ) {
114 telemetry::event!("Git Branch Diff Opened");
115 let project = workspace.project().clone();
116
117 let existing = workspace
118 .items_of_type::<Self>(cx)
119 .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Merge { .. }));
120 if let Some(existing) = existing {
121 workspace.activate_item(&existing, true, true, window, cx);
122 return;
123 }
124 let workspace = cx.entity();
125 window
126 .spawn(cx, async move |cx| {
127 let this = cx
128 .update(|window, cx| {
129 Self::new_with_default_branch(project, workspace.clone(), window, cx)
130 })?
131 .await?;
132 workspace
133 .update_in(cx, |workspace, window, cx| {
134 workspace.add_item_to_active_pane(Box::new(this), None, true, window, cx);
135 })
136 .ok();
137 anyhow::Ok(())
138 })
139 .detach_and_notify_err(window, cx);
140 }
141
142 pub fn deploy_at(
143 workspace: &mut Workspace,
144 entry: Option<GitStatusEntry>,
145 window: &mut Window,
146 cx: &mut Context<Workspace>,
147 ) {
148 telemetry::event!(
149 "Git Diff Opened",
150 source = if entry.is_some() {
151 "Git Panel"
152 } else {
153 "Action"
154 }
155 );
156 let existing = workspace
157 .items_of_type::<Self>(cx)
158 .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Head));
159 let project_diff = if let Some(existing) = existing {
160 existing.update(cx, |project_diff, cx| {
161 project_diff.move_to_beginning(window, cx);
162 });
163
164 workspace.activate_item(&existing, true, true, window, cx);
165 existing
166 } else {
167 let workspace_handle = cx.entity();
168 let project_diff =
169 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
170 workspace.add_item_to_active_pane(
171 Box::new(project_diff.clone()),
172 None,
173 true,
174 window,
175 cx,
176 );
177 project_diff
178 };
179 if let Some(entry) = entry {
180 project_diff.update(cx, |project_diff, cx| {
181 project_diff.move_to_entry(entry, window, cx);
182 })
183 }
184 }
185
186 pub fn deploy_at_project_path(
187 workspace: &mut Workspace,
188 project_path: ProjectPath,
189 window: &mut Window,
190 cx: &mut Context<Workspace>,
191 ) {
192 telemetry::event!("Git Diff Opened", source = "Agent Panel");
193 let existing = workspace
194 .items_of_type::<Self>(cx)
195 .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Head));
196 let project_diff = if let Some(existing) = existing {
197 workspace.activate_item(&existing, true, true, window, cx);
198 existing
199 } else {
200 let workspace_handle = cx.entity();
201 let project_diff =
202 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
203 workspace.add_item_to_active_pane(
204 Box::new(project_diff.clone()),
205 None,
206 true,
207 window,
208 cx,
209 );
210 project_diff
211 };
212 project_diff.update(cx, |project_diff, cx| {
213 project_diff.move_to_project_path(&project_path, window, cx);
214 });
215 }
216
217 pub fn autoscroll(&self, cx: &mut Context<Self>) {
218 self.editor.update(cx, |editor, cx| {
219 editor.primary_editor().update(cx, |editor, cx| {
220 editor.request_autoscroll(Autoscroll::fit(), cx);
221 })
222 })
223 }
224
225 fn new_with_default_branch(
226 project: Entity<Project>,
227 workspace: Entity<Workspace>,
228 window: &mut Window,
229 cx: &mut App,
230 ) -> Task<Result<Entity<Self>>> {
231 let Some(repo) = project.read(cx).git_store().read(cx).active_repository() else {
232 return Task::ready(Err(anyhow!("No active repository")));
233 };
234 let main_branch = repo.update(cx, |repo, _| repo.default_branch(true));
235 window.spawn(cx, async move |cx| {
236 let main_branch = main_branch
237 .await??
238 .context("Could not determine default branch")?;
239
240 let branch_diff = cx.new_window_entity(|window, cx| {
241 branch_diff::BranchDiff::new(
242 DiffBase::Merge {
243 base_ref: main_branch,
244 },
245 project.clone(),
246 window,
247 cx,
248 )
249 })?;
250 cx.new_window_entity(|window, cx| {
251 Self::new_impl(branch_diff, project, workspace, window, cx)
252 })
253 })
254 }
255
256 fn new(
257 project: Entity<Project>,
258 workspace: Entity<Workspace>,
259 window: &mut Window,
260 cx: &mut Context<Self>,
261 ) -> Self {
262 let branch_diff =
263 cx.new(|cx| branch_diff::BranchDiff::new(DiffBase::Head, project.clone(), window, cx));
264 Self::new_impl(branch_diff, project, workspace, window, cx)
265 }
266
267 fn new_impl(
268 branch_diff: Entity<branch_diff::BranchDiff>,
269 project: Entity<Project>,
270 workspace: Entity<Workspace>,
271 window: &mut Window,
272 cx: &mut Context<Self>,
273 ) -> Self {
274 let focus_handle = cx.focus_handle();
275 let multibuffer = cx.new(|cx| {
276 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
277 multibuffer.set_all_diff_hunks_expanded(cx);
278 multibuffer
279 });
280
281 let editor = cx.new(|cx| {
282 let diff_display_editor = SplittableEditor::new_unsplit(
283 multibuffer.clone(),
284 project.clone(),
285 workspace.clone(),
286 window,
287 cx,
288 );
289 diff_display_editor
290 .primary_editor()
291 .update(cx, |editor, cx| {
292 editor.disable_diagnostics(cx);
293 editor.set_show_diff_review_button(true, cx);
294
295 match branch_diff.read(cx).diff_base() {
296 DiffBase::Head => {
297 editor.register_addon(GitPanelAddon {
298 workspace: workspace.downgrade(),
299 });
300 }
301 DiffBase::Merge { .. } => {
302 editor.register_addon(BranchDiffAddon {
303 branch_diff: branch_diff.clone(),
304 });
305 editor.start_temporary_diff_override();
306 editor.set_render_diff_hunk_controls(
307 Arc::new(|_, _, _, _, _, _, _, _| gpui::Empty.into_any_element()),
308 cx,
309 );
310 }
311 }
312 });
313 diff_display_editor
314 });
315 let editor_subscription = cx.subscribe_in(&editor, window, Self::handle_editor_event);
316
317 let primary_editor = editor.read(cx).primary_editor().clone();
318 let review_comment_subscription =
319 cx.subscribe(&primary_editor, |this, _editor, event: &EditorEvent, cx| {
320 if let EditorEvent::ReviewCommentsChanged { total_count } = event {
321 this.review_comment_count = *total_count;
322 cx.notify();
323 }
324 });
325
326 let branch_diff_subscription = cx.subscribe_in(
327 &branch_diff,
328 window,
329 move |this, _git_store, event, window, cx| match event {
330 BranchDiffEvent::FileListChanged => {
331 this._task = window.spawn(cx, {
332 let this = cx.weak_entity();
333 async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
334 })
335 }
336 },
337 );
338
339 let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
340 let mut was_collapse_untracked_diff =
341 GitPanelSettings::get_global(cx).collapse_untracked_diff;
342 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
343 let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
344 let is_collapse_untracked_diff =
345 GitPanelSettings::get_global(cx).collapse_untracked_diff;
346 if is_sort_by_path != was_sort_by_path
347 || is_collapse_untracked_diff != was_collapse_untracked_diff
348 {
349 this._task = {
350 window.spawn(cx, {
351 let this = cx.weak_entity();
352 async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
353 })
354 }
355 }
356 was_sort_by_path = is_sort_by_path;
357 was_collapse_untracked_diff = is_collapse_untracked_diff;
358 })
359 .detach();
360
361 let task = window.spawn(cx, {
362 let this = cx.weak_entity();
363 async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
364 });
365
366 Self {
367 project,
368 workspace: workspace.downgrade(),
369 branch_diff,
370 focus_handle,
371 editor,
372 multibuffer,
373 buffer_diff_subscriptions: Default::default(),
374 pending_scroll: None,
375 review_comment_count: 0,
376 _task: task,
377 _subscription: Subscription::join(
378 branch_diff_subscription,
379 Subscription::join(editor_subscription, review_comment_subscription),
380 ),
381 }
382 }
383
384 pub fn diff_base<'a>(&'a self, cx: &'a App) -> &'a DiffBase {
385 self.branch_diff.read(cx).diff_base()
386 }
387
388 pub fn move_to_entry(
389 &mut self,
390 entry: GitStatusEntry,
391 window: &mut Window,
392 cx: &mut Context<Self>,
393 ) {
394 let Some(git_repo) = self.branch_diff.read(cx).repo() else {
395 return;
396 };
397 let repo = git_repo.read(cx);
398 let sort_prefix = sort_prefix(repo, &entry.repo_path, entry.status, cx);
399 let path_key = PathKey::with_sort_prefix(sort_prefix, entry.repo_path.as_ref().clone());
400
401 self.move_to_path(path_key, window, cx)
402 }
403
404 pub fn move_to_project_path(
405 &mut self,
406 project_path: &ProjectPath,
407 window: &mut Window,
408 cx: &mut Context<Self>,
409 ) {
410 let Some(git_repo) = self.branch_diff.read(cx).repo() else {
411 return;
412 };
413 let Some(repo_path) = git_repo
414 .read(cx)
415 .project_path_to_repo_path(project_path, cx)
416 else {
417 return;
418 };
419 let status = git_repo
420 .read(cx)
421 .status_for_path(&repo_path)
422 .map(|entry| entry.status)
423 .unwrap_or(FileStatus::Untracked);
424 let sort_prefix = sort_prefix(&git_repo.read(cx), &repo_path, status, cx);
425 let path_key = PathKey::with_sort_prefix(sort_prefix, repo_path.as_ref().clone());
426 self.move_to_path(path_key, window, cx)
427 }
428
429 pub fn active_path(&self, cx: &App) -> Option<ProjectPath> {
430 let editor = self.editor.read(cx).last_selected_editor().read(cx);
431 let position = editor.selections.newest_anchor().head();
432 let multi_buffer = editor.buffer().read(cx);
433 let (_, buffer, _) = multi_buffer.excerpt_containing(position, cx)?;
434
435 let file = buffer.read(cx).file()?;
436 Some(ProjectPath {
437 worktree_id: file.worktree_id(cx),
438 path: file.path().clone(),
439 })
440 }
441
442 fn move_to_beginning(&mut self, window: &mut Window, cx: &mut Context<Self>) {
443 self.editor.update(cx, |editor, cx| {
444 editor.primary_editor().update(cx, |editor, cx| {
445 editor.move_to_beginning(&Default::default(), window, cx);
446 });
447 });
448 }
449
450 fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
451 if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
452 self.editor.update(cx, |editor, cx| {
453 editor.primary_editor().update(cx, |editor, cx| {
454 editor.change_selections(
455 SelectionEffects::scroll(Autoscroll::focused()),
456 window,
457 cx,
458 |s| {
459 s.select_ranges([position..position]);
460 },
461 )
462 })
463 });
464 } else {
465 self.pending_scroll = Some(path_key);
466 }
467 }
468
469 /// Returns the total count of review comments across all hunks/files.
470 pub fn total_review_comment_count(&self) -> usize {
471 self.review_comment_count
472 }
473
474 /// Returns a reference to the splittable editor.
475 pub fn editor(&self) -> &Entity<SplittableEditor> {
476 &self.editor
477 }
478
479 fn button_states(&self, cx: &App) -> ButtonStates {
480 let editor = self.editor.read(cx).primary_editor().read(cx);
481 let snapshot = self.multibuffer.read(cx).snapshot(cx);
482 let prev_next = snapshot.diff_hunks().nth(1).is_some();
483 let mut selection = true;
484
485 let mut ranges = editor
486 .selections
487 .disjoint_anchor_ranges()
488 .collect::<Vec<_>>();
489 if !ranges.iter().any(|range| range.start != range.end) {
490 selection = false;
491 if let Some((excerpt_id, _, range)) = self
492 .editor
493 .read(cx)
494 .primary_editor()
495 .read(cx)
496 .active_excerpt(cx)
497 {
498 ranges = vec![multi_buffer::Anchor::range_in_buffer(excerpt_id, range)];
499 } else {
500 ranges = Vec::default();
501 }
502 }
503 let mut has_staged_hunks = false;
504 let mut has_unstaged_hunks = false;
505 for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
506 match hunk.status.secondary {
507 DiffHunkSecondaryStatus::HasSecondaryHunk
508 | DiffHunkSecondaryStatus::SecondaryHunkAdditionPending => {
509 has_unstaged_hunks = true;
510 }
511 DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
512 has_staged_hunks = true;
513 has_unstaged_hunks = true;
514 }
515 DiffHunkSecondaryStatus::NoSecondaryHunk
516 | DiffHunkSecondaryStatus::SecondaryHunkRemovalPending => {
517 has_staged_hunks = true;
518 }
519 }
520 }
521 let mut stage_all = false;
522 let mut unstage_all = false;
523 self.workspace
524 .read_with(cx, |workspace, cx| {
525 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
526 let git_panel = git_panel.read(cx);
527 stage_all = git_panel.can_stage_all();
528 unstage_all = git_panel.can_unstage_all();
529 }
530 })
531 .ok();
532
533 ButtonStates {
534 stage: has_unstaged_hunks,
535 unstage: has_staged_hunks,
536 prev_next,
537 selection,
538 stage_all,
539 unstage_all,
540 }
541 }
542
543 fn handle_editor_event(
544 &mut self,
545 editor: &Entity<SplittableEditor>,
546 event: &EditorEvent,
547 window: &mut Window,
548 cx: &mut Context<Self>,
549 ) {
550 match event {
551 EditorEvent::SelectionsChanged { local: true } => {
552 let Some(project_path) = self.active_path(cx) else {
553 return;
554 };
555 self.workspace
556 .update(cx, |workspace, cx| {
557 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
558 git_panel.update(cx, |git_panel, cx| {
559 git_panel.select_entry_by_path(project_path, window, cx)
560 })
561 }
562 })
563 .ok();
564 }
565 EditorEvent::Saved => {
566 self._task = cx.spawn_in(window, async move |this, cx| {
567 Self::refresh(this, RefreshReason::EditorSaved, cx).await
568 });
569 }
570 _ => {}
571 }
572 if editor.focus_handle(cx).contains_focused(window, cx)
573 && self.multibuffer.read(cx).is_empty()
574 {
575 self.focus_handle.focus(window, cx)
576 }
577 }
578
579 #[instrument(skip_all)]
580 fn register_buffer(
581 &mut self,
582 path_key: PathKey,
583 file_status: FileStatus,
584 buffer: Entity<Buffer>,
585 diff: Entity<BufferDiff>,
586 window: &mut Window,
587 cx: &mut Context<Self>,
588 ) {
589 let subscription = cx.subscribe_in(&diff, window, move |this, _, _, window, cx| {
590 this._task = window.spawn(cx, {
591 let this = cx.weak_entity();
592 async |cx| Self::refresh(this, RefreshReason::DiffChanged, cx).await
593 })
594 });
595 self.buffer_diff_subscriptions
596 .insert(path_key.path.clone(), (diff.clone(), subscription));
597
598 // TODO(split-diff) we shouldn't have a conflict addon when split
599 let conflict_addon = self
600 .editor
601 .read(cx)
602 .primary_editor()
603 .read(cx)
604 .addon::<ConflictAddon>()
605 .expect("project diff editor should have a conflict addon");
606
607 let snapshot = buffer.read(cx).snapshot();
608 let diff_snapshot = diff.read(cx).snapshot(cx);
609
610 let excerpt_ranges = {
611 let diff_hunk_ranges = diff_snapshot
612 .hunks_intersecting_range(
613 Anchor::min_max_range_for_buffer(snapshot.remote_id()),
614 &snapshot,
615 )
616 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot));
617 let conflicts = conflict_addon
618 .conflict_set(snapshot.remote_id())
619 .map(|conflict_set| conflict_set.read(cx).snapshot().conflicts)
620 .unwrap_or_default();
621 let mut conflicts = conflicts
622 .iter()
623 .map(|conflict| conflict.range.to_point(&snapshot))
624 .peekable();
625
626 if conflicts.peek().is_some() {
627 conflicts.collect::<Vec<_>>()
628 } else {
629 diff_hunk_ranges.collect()
630 }
631 };
632
633 let (was_empty, is_excerpt_newly_added) = self.editor.update(cx, |editor, cx| {
634 let was_empty = editor
635 .primary_editor()
636 .read(cx)
637 .buffer()
638 .read(cx)
639 .is_empty();
640 let (_, is_newly_added) = editor.set_excerpts_for_path(
641 path_key.clone(),
642 buffer,
643 excerpt_ranges,
644 multibuffer_context_lines(cx),
645 diff,
646 cx,
647 );
648 (was_empty, is_newly_added)
649 });
650
651 self.editor.update(cx, |editor, cx| {
652 editor.primary_editor().update(cx, |editor, cx| {
653 if was_empty {
654 editor.change_selections(
655 SelectionEffects::no_scroll(),
656 window,
657 cx,
658 |selections| {
659 selections.select_ranges([
660 multi_buffer::Anchor::min()..multi_buffer::Anchor::min()
661 ])
662 },
663 );
664 }
665 if is_excerpt_newly_added
666 && (file_status.is_deleted()
667 || (file_status.is_untracked()
668 && GitPanelSettings::get_global(cx).collapse_untracked_diff))
669 {
670 editor.fold_buffer(snapshot.text.remote_id(), cx)
671 }
672 })
673 });
674
675 if self.multibuffer.read(cx).is_empty()
676 && self
677 .editor
678 .read(cx)
679 .focus_handle(cx)
680 .contains_focused(window, cx)
681 {
682 self.focus_handle.focus(window, cx);
683 } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
684 self.editor.update(cx, |editor, cx| {
685 editor.focus_handle(cx).focus(window, cx);
686 });
687 }
688 if self.pending_scroll.as_ref() == Some(&path_key) {
689 self.move_to_path(path_key, window, cx);
690 }
691 }
692
693 pub async fn refresh(
694 this: WeakEntity<Self>,
695 reason: RefreshReason,
696 cx: &mut AsyncWindowContext,
697 ) -> Result<()> {
698 let mut path_keys = Vec::new();
699 let buffers_to_load = this.update(cx, |this, cx| {
700 let (repo, buffers_to_load) = this.branch_diff.update(cx, |branch_diff, cx| {
701 let load_buffers = branch_diff.load_buffers(cx);
702 (branch_diff.repo().cloned(), load_buffers)
703 });
704 let mut previous_paths = this
705 .multibuffer
706 .read(cx)
707 .paths()
708 .cloned()
709 .collect::<HashSet<_>>();
710
711 if let Some(repo) = repo {
712 let repo = repo.read(cx);
713
714 path_keys = Vec::with_capacity(buffers_to_load.len());
715 for entry in buffers_to_load.iter() {
716 let sort_prefix = sort_prefix(&repo, &entry.repo_path, entry.file_status, cx);
717 let path_key =
718 PathKey::with_sort_prefix(sort_prefix, entry.repo_path.as_ref().clone());
719 previous_paths.remove(&path_key);
720 path_keys.push(path_key)
721 }
722 }
723
724 this.editor.update(cx, |editor, cx| {
725 for path in previous_paths {
726 if let Some(buffer) = this.multibuffer.read(cx).buffer_for_path(&path, cx) {
727 let skip = match reason {
728 RefreshReason::DiffChanged | RefreshReason::EditorSaved => {
729 buffer.read(cx).is_dirty()
730 }
731 RefreshReason::StatusesChanged => false,
732 };
733 if skip {
734 continue;
735 }
736 }
737
738 this.buffer_diff_subscriptions.remove(&path.path);
739 editor.remove_excerpts_for_path(path, cx);
740 }
741 });
742 buffers_to_load
743 })?;
744
745 for (entry, path_key) in buffers_to_load.into_iter().zip(path_keys.into_iter()) {
746 if let Some((buffer, diff)) = entry.load.await.log_err() {
747 // We might be lagging behind enough that all future entry.load futures are no longer pending.
748 // If that is the case, this task will never yield, starving the foreground thread of execution time.
749 yield_now().await;
750 cx.update(|window, cx| {
751 this.update(cx, |this, cx| {
752 let multibuffer = this.multibuffer.read(cx);
753 let skip = multibuffer.buffer(buffer.read(cx).remote_id()).is_some()
754 && multibuffer
755 .diff_for(buffer.read(cx).remote_id())
756 .is_some_and(|prev_diff| prev_diff.entity_id() == diff.entity_id())
757 && match reason {
758 RefreshReason::DiffChanged | RefreshReason::EditorSaved => {
759 buffer.read(cx).is_dirty()
760 }
761 RefreshReason::StatusesChanged => false,
762 };
763 if !skip {
764 this.register_buffer(
765 path_key,
766 entry.file_status,
767 buffer,
768 diff,
769 window,
770 cx,
771 )
772 }
773 })
774 .ok();
775 })?;
776 }
777 }
778 this.update(cx, |this, cx| {
779 this.pending_scroll.take();
780 cx.notify();
781 })?;
782
783 Ok(())
784 }
785
786 #[cfg(any(test, feature = "test-support"))]
787 pub fn excerpt_paths(&self, cx: &App) -> Vec<std::sync::Arc<util::rel_path::RelPath>> {
788 self.multibuffer
789 .read(cx)
790 .paths()
791 .map(|key| key.path.clone())
792 .collect()
793 }
794}
795
796fn sort_prefix(repo: &Repository, repo_path: &RepoPath, status: FileStatus, cx: &App) -> u64 {
797 let settings = GitPanelSettings::get_global(cx);
798
799 if settings.sort_by_path && !settings.tree_view {
800 TRACKED_SORT_PREFIX
801 } else if repo.had_conflict_on_last_merge_head_change(repo_path) {
802 CONFLICT_SORT_PREFIX
803 } else if status.is_created() {
804 NEW_SORT_PREFIX
805 } else {
806 TRACKED_SORT_PREFIX
807 }
808}
809
810impl EventEmitter<EditorEvent> for ProjectDiff {}
811
812impl Focusable for ProjectDiff {
813 fn focus_handle(&self, cx: &App) -> FocusHandle {
814 if self.multibuffer.read(cx).is_empty() {
815 self.focus_handle.clone()
816 } else {
817 self.editor.focus_handle(cx)
818 }
819 }
820}
821
822impl Item for ProjectDiff {
823 type Event = EditorEvent;
824
825 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
826 Some(Icon::new(IconName::GitBranch).color(Color::Muted))
827 }
828
829 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
830 Editor::to_item_events(event, f)
831 }
832
833 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
834 self.editor.update(cx, |editor, cx| {
835 editor.primary_editor().update(cx, |primary_editor, cx| {
836 primary_editor.deactivated(window, cx);
837 })
838 });
839 }
840
841 fn navigate(
842 &mut self,
843 data: Arc<dyn Any + Send>,
844 window: &mut Window,
845 cx: &mut Context<Self>,
846 ) -> bool {
847 self.editor.update(cx, |editor, cx| {
848 editor.primary_editor().update(cx, |primary_editor, cx| {
849 primary_editor.navigate(data, window, cx)
850 })
851 })
852 }
853
854 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
855 Some("Project Diff".into())
856 }
857
858 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
859 Label::new(self.tab_content_text(0, cx))
860 .color(if params.selected {
861 Color::Default
862 } else {
863 Color::Muted
864 })
865 .into_any_element()
866 }
867
868 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
869 match self.branch_diff.read(cx).diff_base() {
870 DiffBase::Head => "Uncommitted Changes".into(),
871 DiffBase::Merge { base_ref } => format!("Changes since {}", base_ref).into(),
872 }
873 }
874
875 fn telemetry_event_text(&self) -> Option<&'static str> {
876 Some("Project Diff Opened")
877 }
878
879 fn as_searchable(&self, _: &Entity<Self>, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
880 // TODO(split-diff) SplitEditor should be searchable
881 Some(Box::new(self.editor.read(cx).primary_editor().clone()))
882 }
883
884 fn for_each_project_item(
885 &self,
886 cx: &App,
887 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
888 ) {
889 self.editor
890 .read(cx)
891 .primary_editor()
892 .read(cx)
893 .for_each_project_item(cx, f)
894 }
895
896 fn set_nav_history(
897 &mut self,
898 nav_history: ItemNavHistory,
899 _: &mut Window,
900 cx: &mut Context<Self>,
901 ) {
902 self.editor.update(cx, |editor, cx| {
903 editor.primary_editor().update(cx, |primary_editor, _| {
904 primary_editor.set_nav_history(Some(nav_history));
905 })
906 });
907 }
908
909 fn can_split(&self) -> bool {
910 true
911 }
912
913 fn clone_on_split(
914 &self,
915 _workspace_id: Option<workspace::WorkspaceId>,
916 window: &mut Window,
917 cx: &mut Context<Self>,
918 ) -> Task<Option<Entity<Self>>>
919 where
920 Self: Sized,
921 {
922 let Some(workspace) = self.workspace.upgrade() else {
923 return Task::ready(None);
924 };
925 Task::ready(Some(cx.new(|cx| {
926 ProjectDiff::new(self.project.clone(), workspace, window, cx)
927 })))
928 }
929
930 fn is_dirty(&self, cx: &App) -> bool {
931 self.multibuffer.read(cx).is_dirty(cx)
932 }
933
934 fn has_conflict(&self, cx: &App) -> bool {
935 self.multibuffer.read(cx).has_conflict(cx)
936 }
937
938 fn can_save(&self, _: &App) -> bool {
939 true
940 }
941
942 fn save(
943 &mut self,
944 options: SaveOptions,
945 project: Entity<Project>,
946 window: &mut Window,
947 cx: &mut Context<Self>,
948 ) -> Task<Result<()>> {
949 self.editor.update(cx, |editor, cx| {
950 editor.primary_editor().update(cx, |primary_editor, cx| {
951 primary_editor.save(options, project, window, cx)
952 })
953 })
954 }
955
956 fn save_as(
957 &mut self,
958 _: Entity<Project>,
959 _: ProjectPath,
960 _window: &mut Window,
961 _: &mut Context<Self>,
962 ) -> Task<Result<()>> {
963 unreachable!()
964 }
965
966 fn reload(
967 &mut self,
968 project: Entity<Project>,
969 window: &mut Window,
970 cx: &mut Context<Self>,
971 ) -> Task<Result<()>> {
972 self.editor.update(cx, |editor, cx| {
973 editor.primary_editor().update(cx, |primary_editor, cx| {
974 primary_editor.reload(project, window, cx)
975 })
976 })
977 }
978
979 fn act_as_type<'a>(
980 &'a self,
981 type_id: TypeId,
982 self_handle: &'a Entity<Self>,
983 cx: &'a App,
984 ) -> Option<gpui::AnyEntity> {
985 if type_id == TypeId::of::<Self>() {
986 Some(self_handle.clone().into())
987 } else if type_id == TypeId::of::<Editor>() {
988 Some(self.editor.read(cx).primary_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).primary_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).primary_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).primary_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 =
2017 diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2018
2019 assert_state_with_diff(
2020 &diff_editor,
2021 cx,
2022 &"
2023 - ˇoriginal
2024 + modified
2025 "
2026 .unindent(),
2027 );
2028
2029 let prev_buffer_hunks =
2030 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2031 let snapshot = buffer_editor.snapshot(window, cx);
2032 let snapshot = &snapshot.buffer_snapshot();
2033 let prev_buffer_hunks = buffer_editor
2034 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
2035 .collect::<Vec<_>>();
2036 buffer_editor.git_restore(&Default::default(), window, cx);
2037 prev_buffer_hunks
2038 });
2039 assert_eq!(prev_buffer_hunks.len(), 1);
2040 cx.run_until_parked();
2041
2042 let new_buffer_hunks =
2043 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2044 let snapshot = buffer_editor.snapshot(window, cx);
2045 let snapshot = &snapshot.buffer_snapshot();
2046 buffer_editor
2047 .diff_hunks_in_ranges(&[editor::Anchor::min()..editor::Anchor::max()], snapshot)
2048 .collect::<Vec<_>>()
2049 });
2050 assert_eq!(new_buffer_hunks.as_slice(), &[]);
2051
2052 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2053 buffer_editor.set_text("different\n", window, cx);
2054 buffer_editor.save(
2055 SaveOptions {
2056 format: false,
2057 autosave: false,
2058 },
2059 project.clone(),
2060 window,
2061 cx,
2062 )
2063 })
2064 .await
2065 .unwrap();
2066
2067 cx.run_until_parked();
2068
2069 cx.update_window_entity(&buffer_editor, |buffer_editor, window, cx| {
2070 buffer_editor.expand_all_diff_hunks(&Default::default(), window, cx);
2071 });
2072
2073 assert_state_with_diff(
2074 &buffer_editor,
2075 cx,
2076 &"
2077 - original
2078 + different
2079 ˇ"
2080 .unindent(),
2081 );
2082
2083 assert_state_with_diff(
2084 &diff_editor,
2085 cx,
2086 &"
2087 - ˇoriginal
2088 + different
2089 "
2090 .unindent(),
2091 );
2092 }
2093
2094 use crate::{
2095 conflict_view::resolve_conflict,
2096 project_diff::{self, ProjectDiff},
2097 };
2098
2099 #[gpui::test]
2100 async fn test_go_to_prev_hunk_multibuffer(cx: &mut TestAppContext) {
2101 init_test(cx);
2102
2103 let fs = FakeFs::new(cx.executor());
2104 fs.insert_tree(
2105 path!("/a"),
2106 json!({
2107 ".git": {},
2108 "a.txt": "created\n",
2109 "b.txt": "really changed\n",
2110 "c.txt": "unchanged\n"
2111 }),
2112 )
2113 .await;
2114
2115 fs.set_head_and_index_for_repo(
2116 Path::new(path!("/a/.git")),
2117 &[
2118 ("b.txt", "before\n".to_string()),
2119 ("c.txt", "unchanged\n".to_string()),
2120 ("d.txt", "deleted\n".to_string()),
2121 ],
2122 );
2123
2124 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2125 let (workspace, cx) =
2126 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2127
2128 cx.run_until_parked();
2129
2130 cx.focus(&workspace);
2131 cx.update(|window, cx| {
2132 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2133 });
2134
2135 cx.run_until_parked();
2136
2137 let item = workspace.update(cx, |workspace, cx| {
2138 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2139 });
2140 cx.focus(&item);
2141 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2142
2143 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2144
2145 cx.assert_excerpts_with_selections(indoc!(
2146 "
2147 [EXCERPT]
2148 before
2149 really changed
2150 [EXCERPT]
2151 [FOLDED]
2152 [EXCERPT]
2153 ˇcreated
2154 "
2155 ));
2156
2157 cx.dispatch_action(editor::actions::GoToPreviousHunk);
2158
2159 cx.assert_excerpts_with_selections(indoc!(
2160 "
2161 [EXCERPT]
2162 before
2163 really changed
2164 [EXCERPT]
2165 ˇ[FOLDED]
2166 [EXCERPT]
2167 created
2168 "
2169 ));
2170
2171 cx.dispatch_action(editor::actions::GoToPreviousHunk);
2172
2173 cx.assert_excerpts_with_selections(indoc!(
2174 "
2175 [EXCERPT]
2176 ˇbefore
2177 really changed
2178 [EXCERPT]
2179 [FOLDED]
2180 [EXCERPT]
2181 created
2182 "
2183 ));
2184 }
2185
2186 #[gpui::test]
2187 async fn test_excerpts_splitting_after_restoring_the_middle_excerpt(cx: &mut TestAppContext) {
2188 init_test(cx);
2189
2190 let git_contents = indoc! {r#"
2191 #[rustfmt::skip]
2192 fn main() {
2193 let x = 0.0; // this line will be removed
2194 // 1
2195 // 2
2196 // 3
2197 let y = 0.0; // this line will be removed
2198 // 1
2199 // 2
2200 // 3
2201 let arr = [
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 0.0, // this line will be removed
2206 ];
2207 }
2208 "#};
2209 let buffer_contents = indoc! {"
2210 #[rustfmt::skip]
2211 fn main() {
2212 // 1
2213 // 2
2214 // 3
2215 // 1
2216 // 2
2217 // 3
2218 let arr = [
2219 ];
2220 }
2221 "};
2222
2223 let fs = FakeFs::new(cx.executor());
2224 fs.insert_tree(
2225 path!("/a"),
2226 json!({
2227 ".git": {},
2228 "main.rs": buffer_contents,
2229 }),
2230 )
2231 .await;
2232
2233 fs.set_head_and_index_for_repo(
2234 Path::new(path!("/a/.git")),
2235 &[("main.rs", git_contents.to_owned())],
2236 );
2237
2238 let project = Project::test(fs, [Path::new(path!("/a"))], cx).await;
2239 let (workspace, cx) =
2240 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2241
2242 cx.run_until_parked();
2243
2244 cx.focus(&workspace);
2245 cx.update(|window, cx| {
2246 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2247 });
2248
2249 cx.run_until_parked();
2250
2251 let item = workspace.update(cx, |workspace, cx| {
2252 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2253 });
2254 cx.focus(&item);
2255 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2256
2257 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2258
2259 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2260
2261 cx.dispatch_action(editor::actions::GoToHunk);
2262 cx.dispatch_action(editor::actions::GoToHunk);
2263 cx.dispatch_action(git::Restore);
2264 cx.dispatch_action(editor::actions::MoveToBeginning);
2265
2266 cx.assert_excerpts_with_selections(&format!("[EXCERPT]\nˇ{git_contents}"));
2267 }
2268
2269 #[gpui::test]
2270 async fn test_saving_resolved_conflicts(cx: &mut TestAppContext) {
2271 init_test(cx);
2272
2273 let fs = FakeFs::new(cx.executor());
2274 fs.insert_tree(
2275 path!("/project"),
2276 json!({
2277 ".git": {},
2278 "foo": "<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\n",
2279 }),
2280 )
2281 .await;
2282 fs.set_status_for_repo(
2283 Path::new(path!("/project/.git")),
2284 &[(
2285 "foo",
2286 UnmergedStatus {
2287 first_head: UnmergedStatusCode::Updated,
2288 second_head: UnmergedStatusCode::Updated,
2289 }
2290 .into(),
2291 )],
2292 );
2293 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2294 let (workspace, cx) =
2295 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2296 let diff = cx.new_window_entity(|window, cx| {
2297 ProjectDiff::new(project.clone(), workspace, window, cx)
2298 });
2299 cx.run_until_parked();
2300
2301 cx.update(|window, cx| {
2302 let editor = diff.read(cx).editor.read(cx).primary_editor().clone();
2303 let excerpt_ids = editor.read(cx).buffer().read(cx).excerpt_ids();
2304 assert_eq!(excerpt_ids.len(), 1);
2305 let excerpt_id = excerpt_ids[0];
2306 let buffer = editor
2307 .read(cx)
2308 .buffer()
2309 .read(cx)
2310 .all_buffers()
2311 .into_iter()
2312 .next()
2313 .unwrap();
2314 let buffer_id = buffer.read(cx).remote_id();
2315 let conflict_set = diff
2316 .read(cx)
2317 .editor
2318 .read(cx)
2319 .primary_editor()
2320 .read(cx)
2321 .addon::<ConflictAddon>()
2322 .unwrap()
2323 .conflict_set(buffer_id)
2324 .unwrap();
2325 assert!(conflict_set.read(cx).has_conflict);
2326 let snapshot = conflict_set.read(cx).snapshot();
2327 assert_eq!(snapshot.conflicts.len(), 1);
2328
2329 let ours_range = snapshot.conflicts[0].ours.clone();
2330
2331 resolve_conflict(
2332 editor.downgrade(),
2333 excerpt_id,
2334 snapshot.conflicts[0].clone(),
2335 vec![ours_range],
2336 window,
2337 cx,
2338 )
2339 })
2340 .await;
2341
2342 let contents = fs.read_file_sync(path!("/project/foo")).unwrap();
2343 let contents = String::from_utf8(contents).unwrap();
2344 assert_eq!(contents, "ours\n");
2345 }
2346
2347 #[gpui::test]
2348 async fn test_new_hunk_in_modified_file(cx: &mut TestAppContext) {
2349 init_test(cx);
2350
2351 let fs = FakeFs::new(cx.executor());
2352 fs.insert_tree(
2353 path!("/project"),
2354 json!({
2355 ".git": {},
2356 "foo.txt": "
2357 one
2358 two
2359 three
2360 four
2361 five
2362 six
2363 seven
2364 eight
2365 nine
2366 ten
2367 ELEVEN
2368 twelve
2369 ".unindent()
2370 }),
2371 )
2372 .await;
2373 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2374 let (workspace, cx) =
2375 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2376 let diff = cx.new_window_entity(|window, cx| {
2377 ProjectDiff::new(project.clone(), workspace, window, cx)
2378 });
2379 cx.run_until_parked();
2380
2381 fs.set_head_and_index_for_repo(
2382 Path::new(path!("/project/.git")),
2383 &[(
2384 "foo.txt",
2385 "
2386 one
2387 two
2388 three
2389 four
2390 five
2391 six
2392 seven
2393 eight
2394 nine
2395 ten
2396 eleven
2397 twelve
2398 "
2399 .unindent(),
2400 )],
2401 );
2402 cx.run_until_parked();
2403
2404 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2405
2406 assert_state_with_diff(
2407 &editor,
2408 cx,
2409 &"
2410 ˇnine
2411 ten
2412 - eleven
2413 + ELEVEN
2414 twelve
2415 "
2416 .unindent(),
2417 );
2418
2419 // The project diff updates its excerpts when a new hunk appears in a buffer that already has a diff.
2420 let buffer = project
2421 .update(cx, |project, cx| {
2422 project.open_local_buffer(path!("/project/foo.txt"), cx)
2423 })
2424 .await
2425 .unwrap();
2426 buffer.update(cx, |buffer, cx| {
2427 buffer.edit_via_marked_text(
2428 &"
2429 one
2430 «TWO»
2431 three
2432 four
2433 five
2434 six
2435 seven
2436 eight
2437 nine
2438 ten
2439 ELEVEN
2440 twelve
2441 "
2442 .unindent(),
2443 None,
2444 cx,
2445 );
2446 });
2447 project
2448 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
2449 .await
2450 .unwrap();
2451 cx.run_until_parked();
2452
2453 assert_state_with_diff(
2454 &editor,
2455 cx,
2456 &"
2457 one
2458 - two
2459 + TWO
2460 three
2461 four
2462 five
2463 ˇnine
2464 ten
2465 - eleven
2466 + ELEVEN
2467 twelve
2468 "
2469 .unindent(),
2470 );
2471 }
2472
2473 #[gpui::test]
2474 async fn test_branch_diff(cx: &mut TestAppContext) {
2475 init_test(cx);
2476
2477 let fs = FakeFs::new(cx.executor());
2478 fs.insert_tree(
2479 path!("/project"),
2480 json!({
2481 ".git": {},
2482 "a.txt": "C",
2483 "b.txt": "new",
2484 "c.txt": "in-merge-base-and-work-tree",
2485 "d.txt": "created-in-head",
2486 }),
2487 )
2488 .await;
2489 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
2490 let (workspace, cx) =
2491 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2492 let diff = cx
2493 .update(|window, cx| {
2494 ProjectDiff::new_with_default_branch(project.clone(), workspace, window, cx)
2495 })
2496 .await
2497 .unwrap();
2498 cx.run_until_parked();
2499
2500 fs.set_head_for_repo(
2501 Path::new(path!("/project/.git")),
2502 &[("a.txt", "B".into()), ("d.txt", "created-in-head".into())],
2503 "sha",
2504 );
2505 // fs.set_index_for_repo(dot_git, index_state);
2506 fs.set_merge_base_content_for_repo(
2507 Path::new(path!("/project/.git")),
2508 &[
2509 ("a.txt", "A".into()),
2510 ("c.txt", "in-merge-base-and-work-tree".into()),
2511 ],
2512 );
2513 cx.run_until_parked();
2514
2515 let editor = diff.read_with(cx, |diff, cx| diff.editor.read(cx).primary_editor().clone());
2516
2517 assert_state_with_diff(
2518 &editor,
2519 cx,
2520 &"
2521 - A
2522 + ˇC
2523 + new
2524 + created-in-head"
2525 .unindent(),
2526 );
2527
2528 let statuses: HashMap<Arc<RelPath>, Option<FileStatus>> =
2529 editor.update(cx, |editor, cx| {
2530 editor
2531 .buffer()
2532 .read(cx)
2533 .all_buffers()
2534 .iter()
2535 .map(|buffer| {
2536 (
2537 buffer.read(cx).file().unwrap().path().clone(),
2538 editor.status_for_buffer_id(buffer.read(cx).remote_id(), cx),
2539 )
2540 })
2541 .collect()
2542 });
2543
2544 assert_eq!(
2545 statuses,
2546 HashMap::from_iter([
2547 (
2548 rel_path("a.txt").into_arc(),
2549 Some(FileStatus::Tracked(TrackedStatus {
2550 index_status: git::status::StatusCode::Modified,
2551 worktree_status: git::status::StatusCode::Modified
2552 }))
2553 ),
2554 (rel_path("b.txt").into_arc(), Some(FileStatus::Untracked)),
2555 (
2556 rel_path("d.txt").into_arc(),
2557 Some(FileStatus::Tracked(TrackedStatus {
2558 index_status: git::status::StatusCode::Added,
2559 worktree_status: git::status::StatusCode::Added
2560 }))
2561 )
2562 ])
2563 );
2564 }
2565
2566 #[gpui::test]
2567 async fn test_update_on_uncommit(cx: &mut TestAppContext) {
2568 init_test(cx);
2569
2570 let fs = FakeFs::new(cx.executor());
2571 fs.insert_tree(
2572 path!("/project"),
2573 json!({
2574 ".git": {},
2575 "README.md": "# My cool project\n".to_owned()
2576 }),
2577 )
2578 .await;
2579 fs.set_head_and_index_for_repo(
2580 Path::new(path!("/project/.git")),
2581 &[("README.md", "# My cool project\n".to_owned())],
2582 );
2583 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
2584 let worktree_id = project.read_with(cx, |project, cx| {
2585 project.worktrees(cx).next().unwrap().read(cx).id()
2586 });
2587 let (workspace, cx) =
2588 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2589 cx.run_until_parked();
2590
2591 let _editor = workspace
2592 .update_in(cx, |workspace, window, cx| {
2593 workspace.open_path((worktree_id, rel_path("README.md")), None, true, window, cx)
2594 })
2595 .await
2596 .unwrap()
2597 .downcast::<Editor>()
2598 .unwrap();
2599
2600 cx.focus(&workspace);
2601 cx.update(|window, cx| {
2602 window.dispatch_action(project_diff::Diff.boxed_clone(), cx);
2603 });
2604 cx.run_until_parked();
2605 let item = workspace.update(cx, |workspace, cx| {
2606 workspace.active_item_as::<ProjectDiff>(cx).unwrap()
2607 });
2608 cx.focus(&item);
2609 let editor = item.read_with(cx, |item, cx| item.editor.read(cx).primary_editor().clone());
2610
2611 fs.set_head_and_index_for_repo(
2612 Path::new(path!("/project/.git")),
2613 &[(
2614 "README.md",
2615 "# My cool project\nDetails to come.\n".to_owned(),
2616 )],
2617 );
2618 cx.run_until_parked();
2619
2620 let mut cx = EditorTestContext::for_editor_in(editor, cx).await;
2621
2622 cx.assert_excerpts_with_selections("[EXCERPT]\nˇ# My cool project\nDetails to come.\n");
2623 }
2624}