1use crate::askpass_modal::AskPassModal;
2use crate::commit_modal::CommitModal;
3use crate::git_panel_settings::StatusStyle;
4use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};
5use crate::repository_selector::filtered_repository_entries;
6use crate::{branch_picker, render_remote_button};
7use crate::{
8 git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
9};
10use crate::{picker_prompt, project_diff, ProjectDiff};
11use anyhow::Result;
12use askpass::AskPassDelegate;
13use db::kvp::KEY_VALUE_STORE;
14use editor::commit_tooltip::CommitTooltip;
15
16use editor::{
17 scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
18 ShowScrollbar,
19};
20use futures::StreamExt as _;
21use git::repository::{
22 Branch, CommitDetails, CommitSummary, DiffType, PushOptions, Remote, RemoteCommandOutput,
23 ResetMode, Upstream, UpstreamTracking, UpstreamTrackingStatus,
24};
25use git::status::StageStatus;
26use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
27use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
28use gpui::{
29 actions, anchored, deferred, percentage, uniform_list, Action, Animation, AnimationExt as _,
30 ClickEvent, Corner, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,
31 ListHorizontalSizingBehavior, ListSizingBehavior, Modifiers, ModifiersChangedEvent,
32 MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Stateful, Subscription, Task,
33 Transformation, UniformListScrollHandle, WeakEntity,
34};
35use itertools::Itertools;
36use language::{Buffer, File};
37use language_model::{
38 LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
39};
40use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
41use multi_buffer::ExcerptInfo;
42use panel::{
43 panel_editor_container, panel_editor_style, panel_filled_button, panel_icon_button, PanelHeader,
44};
45use project::{
46 git::{GitEvent, Repository},
47 Fs, Project, ProjectPath,
48};
49use serde::{Deserialize, Serialize};
50use settings::Settings as _;
51use std::cell::RefCell;
52use std::future::Future;
53use std::path::{Path, PathBuf};
54use std::rc::Rc;
55use std::{collections::HashSet, sync::Arc, time::Duration, usize};
56use strum::{IntoEnumIterator, VariantNames};
57use time::OffsetDateTime;
58use ui::{
59 prelude::*, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState,
60 Tooltip,
61};
62use util::{maybe, post_inc, ResultExt, TryFutureExt};
63use workspace::{AppState, OpenOptions, OpenVisible};
64
65use workspace::{
66 dock::{DockPosition, Panel, PanelEvent},
67 notifications::{DetachAndPromptErr, NotificationId},
68 Toast, Workspace,
69};
70
71actions!(
72 git_panel,
73 [
74 Close,
75 ToggleFocus,
76 OpenMenu,
77 FocusEditor,
78 FocusChanges,
79 ToggleFillCoAuthors,
80 GenerateCommitMessage
81 ]
82);
83
84fn prompt<T>(
85 msg: &str,
86 detail: Option<&str>,
87 window: &mut Window,
88 cx: &mut App,
89) -> Task<anyhow::Result<T>>
90where
91 T: IntoEnumIterator + VariantNames + 'static,
92{
93 let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
94 cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
95}
96
97#[derive(strum::EnumIter, strum::VariantNames)]
98#[strum(serialize_all = "title_case")]
99enum TrashCancel {
100 Trash,
101 Cancel,
102}
103
104fn git_panel_context_menu(window: &mut Window, cx: &mut App) -> Entity<ContextMenu> {
105 ContextMenu::build(window, cx, |context_menu, _, _| {
106 context_menu
107 .action("Stage All", StageAll.boxed_clone())
108 .action("Unstage All", UnstageAll.boxed_clone())
109 .separator()
110 .action("Open Diff", project_diff::Diff.boxed_clone())
111 .separator()
112 .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
113 .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
114 })
115}
116
117const GIT_PANEL_KEY: &str = "GitPanel";
118
119const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
120
121pub fn init(cx: &mut App) {
122 cx.observe_new(
123 |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
124 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
125 workspace.toggle_panel_focus::<GitPanel>(window, cx);
126 });
127 workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
128 CommitModal::toggle(workspace, window, cx)
129 });
130 },
131 )
132 .detach();
133}
134
135#[derive(Debug, Clone)]
136pub enum Event {
137 Focus,
138}
139
140#[derive(Serialize, Deserialize)]
141struct SerializedGitPanel {
142 width: Option<Pixels>,
143}
144
145#[derive(Debug, PartialEq, Eq, Clone, Copy)]
146enum Section {
147 Conflict,
148 Tracked,
149 New,
150}
151
152#[derive(Debug, PartialEq, Eq, Clone)]
153struct GitHeaderEntry {
154 header: Section,
155}
156
157impl GitHeaderEntry {
158 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
159 let this = &self.header;
160 let status = status_entry.status;
161 match this {
162 Section::Conflict => repo.has_conflict(&status_entry.repo_path),
163 Section::Tracked => !status.is_created(),
164 Section::New => status.is_created(),
165 }
166 }
167 pub fn title(&self) -> &'static str {
168 match self.header {
169 Section::Conflict => "Conflicts",
170 Section::Tracked => "Tracked",
171 Section::New => "Untracked",
172 }
173 }
174}
175
176#[derive(Debug, PartialEq, Eq, Clone)]
177enum GitListEntry {
178 GitStatusEntry(GitStatusEntry),
179 Header(GitHeaderEntry),
180}
181
182impl GitListEntry {
183 fn status_entry(&self) -> Option<&GitStatusEntry> {
184 match self {
185 GitListEntry::GitStatusEntry(entry) => Some(entry),
186 _ => None,
187 }
188 }
189}
190
191#[derive(Debug, PartialEq, Eq, Clone)]
192pub struct GitStatusEntry {
193 pub(crate) repo_path: RepoPath,
194 pub(crate) worktree_path: Arc<Path>,
195 pub(crate) abs_path: PathBuf,
196 pub(crate) status: FileStatus,
197 pub(crate) staging: StageStatus,
198}
199
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201enum TargetStatus {
202 Staged,
203 Unstaged,
204 Reverted,
205 Unchanged,
206}
207
208struct PendingOperation {
209 finished: bool,
210 target_status: TargetStatus,
211 entries: Vec<GitStatusEntry>,
212 op_id: usize,
213}
214
215type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
216
217pub struct GitPanel {
218 remote_operation_id: u32,
219 pending_remote_operations: RemoteOperations,
220 pub(crate) active_repository: Option<Entity<Repository>>,
221 pub(crate) commit_editor: Entity<Editor>,
222 conflicted_count: usize,
223 conflicted_staged_count: usize,
224 current_modifiers: Modifiers,
225 add_coauthors: bool,
226 generate_commit_message_task: Option<Task<Option<()>>>,
227 entries: Vec<GitListEntry>,
228 single_staged_entry: Option<GitStatusEntry>,
229 single_tracked_entry: Option<GitStatusEntry>,
230 focus_handle: FocusHandle,
231 fs: Arc<dyn Fs>,
232 hide_scrollbar_task: Option<Task<()>>,
233 new_count: usize,
234 new_staged_count: usize,
235 pending: Vec<PendingOperation>,
236 pending_commit: Option<Task<()>>,
237 pending_serialization: Task<Option<()>>,
238 pub(crate) project: Entity<Project>,
239 scroll_handle: UniformListScrollHandle,
240 scrollbar_state: ScrollbarState,
241 selected_entry: Option<usize>,
242 marked_entries: Vec<usize>,
243 show_scrollbar: bool,
244 tracked_count: usize,
245 tracked_staged_count: usize,
246 update_visible_entries_task: Task<()>,
247 width: Option<Pixels>,
248 workspace: WeakEntity<Workspace>,
249 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
250 modal_open: bool,
251}
252
253struct RemoteOperationGuard {
254 id: u32,
255 pending_remote_operations: RemoteOperations,
256}
257
258impl Drop for RemoteOperationGuard {
259 fn drop(&mut self) {
260 self.pending_remote_operations.borrow_mut().remove(&self.id);
261 }
262}
263
264pub(crate) fn commit_message_editor(
265 commit_message_buffer: Entity<Buffer>,
266 placeholder: Option<&str>,
267 project: Entity<Project>,
268 in_panel: bool,
269 window: &mut Window,
270 cx: &mut Context<'_, Editor>,
271) -> Editor {
272 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
273 let max_lines = if in_panel { 6 } else { 18 };
274 let mut commit_editor = Editor::new(
275 EditorMode::AutoHeight { max_lines },
276 buffer,
277 None,
278 false,
279 window,
280 cx,
281 );
282 commit_editor.set_collaboration_hub(Box::new(project));
283 commit_editor.set_use_autoclose(false);
284 commit_editor.set_show_gutter(false, cx);
285 commit_editor.set_show_wrap_guides(false, cx);
286 commit_editor.set_show_indent_guides(false, cx);
287 let placeholder = placeholder.unwrap_or("Enter commit message");
288 commit_editor.set_placeholder_text(placeholder, cx);
289 commit_editor
290}
291
292impl GitPanel {
293 pub fn new(
294 workspace: Entity<Workspace>,
295 project: Entity<Project>,
296 app_state: Arc<AppState>,
297 window: &mut Window,
298 cx: &mut Context<Self>,
299 ) -> Self {
300 let fs = app_state.fs.clone();
301 let git_store = project.read(cx).git_store().clone();
302 let active_repository = project.read(cx).active_repository(cx);
303 let workspace = workspace.downgrade();
304
305 let focus_handle = cx.focus_handle();
306 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
307 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
308 this.hide_scrollbar(window, cx);
309 })
310 .detach();
311
312 // just to let us render a placeholder editor.
313 // Once the active git repo is set, this buffer will be replaced.
314 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
315 let commit_editor = cx.new(|cx| {
316 commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
317 });
318
319 commit_editor.update(cx, |editor, cx| {
320 editor.clear(window, cx);
321 });
322
323 let scroll_handle = UniformListScrollHandle::new();
324
325 cx.subscribe_in(
326 &git_store,
327 window,
328 move |this, git_store, event, window, cx| match event {
329 GitEvent::FileSystemUpdated => {
330 this.schedule_update(false, window, cx);
331 }
332 GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
333 this.active_repository = git_store.read(cx).active_repository();
334 this.schedule_update(true, window, cx);
335 }
336 GitEvent::IndexWriteError(error) => {
337 this.workspace
338 .update(cx, |workspace, cx| {
339 workspace.show_error(error, cx);
340 })
341 .ok();
342 }
343 },
344 )
345 .detach();
346
347 let scrollbar_state =
348 ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
349
350 let mut git_panel = Self {
351 pending_remote_operations: Default::default(),
352 remote_operation_id: 0,
353 active_repository,
354 commit_editor,
355 conflicted_count: 0,
356 conflicted_staged_count: 0,
357 current_modifiers: window.modifiers(),
358 add_coauthors: true,
359 generate_commit_message_task: None,
360 entries: Vec::new(),
361 focus_handle: cx.focus_handle(),
362 fs,
363 hide_scrollbar_task: None,
364 new_count: 0,
365 new_staged_count: 0,
366 pending: Vec::new(),
367 pending_commit: None,
368 pending_serialization: Task::ready(None),
369 single_staged_entry: None,
370 single_tracked_entry: None,
371 project,
372 scroll_handle,
373 scrollbar_state,
374 selected_entry: None,
375 marked_entries: Vec::new(),
376 show_scrollbar: false,
377 tracked_count: 0,
378 tracked_staged_count: 0,
379 update_visible_entries_task: Task::ready(()),
380 width: None,
381 context_menu: None,
382 workspace,
383 modal_open: false,
384 };
385 git_panel.schedule_update(false, window, cx);
386 git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
387 git_panel
388 }
389
390 pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
391 fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
392 where
393 F: Fn(usize) -> std::cmp::Ordering,
394 {
395 while low < high {
396 let mid = low + (high - low) / 2;
397 match is_target(mid) {
398 std::cmp::Ordering::Equal => return Some(mid),
399 std::cmp::Ordering::Less => low = mid + 1,
400 std::cmp::Ordering::Greater => high = mid,
401 }
402 }
403 None
404 }
405 if self.conflicted_count > 0 {
406 let conflicted_start = 1;
407 if let Some(ix) = binary_search(
408 conflicted_start,
409 conflicted_start + self.conflicted_count,
410 |ix| {
411 self.entries[ix]
412 .status_entry()
413 .unwrap()
414 .repo_path
415 .cmp(&path)
416 },
417 ) {
418 return Some(ix);
419 }
420 }
421 if self.tracked_count > 0 {
422 let tracked_start = if self.conflicted_count > 0 {
423 1 + self.conflicted_count
424 } else {
425 0
426 } + 1;
427 if let Some(ix) =
428 binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
429 self.entries[ix]
430 .status_entry()
431 .unwrap()
432 .repo_path
433 .cmp(&path)
434 })
435 {
436 return Some(ix);
437 }
438 }
439 if self.new_count > 0 {
440 let untracked_start = if self.conflicted_count > 0 {
441 1 + self.conflicted_count
442 } else {
443 0
444 } + if self.tracked_count > 0 {
445 1 + self.tracked_count
446 } else {
447 0
448 } + 1;
449 if let Some(ix) =
450 binary_search(untracked_start, untracked_start + self.new_count, |ix| {
451 self.entries[ix]
452 .status_entry()
453 .unwrap()
454 .repo_path
455 .cmp(&path)
456 })
457 {
458 return Some(ix);
459 }
460 }
461 None
462 }
463
464 pub fn select_entry_by_path(
465 &mut self,
466 path: ProjectPath,
467 _: &mut Window,
468 cx: &mut Context<Self>,
469 ) {
470 let Some(git_repo) = self.active_repository.as_ref() else {
471 return;
472 };
473 let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
474 return;
475 };
476 let Some(ix) = self.entry_by_path(&repo_path) else {
477 return;
478 };
479 self.selected_entry = Some(ix);
480 cx.notify();
481 }
482
483 fn start_remote_operation(&mut self) -> RemoteOperationGuard {
484 let id = post_inc(&mut self.remote_operation_id);
485 self.pending_remote_operations.borrow_mut().insert(id);
486
487 RemoteOperationGuard {
488 id,
489 pending_remote_operations: self.pending_remote_operations.clone(),
490 }
491 }
492
493 fn serialize(&mut self, cx: &mut Context<Self>) {
494 let width = self.width;
495 self.pending_serialization = cx.background_spawn(
496 async move {
497 KEY_VALUE_STORE
498 .write_kvp(
499 GIT_PANEL_KEY.into(),
500 serde_json::to_string(&SerializedGitPanel { width })?,
501 )
502 .await?;
503 anyhow::Ok(())
504 }
505 .log_err(),
506 );
507 }
508
509 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
510 self.modal_open = open;
511 cx.notify();
512 }
513
514 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
515 let mut dispatch_context = KeyContext::new_with_defaults();
516 dispatch_context.add("GitPanel");
517
518 if self.is_focused(window, cx) {
519 dispatch_context.add("menu");
520 dispatch_context.add("ChangesList");
521 }
522
523 if self.commit_editor.read(cx).is_focused(window) {
524 dispatch_context.add("CommitEditor");
525 }
526
527 dispatch_context
528 }
529
530 fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
531 window
532 .focused(cx)
533 .map_or(false, |focused| self.focus_handle == focused)
534 }
535
536 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
537 cx.emit(PanelEvent::Close);
538 }
539
540 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
541 if !self.focus_handle.contains_focused(window, cx) {
542 cx.emit(Event::Focus);
543 }
544 }
545
546 fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
547 GitPanelSettings::get_global(cx)
548 .scrollbar
549 .show
550 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
551 }
552
553 fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
554 let show = self.show_scrollbar(cx);
555 match show {
556 ShowScrollbar::Auto => true,
557 ShowScrollbar::System => true,
558 ShowScrollbar::Always => true,
559 ShowScrollbar::Never => false,
560 }
561 }
562
563 fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
564 let show = self.show_scrollbar(cx);
565 match show {
566 ShowScrollbar::Auto => true,
567 ShowScrollbar::System => cx
568 .try_global::<ScrollbarAutoHide>()
569 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
570 ShowScrollbar::Always => false,
571 ShowScrollbar::Never => true,
572 }
573 }
574
575 fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
576 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
577 if !self.should_autohide_scrollbar(cx) {
578 return;
579 }
580 self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
581 cx.background_executor()
582 .timer(SCROLLBAR_SHOW_INTERVAL)
583 .await;
584 panel
585 .update(&mut cx, |panel, cx| {
586 panel.show_scrollbar = false;
587 cx.notify();
588 })
589 .log_err();
590 }))
591 }
592
593 fn handle_modifiers_changed(
594 &mut self,
595 event: &ModifiersChangedEvent,
596 _: &mut Window,
597 cx: &mut Context<Self>,
598 ) {
599 self.current_modifiers = event.modifiers;
600 cx.notify();
601 }
602
603 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
604 if let Some(selected_entry) = self.selected_entry {
605 self.scroll_handle
606 .scroll_to_item(selected_entry, ScrollStrategy::Center);
607 }
608
609 cx.notify();
610 }
611
612 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
613 if !self.entries.is_empty() {
614 self.selected_entry = Some(1);
615 self.scroll_to_selected_entry(cx);
616 }
617 }
618
619 fn select_previous(
620 &mut self,
621 _: &SelectPrevious,
622 _window: &mut Window,
623 cx: &mut Context<Self>,
624 ) {
625 let item_count = self.entries.len();
626 if item_count == 0 {
627 return;
628 }
629
630 if let Some(selected_entry) = self.selected_entry {
631 let new_selected_entry = if selected_entry > 0 {
632 selected_entry - 1
633 } else {
634 selected_entry
635 };
636
637 if matches!(
638 self.entries.get(new_selected_entry),
639 Some(GitListEntry::Header(..))
640 ) {
641 if new_selected_entry > 0 {
642 self.selected_entry = Some(new_selected_entry - 1)
643 }
644 } else {
645 self.selected_entry = Some(new_selected_entry);
646 }
647
648 self.scroll_to_selected_entry(cx);
649 }
650
651 cx.notify();
652 }
653
654 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
655 let item_count = self.entries.len();
656 if item_count == 0 {
657 return;
658 }
659
660 if let Some(selected_entry) = self.selected_entry {
661 let new_selected_entry = if selected_entry < item_count - 1 {
662 selected_entry + 1
663 } else {
664 selected_entry
665 };
666 if matches!(
667 self.entries.get(new_selected_entry),
668 Some(GitListEntry::Header(..))
669 ) {
670 self.selected_entry = Some(new_selected_entry + 1);
671 } else {
672 self.selected_entry = Some(new_selected_entry);
673 }
674
675 self.scroll_to_selected_entry(cx);
676 }
677
678 cx.notify();
679 }
680
681 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
682 if self.entries.last().is_some() {
683 self.selected_entry = Some(self.entries.len() - 1);
684 self.scroll_to_selected_entry(cx);
685 }
686 }
687
688 pub(crate) fn editor_focus_handle(&self, cx: &mut Context<Self>) -> FocusHandle {
689 self.commit_editor.focus_handle(cx).clone()
690 }
691
692 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
693 self.commit_editor.update(cx, |editor, cx| {
694 window.focus(&editor.focus_handle(cx));
695 });
696 cx.notify();
697 }
698
699 fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
700 let have_entries = self
701 .active_repository
702 .as_ref()
703 .map_or(false, |active_repository| {
704 active_repository.read(cx).entry_count() > 0
705 });
706 if have_entries && self.selected_entry.is_none() {
707 self.selected_entry = Some(1);
708 self.scroll_to_selected_entry(cx);
709 cx.notify();
710 }
711 }
712
713 fn focus_changes_list(
714 &mut self,
715 _: &FocusChanges,
716 window: &mut Window,
717 cx: &mut Context<Self>,
718 ) {
719 self.select_first_entry_if_none(cx);
720
721 cx.focus_self(window);
722 cx.notify();
723 }
724
725 fn get_selected_entry(&self) -> Option<&GitListEntry> {
726 self.selected_entry.and_then(|i| self.entries.get(i))
727 }
728
729 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
730 maybe!({
731 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
732 let workspace = self.workspace.upgrade()?;
733 let git_repo = self.active_repository.as_ref()?;
734
735 if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
736 if let Some(project_path) = project_diff.read(cx).active_path(cx) {
737 if Some(&entry.repo_path)
738 == git_repo
739 .read(cx)
740 .project_path_to_repo_path(&project_path)
741 .as_ref()
742 {
743 project_diff.focus_handle(cx).focus(window);
744 return None;
745 }
746 }
747 };
748
749 if entry.worktree_path.starts_with("..") {
750 self.workspace
751 .update(cx, |workspace, cx| {
752 workspace
753 .open_abs_path(
754 entry.abs_path.clone(),
755 OpenOptions {
756 visible: Some(OpenVisible::All),
757 focus: Some(false),
758 ..Default::default()
759 },
760 window,
761 cx,
762 )
763 .detach_and_log_err(cx);
764 })
765 .ok();
766 } else {
767 self.workspace
768 .update(cx, |workspace, cx| {
769 ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
770 })
771 .ok();
772 self.focus_handle.focus(window);
773 }
774
775 Some(())
776 });
777 }
778
779 fn open_file(
780 &mut self,
781 _: &menu::SecondaryConfirm,
782 window: &mut Window,
783 cx: &mut Context<Self>,
784 ) {
785 maybe!({
786 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
787 let active_repo = self.active_repository.as_ref()?;
788 let path = active_repo
789 .read(cx)
790 .repo_path_to_project_path(&entry.repo_path)?;
791 if entry.status.is_deleted() {
792 return None;
793 }
794
795 self.workspace
796 .update(cx, |workspace, cx| {
797 workspace
798 .open_path_preview(path, None, false, false, true, window, cx)
799 .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
800 Some(format!("{e}"))
801 });
802 })
803 .ok()
804 });
805 }
806
807 fn revert_selected(
808 &mut self,
809 _: &git::RestoreFile,
810 window: &mut Window,
811 cx: &mut Context<Self>,
812 ) {
813 maybe!({
814 let list_entry = self.entries.get(self.selected_entry?)?.clone();
815 let entry = list_entry.status_entry()?;
816 self.revert_entry(&entry, window, cx);
817 Some(())
818 });
819 }
820
821 fn revert_entry(
822 &mut self,
823 entry: &GitStatusEntry,
824 window: &mut Window,
825 cx: &mut Context<Self>,
826 ) {
827 maybe!({
828 let active_repo = self.active_repository.clone()?;
829 let path = active_repo
830 .read(cx)
831 .repo_path_to_project_path(&entry.repo_path)?;
832 let workspace = self.workspace.clone();
833
834 if entry.status.staging().has_staged() {
835 self.change_file_stage(false, vec![entry.clone()], cx);
836 }
837 let filename = path.path.file_name()?.to_string_lossy();
838
839 if !entry.status.is_created() {
840 self.perform_checkout(vec![entry.clone()], cx);
841 } else {
842 let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
843 cx.spawn_in(window, |_, mut cx| async move {
844 match prompt.await? {
845 TrashCancel::Trash => {}
846 TrashCancel::Cancel => return Ok(()),
847 }
848 let task = workspace.update(&mut cx, |workspace, cx| {
849 workspace
850 .project()
851 .update(cx, |project, cx| project.delete_file(path, true, cx))
852 })?;
853 if let Some(task) = task {
854 task.await?;
855 }
856 Ok(())
857 })
858 .detach_and_prompt_err(
859 "Failed to trash file",
860 window,
861 cx,
862 |e, _, _| Some(format!("{e}")),
863 );
864 }
865 Some(())
866 });
867 }
868
869 fn perform_checkout(&mut self, entries: Vec<GitStatusEntry>, cx: &mut Context<Self>) {
870 let workspace = self.workspace.clone();
871 let Some(active_repository) = self.active_repository.clone() else {
872 return;
873 };
874
875 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
876 self.pending.push(PendingOperation {
877 op_id,
878 target_status: TargetStatus::Reverted,
879 entries: entries.clone(),
880 finished: false,
881 });
882 self.update_visible_entries(cx);
883 let task = cx.spawn(|_, mut cx| async move {
884 let tasks: Vec<_> = workspace.update(&mut cx, |workspace, cx| {
885 workspace.project().update(cx, |project, cx| {
886 entries
887 .iter()
888 .filter_map(|entry| {
889 let path = active_repository
890 .read(cx)
891 .repo_path_to_project_path(&entry.repo_path)?;
892 Some(project.open_buffer(path, cx))
893 })
894 .collect()
895 })
896 })?;
897
898 let buffers = futures::future::join_all(tasks).await;
899
900 active_repository
901 .update(&mut cx, |repo, _| {
902 repo.checkout_files(
903 "HEAD",
904 entries
905 .iter()
906 .map(|entries| entries.repo_path.clone())
907 .collect(),
908 )
909 })?
910 .await??;
911
912 let tasks: Vec<_> = cx.update(|cx| {
913 buffers
914 .iter()
915 .filter_map(|buffer| {
916 buffer.as_ref().ok()?.update(cx, |buffer, cx| {
917 buffer.is_dirty().then(|| buffer.reload(cx))
918 })
919 })
920 .collect()
921 })?;
922
923 futures::future::join_all(tasks).await;
924
925 Ok(())
926 });
927
928 cx.spawn(|this, mut cx| async move {
929 let result = task.await;
930
931 this.update(&mut cx, |this, cx| {
932 for pending in this.pending.iter_mut() {
933 if pending.op_id == op_id {
934 pending.finished = true;
935 if result.is_err() {
936 pending.target_status = TargetStatus::Unchanged;
937 this.update_visible_entries(cx);
938 }
939 break;
940 }
941 }
942 result
943 .map_err(|e| {
944 this.show_err_toast(e, cx);
945 })
946 .ok();
947 })
948 .ok();
949 })
950 .detach();
951 }
952
953 fn restore_tracked_files(
954 &mut self,
955 _: &RestoreTrackedFiles,
956 window: &mut Window,
957 cx: &mut Context<Self>,
958 ) {
959 let entries = self
960 .entries
961 .iter()
962 .filter_map(|entry| entry.status_entry().cloned())
963 .filter(|status_entry| !status_entry.status.is_created())
964 .collect::<Vec<_>>();
965
966 match entries.len() {
967 0 => return,
968 1 => return self.revert_entry(&entries[0], window, cx),
969 _ => {}
970 }
971 let mut details = entries
972 .iter()
973 .filter_map(|entry| entry.repo_path.0.file_name())
974 .map(|filename| filename.to_string_lossy())
975 .take(5)
976 .join("\n");
977 if entries.len() > 5 {
978 details.push_str(&format!("\nand {} more…", entries.len() - 5))
979 }
980
981 #[derive(strum::EnumIter, strum::VariantNames)]
982 #[strum(serialize_all = "title_case")]
983 enum RestoreCancel {
984 RestoreTrackedFiles,
985 Cancel,
986 }
987 let prompt = prompt(
988 "Discard changes to these files?",
989 Some(&details),
990 window,
991 cx,
992 );
993 cx.spawn(|this, mut cx| async move {
994 match prompt.await {
995 Ok(RestoreCancel::RestoreTrackedFiles) => {
996 this.update(&mut cx, |this, cx| {
997 this.perform_checkout(entries, cx);
998 })
999 .ok();
1000 }
1001 _ => {
1002 return;
1003 }
1004 }
1005 })
1006 .detach();
1007 }
1008
1009 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
1010 let workspace = self.workspace.clone();
1011 let Some(active_repo) = self.active_repository.clone() else {
1012 return;
1013 };
1014 let to_delete = self
1015 .entries
1016 .iter()
1017 .filter_map(|entry| entry.status_entry())
1018 .filter(|status_entry| status_entry.status.is_created())
1019 .cloned()
1020 .collect::<Vec<_>>();
1021
1022 match to_delete.len() {
1023 0 => return,
1024 1 => return self.revert_entry(&to_delete[0], window, cx),
1025 _ => {}
1026 };
1027
1028 let mut details = to_delete
1029 .iter()
1030 .map(|entry| {
1031 entry
1032 .repo_path
1033 .0
1034 .file_name()
1035 .map(|f| f.to_string_lossy())
1036 .unwrap_or_default()
1037 })
1038 .take(5)
1039 .join("\n");
1040
1041 if to_delete.len() > 5 {
1042 details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
1043 }
1044
1045 let prompt = prompt("Trash these files?", Some(&details), window, cx);
1046 cx.spawn_in(window, |this, mut cx| async move {
1047 match prompt.await? {
1048 TrashCancel::Trash => {}
1049 TrashCancel::Cancel => return Ok(()),
1050 }
1051 let tasks = workspace.update(&mut cx, |workspace, cx| {
1052 to_delete
1053 .iter()
1054 .filter_map(|entry| {
1055 workspace.project().update(cx, |project, cx| {
1056 let project_path = active_repo
1057 .read(cx)
1058 .repo_path_to_project_path(&entry.repo_path)?;
1059 project.delete_file(project_path, true, cx)
1060 })
1061 })
1062 .collect::<Vec<_>>()
1063 })?;
1064 let to_unstage = to_delete
1065 .into_iter()
1066 .filter(|entry| !entry.status.staging().is_fully_unstaged())
1067 .collect();
1068 this.update(&mut cx, |this, cx| {
1069 this.change_file_stage(false, to_unstage, cx)
1070 })?;
1071 for task in tasks {
1072 task.await?;
1073 }
1074 Ok(())
1075 })
1076 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1077 Some(format!("{e}"))
1078 });
1079 }
1080
1081 fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1082 let entries = self
1083 .entries
1084 .iter()
1085 .filter_map(|entry| entry.status_entry())
1086 .filter(|status_entry| status_entry.staging.has_unstaged())
1087 .cloned()
1088 .collect::<Vec<_>>();
1089 self.change_file_stage(true, entries, cx);
1090 }
1091
1092 fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1093 let entries = self
1094 .entries
1095 .iter()
1096 .filter_map(|entry| entry.status_entry())
1097 .filter(|status_entry| status_entry.staging.has_staged())
1098 .cloned()
1099 .collect::<Vec<_>>();
1100 self.change_file_stage(false, entries, cx);
1101 }
1102
1103 fn toggle_staged_for_entry(
1104 &mut self,
1105 entry: &GitListEntry,
1106 _window: &mut Window,
1107 cx: &mut Context<Self>,
1108 ) {
1109 let Some(active_repository) = self.active_repository.as_ref() else {
1110 return;
1111 };
1112 let (stage, repo_paths) = match entry {
1113 GitListEntry::GitStatusEntry(status_entry) => {
1114 if status_entry.status.staging().is_fully_staged() {
1115 (false, vec![status_entry.clone()])
1116 } else {
1117 (true, vec![status_entry.clone()])
1118 }
1119 }
1120 GitListEntry::Header(section) => {
1121 let goal_staged_state = !self.header_state(section.header).selected();
1122 let repository = active_repository.read(cx);
1123 let entries = self
1124 .entries
1125 .iter()
1126 .filter_map(|entry| entry.status_entry())
1127 .filter(|status_entry| {
1128 section.contains(&status_entry, repository)
1129 && status_entry.staging.as_bool() != Some(goal_staged_state)
1130 })
1131 .map(|status_entry| status_entry.clone())
1132 .collect::<Vec<_>>();
1133
1134 (goal_staged_state, entries)
1135 }
1136 };
1137 self.change_file_stage(stage, repo_paths, cx);
1138 }
1139
1140 fn change_file_stage(
1141 &mut self,
1142 stage: bool,
1143 entries: Vec<GitStatusEntry>,
1144 cx: &mut Context<Self>,
1145 ) {
1146 let Some(active_repository) = self.active_repository.clone() else {
1147 return;
1148 };
1149 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1150 self.pending.push(PendingOperation {
1151 op_id,
1152 target_status: if stage {
1153 TargetStatus::Staged
1154 } else {
1155 TargetStatus::Unstaged
1156 },
1157 entries: entries.clone(),
1158 finished: false,
1159 });
1160 let repository = active_repository.read(cx);
1161 self.update_counts(repository);
1162 cx.notify();
1163
1164 cx.spawn({
1165 |this, mut cx| async move {
1166 let result = cx
1167 .update(|cx| {
1168 if stage {
1169 active_repository.update(cx, |repo, cx| {
1170 let repo_paths = entries
1171 .iter()
1172 .map(|entry| entry.repo_path.clone())
1173 .collect();
1174 repo.stage_entries(repo_paths, cx)
1175 })
1176 } else {
1177 active_repository.update(cx, |repo, cx| {
1178 let repo_paths = entries
1179 .iter()
1180 .map(|entry| entry.repo_path.clone())
1181 .collect();
1182 repo.unstage_entries(repo_paths, cx)
1183 })
1184 }
1185 })?
1186 .await;
1187
1188 this.update(&mut cx, |this, cx| {
1189 for pending in this.pending.iter_mut() {
1190 if pending.op_id == op_id {
1191 pending.finished = true
1192 }
1193 }
1194 result
1195 .map_err(|e| {
1196 this.show_err_toast(e, cx);
1197 })
1198 .ok();
1199 cx.notify();
1200 })
1201 }
1202 })
1203 .detach();
1204 }
1205
1206 pub fn total_staged_count(&self) -> usize {
1207 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1208 }
1209
1210 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1211 self.commit_editor
1212 .read(cx)
1213 .buffer()
1214 .read(cx)
1215 .as_singleton()
1216 .unwrap()
1217 .clone()
1218 }
1219
1220 fn toggle_staged_for_selected(
1221 &mut self,
1222 _: &git::ToggleStaged,
1223 window: &mut Window,
1224 cx: &mut Context<Self>,
1225 ) {
1226 if let Some(selected_entry) = self.get_selected_entry().cloned() {
1227 self.toggle_staged_for_entry(&selected_entry, window, cx);
1228 }
1229 }
1230
1231 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1232 if self
1233 .commit_editor
1234 .focus_handle(cx)
1235 .contains_focused(window, cx)
1236 {
1237 telemetry::event!("Git Committed", source = "Git Panel");
1238 self.commit_changes(window, cx)
1239 } else {
1240 cx.propagate();
1241 }
1242 }
1243
1244 fn custom_or_suggested_commit_message(&self, cx: &mut Context<Self>) -> Option<String> {
1245 let message = self.commit_editor.read(cx).text(cx);
1246
1247 if !message.trim().is_empty() {
1248 return Some(message.to_string());
1249 }
1250
1251 self.suggest_commit_message()
1252 .filter(|message| !message.trim().is_empty())
1253 }
1254
1255 pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1256 let Some(active_repository) = self.active_repository.clone() else {
1257 return;
1258 };
1259 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1260 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1261 cx.spawn(|_| async move {
1262 prompt.await.ok();
1263 })
1264 .detach();
1265 };
1266
1267 if self.has_unstaged_conflicts() {
1268 error_spawn(
1269 "There are still conflicts. You must stage these before committing",
1270 window,
1271 cx,
1272 );
1273 return;
1274 }
1275
1276 let commit_message = self.custom_or_suggested_commit_message(cx);
1277
1278 let Some(mut message) = commit_message else {
1279 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1280 return;
1281 };
1282
1283 if self.add_coauthors {
1284 self.fill_co_authors(&mut message, cx);
1285 }
1286
1287 let task = if self.has_staged_changes() {
1288 // Repository serializes all git operations, so we can just send a commit immediately
1289 let commit_task = active_repository.read(cx).commit(message.into(), None);
1290 cx.background_spawn(async move { commit_task.await? })
1291 } else {
1292 let changed_files = self
1293 .entries
1294 .iter()
1295 .filter_map(|entry| entry.status_entry())
1296 .filter(|status_entry| !status_entry.status.is_created())
1297 .map(|status_entry| status_entry.repo_path.clone())
1298 .collect::<Vec<_>>();
1299
1300 if changed_files.is_empty() {
1301 error_spawn("No changes to commit", window, cx);
1302 return;
1303 }
1304
1305 let stage_task =
1306 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1307 cx.spawn(|_, mut cx| async move {
1308 stage_task.await?;
1309 let commit_task = active_repository
1310 .update(&mut cx, |repo, _| repo.commit(message.into(), None))?;
1311 commit_task.await?
1312 })
1313 };
1314 let task = cx.spawn_in(window, |this, mut cx| async move {
1315 let result = task.await;
1316 this.update_in(&mut cx, |this, window, cx| {
1317 this.pending_commit.take();
1318 match result {
1319 Ok(()) => {
1320 this.commit_editor
1321 .update(cx, |editor, cx| editor.clear(window, cx));
1322 }
1323 Err(e) => this.show_err_toast(e, cx),
1324 }
1325 })
1326 .ok();
1327 });
1328
1329 self.pending_commit = Some(task);
1330 }
1331
1332 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1333 let Some(repo) = self.active_repository.clone() else {
1334 return;
1335 };
1336 telemetry::event!("Git Uncommitted");
1337
1338 let confirmation = self.check_for_pushed_commits(window, cx);
1339 let prior_head = self.load_commit_details("HEAD", cx);
1340
1341 let task = cx.spawn_in(window, |this, mut cx| async move {
1342 let result = maybe!(async {
1343 if let Ok(true) = confirmation.await {
1344 let prior_head = prior_head.await?;
1345
1346 repo.update(&mut cx, |repo, _| repo.reset("HEAD^", ResetMode::Soft))?
1347 .await??;
1348
1349 Ok(Some(prior_head))
1350 } else {
1351 Ok(None)
1352 }
1353 })
1354 .await;
1355
1356 this.update_in(&mut cx, |this, window, cx| {
1357 this.pending_commit.take();
1358 match result {
1359 Ok(None) => {}
1360 Ok(Some(prior_commit)) => {
1361 this.commit_editor.update(cx, |editor, cx| {
1362 editor.set_text(prior_commit.message, window, cx)
1363 });
1364 }
1365 Err(e) => this.show_err_toast(e, cx),
1366 }
1367 })
1368 .ok();
1369 });
1370
1371 self.pending_commit = Some(task);
1372 }
1373
1374 fn check_for_pushed_commits(
1375 &mut self,
1376 window: &mut Window,
1377 cx: &mut Context<Self>,
1378 ) -> impl Future<Output = Result<bool, anyhow::Error>> {
1379 let repo = self.active_repository.clone();
1380 let mut cx = window.to_async(cx);
1381
1382 async move {
1383 let Some(repo) = repo else {
1384 return Err(anyhow::anyhow!("No active repository"));
1385 };
1386
1387 let pushed_to: Vec<SharedString> = repo
1388 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1389 .await??;
1390
1391 if pushed_to.is_empty() {
1392 Ok(true)
1393 } else {
1394 #[derive(strum::EnumIter, strum::VariantNames)]
1395 #[strum(serialize_all = "title_case")]
1396 enum CancelUncommit {
1397 Uncommit,
1398 Cancel,
1399 }
1400 let detail = format!(
1401 "This commit was already pushed to {}.",
1402 pushed_to.into_iter().join(", ")
1403 );
1404 let result = cx
1405 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1406 .await?;
1407
1408 match result {
1409 CancelUncommit::Cancel => Ok(false),
1410 CancelUncommit::Uncommit => Ok(true),
1411 }
1412 }
1413 }
1414 }
1415
1416 /// Suggests a commit message based on the changed files and their statuses
1417 pub fn suggest_commit_message(&self) -> Option<String> {
1418 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1419 Some(staged_entry)
1420 } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1421 Some(single_tracked_entry)
1422 } else {
1423 None
1424 }?;
1425
1426 let action_text = if git_status_entry.status.is_deleted() {
1427 Some("Delete")
1428 } else if git_status_entry.status.is_created() {
1429 Some("Create")
1430 } else if git_status_entry.status.is_modified() {
1431 Some("Update")
1432 } else {
1433 None
1434 }?;
1435
1436 let file_name = git_status_entry
1437 .repo_path
1438 .file_name()
1439 .unwrap_or_default()
1440 .to_string_lossy();
1441
1442 Some(format!("{} {}", action_text, file_name))
1443 }
1444
1445 fn generate_commit_message_action(
1446 &mut self,
1447 _: &git::GenerateCommitMessage,
1448 _window: &mut Window,
1449 cx: &mut Context<Self>,
1450 ) {
1451 self.generate_commit_message(cx);
1452 }
1453
1454 /// Generates a commit message using an LLM.
1455 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1456 if !self.can_commit() {
1457 return;
1458 }
1459
1460 let model = match current_language_model(cx) {
1461 Some(value) => value,
1462 None => return,
1463 };
1464
1465 let Some(repo) = self.active_repository.as_ref() else {
1466 return;
1467 };
1468
1469 telemetry::event!("Git Commit Message Generated");
1470
1471 let diff = repo.update(cx, |repo, cx| {
1472 if self.has_staged_changes() {
1473 repo.diff(DiffType::HeadToIndex, cx)
1474 } else {
1475 repo.diff(DiffType::HeadToWorktree, cx)
1476 }
1477 });
1478
1479 self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1480 async move {
1481 let _defer = util::defer({
1482 let mut cx = cx.clone();
1483 let this = this.clone();
1484 move || {
1485 this.update(&mut cx, |this, _cx| {
1486 this.generate_commit_message_task.take();
1487 })
1488 .ok();
1489 }
1490 });
1491
1492 let mut diff_text = diff.await??;
1493
1494 const ONE_MB: usize = 1_000_000;
1495 if diff_text.len() > ONE_MB {
1496 diff_text = diff_text.chars().take(ONE_MB).collect()
1497 }
1498
1499 let subject = this.update(&mut cx, |this, cx| {
1500 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1501 })?;
1502
1503 let text_empty = subject.trim().is_empty();
1504
1505 let content = if text_empty {
1506 format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1507 } else {
1508 format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1509 };
1510
1511 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1512
1513 let request = LanguageModelRequest {
1514 messages: vec![LanguageModelRequestMessage {
1515 role: Role::User,
1516 content: vec![content.into()],
1517 cache: false,
1518 }],
1519 tools: Vec::new(),
1520 stop: Vec::new(),
1521 temperature: None,
1522 };
1523
1524 let stream = model.stream_completion_text(request, &cx);
1525 let mut messages = stream.await?;
1526
1527 if !text_empty {
1528 this.update(&mut cx, |this, cx| {
1529 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1530 let insert_position = buffer.anchor_before(buffer.len());
1531 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1532 });
1533 })?;
1534 }
1535
1536 while let Some(message) = messages.stream.next().await {
1537 let text = message?;
1538
1539 this.update(&mut cx, |this, cx| {
1540 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1541 let insert_position = buffer.anchor_before(buffer.len());
1542 buffer.edit([(insert_position..insert_position, text)], None, cx);
1543 });
1544 })?;
1545 }
1546
1547 anyhow::Ok(())
1548 }
1549 .log_err()
1550 }));
1551 }
1552
1553 fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1554 let suggested_commit_message = self.suggest_commit_message();
1555 let placeholder_text = suggested_commit_message
1556 .as_deref()
1557 .unwrap_or("Enter commit message");
1558
1559 self.commit_editor.update(cx, |editor, cx| {
1560 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1561 });
1562
1563 cx.notify();
1564 }
1565
1566 pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1567 if !self.can_push_and_pull(cx) {
1568 return;
1569 }
1570
1571 let Some(repo) = self.active_repository.clone() else {
1572 return;
1573 };
1574 telemetry::event!("Git Fetched");
1575 let guard = self.start_remote_operation();
1576 let askpass = self.askpass_delegate("git fetch", window, cx);
1577 cx.spawn(|this, mut cx| async move {
1578 let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1579
1580 let remote_message = fetch.await?;
1581 drop(guard);
1582 this.update(&mut cx, |this, cx| {
1583 match remote_message {
1584 Ok(remote_message) => {
1585 this.show_remote_output(RemoteAction::Fetch, remote_message, cx);
1586 }
1587 Err(e) => {
1588 log::error!("Error while fetching {:?}", e);
1589 this.show_err_toast(e, cx);
1590 }
1591 }
1592
1593 anyhow::Ok(())
1594 })
1595 .ok();
1596 anyhow::Ok(())
1597 })
1598 .detach_and_log_err(cx);
1599 }
1600
1601 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1602 if !self.can_push_and_pull(cx) {
1603 return;
1604 }
1605 let Some(repo) = self.active_repository.clone() else {
1606 return;
1607 };
1608 let Some(branch) = repo.read(cx).current_branch() else {
1609 return;
1610 };
1611 telemetry::event!("Git Pulled");
1612 let branch = branch.clone();
1613 let remote = self.get_current_remote(window, cx);
1614 cx.spawn_in(window, move |this, mut cx| async move {
1615 let remote = match remote.await {
1616 Ok(Some(remote)) => remote,
1617 Ok(None) => {
1618 return Ok(());
1619 }
1620 Err(e) => {
1621 log::error!("Failed to get current remote: {}", e);
1622 this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1623 .ok();
1624 return Ok(());
1625 }
1626 };
1627
1628 let askpass = this.update_in(&mut cx, |this, window, cx| {
1629 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1630 })?;
1631
1632 let guard = this
1633 .update(&mut cx, |this, _| this.start_remote_operation())
1634 .ok();
1635
1636 let pull = repo.update(&mut cx, |repo, cx| {
1637 repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1638 })?;
1639
1640 let remote_message = pull.await?;
1641 drop(guard);
1642
1643 this.update(&mut cx, |this, cx| match remote_message {
1644 Ok(remote_message) => {
1645 this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1646 }
1647 Err(err) => {
1648 log::error!("Error while pull {:?}", err);
1649 this.show_err_toast(err, cx)
1650 }
1651 })
1652 .ok();
1653
1654 anyhow::Ok(())
1655 })
1656 .detach_and_log_err(cx);
1657 }
1658
1659 pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1660 if !self.can_push_and_pull(cx) {
1661 return;
1662 }
1663 let Some(repo) = self.active_repository.clone() else {
1664 return;
1665 };
1666 let Some(branch) = repo.read(cx).current_branch() else {
1667 return;
1668 };
1669 telemetry::event!("Git Pushed");
1670 let branch = branch.clone();
1671 let options = if force_push {
1672 PushOptions::Force
1673 } else {
1674 PushOptions::SetUpstream
1675 };
1676 let remote = self.get_current_remote(window, cx);
1677
1678 cx.spawn_in(window, move |this, mut cx| async move {
1679 let remote = match remote.await {
1680 Ok(Some(remote)) => remote,
1681 Ok(None) => {
1682 return Ok(());
1683 }
1684 Err(e) => {
1685 log::error!("Failed to get current remote: {}", e);
1686 this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1687 .ok();
1688 return Ok(());
1689 }
1690 };
1691
1692 let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1693 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1694 })?;
1695
1696 let guard = this
1697 .update(&mut cx, |this, _| this.start_remote_operation())
1698 .ok();
1699
1700 let push = repo.update(&mut cx, |repo, cx| {
1701 repo.push(
1702 branch.name.clone(),
1703 remote.name.clone(),
1704 Some(options),
1705 askpass_delegate,
1706 cx,
1707 )
1708 })?;
1709
1710 let remote_output = push.await?;
1711 drop(guard);
1712
1713 this.update(&mut cx, |this, cx| match remote_output {
1714 Ok(remote_message) => {
1715 this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1716 }
1717 Err(e) => {
1718 log::error!("Error while pushing {:?}", e);
1719 this.show_err_toast(e, cx);
1720 }
1721 })?;
1722
1723 anyhow::Ok(())
1724 })
1725 .detach_and_log_err(cx);
1726 }
1727
1728 fn askpass_delegate(
1729 &self,
1730 operation: impl Into<SharedString>,
1731 window: &mut Window,
1732 cx: &mut Context<Self>,
1733 ) -> AskPassDelegate {
1734 let this = cx.weak_entity();
1735 let operation = operation.into();
1736 let window = window.window_handle();
1737 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1738 window
1739 .update(cx, |_, window, cx| {
1740 this.update(cx, |this, cx| {
1741 this.workspace.update(cx, |workspace, cx| {
1742 workspace.toggle_modal(window, cx, |window, cx| {
1743 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1744 });
1745 })
1746 })
1747 })
1748 .ok();
1749 })
1750 }
1751
1752 fn can_push_and_pull(&self, cx: &App) -> bool {
1753 crate::can_push_and_pull(&self.project, cx)
1754 }
1755
1756 fn get_current_remote(
1757 &mut self,
1758 window: &mut Window,
1759 cx: &mut Context<Self>,
1760 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
1761 let repo = self.active_repository.clone();
1762 let workspace = self.workspace.clone();
1763 let mut cx = window.to_async(cx);
1764
1765 async move {
1766 let Some(repo) = repo else {
1767 return Err(anyhow::anyhow!("No active repository"));
1768 };
1769
1770 let mut current_remotes: Vec<Remote> = repo
1771 .update(&mut cx, |repo, _| {
1772 let Some(current_branch) = repo.current_branch() else {
1773 return Err(anyhow::anyhow!("No active branch"));
1774 };
1775
1776 Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1777 })??
1778 .await??;
1779
1780 if current_remotes.len() == 0 {
1781 return Err(anyhow::anyhow!("No active remote"));
1782 } else if current_remotes.len() == 1 {
1783 return Ok(Some(current_remotes.pop().unwrap()));
1784 } else {
1785 let current_remotes: Vec<_> = current_remotes
1786 .into_iter()
1787 .map(|remotes| remotes.name)
1788 .collect();
1789 let selection = cx
1790 .update(|window, cx| {
1791 picker_prompt::prompt(
1792 "Pick which remote to push to",
1793 current_remotes.clone(),
1794 workspace,
1795 window,
1796 cx,
1797 )
1798 })?
1799 .await?;
1800
1801 Ok(selection.map(|selection| Remote {
1802 name: current_remotes[selection].clone(),
1803 }))
1804 }
1805 }
1806 }
1807
1808 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1809 let mut new_co_authors = Vec::new();
1810 let project = self.project.read(cx);
1811
1812 let Some(room) = self
1813 .workspace
1814 .upgrade()
1815 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1816 else {
1817 return Vec::default();
1818 };
1819
1820 let room = room.read(cx);
1821
1822 for (peer_id, collaborator) in project.collaborators() {
1823 if collaborator.is_host {
1824 continue;
1825 }
1826
1827 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1828 continue;
1829 };
1830 if participant.can_write() && participant.user.email.is_some() {
1831 let email = participant.user.email.clone().unwrap();
1832
1833 new_co_authors.push((
1834 participant
1835 .user
1836 .name
1837 .clone()
1838 .unwrap_or_else(|| participant.user.github_login.clone()),
1839 email,
1840 ))
1841 }
1842 }
1843 if !project.is_local() && !project.is_read_only(cx) {
1844 if let Some(user) = room.local_participant_user(cx) {
1845 if let Some(email) = user.email.clone() {
1846 new_co_authors.push((
1847 user.name
1848 .clone()
1849 .unwrap_or_else(|| user.github_login.clone()),
1850 email.clone(),
1851 ))
1852 }
1853 }
1854 }
1855 new_co_authors
1856 }
1857
1858 fn toggle_fill_co_authors(
1859 &mut self,
1860 _: &ToggleFillCoAuthors,
1861 _: &mut Window,
1862 cx: &mut Context<Self>,
1863 ) {
1864 self.add_coauthors = !self.add_coauthors;
1865 cx.notify();
1866 }
1867
1868 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1869 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1870
1871 let existing_text = message.to_ascii_lowercase();
1872 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1873 let mut ends_with_co_authors = false;
1874 let existing_co_authors = existing_text
1875 .lines()
1876 .filter_map(|line| {
1877 let line = line.trim();
1878 if line.starts_with(&lowercase_co_author_prefix) {
1879 ends_with_co_authors = true;
1880 Some(line)
1881 } else {
1882 ends_with_co_authors = false;
1883 None
1884 }
1885 })
1886 .collect::<HashSet<_>>();
1887
1888 let new_co_authors = self
1889 .potential_co_authors(cx)
1890 .into_iter()
1891 .filter(|(_, email)| {
1892 !existing_co_authors
1893 .iter()
1894 .any(|existing| existing.contains(email.as_str()))
1895 })
1896 .collect::<Vec<_>>();
1897
1898 if new_co_authors.is_empty() {
1899 return;
1900 }
1901
1902 if !ends_with_co_authors {
1903 message.push('\n');
1904 }
1905 for (name, email) in new_co_authors {
1906 message.push('\n');
1907 message.push_str(CO_AUTHOR_PREFIX);
1908 message.push_str(&name);
1909 message.push_str(" <");
1910 message.push_str(&email);
1911 message.push('>');
1912 }
1913 message.push('\n');
1914 }
1915
1916 fn schedule_update(
1917 &mut self,
1918 clear_pending: bool,
1919 window: &mut Window,
1920 cx: &mut Context<Self>,
1921 ) {
1922 let handle = cx.entity().downgrade();
1923 self.reopen_commit_buffer(window, cx);
1924 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1925 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1926 if let Some(git_panel) = handle.upgrade() {
1927 git_panel
1928 .update_in(&mut cx, |git_panel, _, cx| {
1929 if clear_pending {
1930 git_panel.clear_pending();
1931 }
1932 git_panel.update_visible_entries(cx);
1933 git_panel.update_editor_placeholder(cx);
1934 })
1935 .ok();
1936 }
1937 });
1938 }
1939
1940 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1941 let Some(active_repo) = self.active_repository.as_ref() else {
1942 return;
1943 };
1944 let load_buffer = active_repo.update(cx, |active_repo, cx| {
1945 let project = self.project.read(cx);
1946 active_repo.open_commit_buffer(
1947 Some(project.languages().clone()),
1948 project.buffer_store().clone(),
1949 cx,
1950 )
1951 });
1952
1953 cx.spawn_in(window, |git_panel, mut cx| async move {
1954 let buffer = load_buffer.await?;
1955 git_panel.update_in(&mut cx, |git_panel, window, cx| {
1956 if git_panel
1957 .commit_editor
1958 .read(cx)
1959 .buffer()
1960 .read(cx)
1961 .as_singleton()
1962 .as_ref()
1963 != Some(&buffer)
1964 {
1965 git_panel.commit_editor = cx.new(|cx| {
1966 commit_message_editor(
1967 buffer,
1968 git_panel.suggest_commit_message().as_deref(),
1969 git_panel.project.clone(),
1970 true,
1971 window,
1972 cx,
1973 )
1974 });
1975 }
1976 })
1977 })
1978 .detach_and_log_err(cx);
1979 }
1980
1981 fn clear_pending(&mut self) {
1982 self.pending.retain(|v| !v.finished)
1983 }
1984
1985 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1986 self.entries.clear();
1987 self.single_staged_entry.take();
1988 self.single_staged_entry.take();
1989 let mut changed_entries = Vec::new();
1990 let mut new_entries = Vec::new();
1991 let mut conflict_entries = Vec::new();
1992 let mut last_staged = None;
1993 let mut staged_count = 0;
1994
1995 let Some(repo) = self.active_repository.as_ref() else {
1996 // Just clear entries if no repository is active.
1997 cx.notify();
1998 return;
1999 };
2000
2001 let repo = repo.read(cx);
2002
2003 for entry in repo.status() {
2004 let is_conflict = repo.has_conflict(&entry.repo_path);
2005 let is_new = entry.status.is_created();
2006 let staging = entry.status.staging();
2007
2008 if self.pending.iter().any(|pending| {
2009 pending.target_status == TargetStatus::Reverted
2010 && !pending.finished
2011 && pending
2012 .entries
2013 .iter()
2014 .any(|pending| pending.repo_path == entry.repo_path)
2015 }) {
2016 continue;
2017 }
2018
2019 // dot_git_abs path always has at least one component, namely .git.
2020 let abs_path = repo
2021 .dot_git_abs_path
2022 .parent()
2023 .unwrap()
2024 .join(&entry.repo_path);
2025 let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2026 let entry = GitStatusEntry {
2027 repo_path: entry.repo_path.clone(),
2028 worktree_path,
2029 abs_path,
2030 status: entry.status,
2031 staging,
2032 };
2033
2034 if staging.has_staged() {
2035 staged_count += 1;
2036 last_staged = Some(entry.clone());
2037 }
2038
2039 if is_conflict {
2040 conflict_entries.push(entry);
2041 } else if is_new {
2042 new_entries.push(entry);
2043 } else {
2044 changed_entries.push(entry);
2045 }
2046 }
2047
2048 let mut pending_staged_count = 0;
2049 let mut last_pending_staged = None;
2050 let mut pending_status_for_last_staged = None;
2051 for pending in self.pending.iter() {
2052 if pending.target_status == TargetStatus::Staged {
2053 pending_staged_count += pending.entries.len();
2054 last_pending_staged = pending.entries.iter().next().cloned();
2055 }
2056 if let Some(last_staged) = &last_staged {
2057 if pending
2058 .entries
2059 .iter()
2060 .any(|entry| entry.repo_path == last_staged.repo_path)
2061 {
2062 pending_status_for_last_staged = Some(pending.target_status);
2063 }
2064 }
2065 }
2066
2067 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2068 match pending_status_for_last_staged {
2069 Some(TargetStatus::Staged) | None => {
2070 self.single_staged_entry = last_staged;
2071 }
2072 _ => {}
2073 }
2074 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2075 self.single_staged_entry = last_pending_staged;
2076 }
2077
2078 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2079 self.single_tracked_entry = changed_entries.first().cloned();
2080 }
2081
2082 if conflict_entries.len() > 0 {
2083 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2084 header: Section::Conflict,
2085 }));
2086 self.entries.extend(
2087 conflict_entries
2088 .into_iter()
2089 .map(GitListEntry::GitStatusEntry),
2090 );
2091 }
2092
2093 if changed_entries.len() > 0 {
2094 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2095 header: Section::Tracked,
2096 }));
2097 self.entries.extend(
2098 changed_entries
2099 .into_iter()
2100 .map(GitListEntry::GitStatusEntry),
2101 );
2102 }
2103 if new_entries.len() > 0 {
2104 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2105 header: Section::New,
2106 }));
2107 self.entries
2108 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2109 }
2110
2111 self.update_counts(repo);
2112
2113 self.select_first_entry_if_none(cx);
2114
2115 cx.notify();
2116 }
2117
2118 fn header_state(&self, header_type: Section) -> ToggleState {
2119 let (staged_count, count) = match header_type {
2120 Section::New => (self.new_staged_count, self.new_count),
2121 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2122 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2123 };
2124 if staged_count == 0 {
2125 ToggleState::Unselected
2126 } else if count == staged_count {
2127 ToggleState::Selected
2128 } else {
2129 ToggleState::Indeterminate
2130 }
2131 }
2132
2133 fn update_counts(&mut self, repo: &Repository) {
2134 self.conflicted_count = 0;
2135 self.conflicted_staged_count = 0;
2136 self.new_count = 0;
2137 self.tracked_count = 0;
2138 self.new_staged_count = 0;
2139 self.tracked_staged_count = 0;
2140 for entry in &self.entries {
2141 let Some(status_entry) = entry.status_entry() else {
2142 continue;
2143 };
2144 if repo.has_conflict(&status_entry.repo_path) {
2145 self.conflicted_count += 1;
2146 if self.entry_staging(status_entry).has_staged() {
2147 self.conflicted_staged_count += 1;
2148 }
2149 } else if status_entry.status.is_created() {
2150 self.new_count += 1;
2151 if self.entry_staging(status_entry).has_staged() {
2152 self.new_staged_count += 1;
2153 }
2154 } else {
2155 self.tracked_count += 1;
2156 if self.entry_staging(status_entry).has_staged() {
2157 self.tracked_staged_count += 1;
2158 }
2159 }
2160 }
2161 }
2162
2163 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2164 for pending in self.pending.iter().rev() {
2165 if pending
2166 .entries
2167 .iter()
2168 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2169 {
2170 match pending.target_status {
2171 TargetStatus::Staged => return StageStatus::Staged,
2172 TargetStatus::Unstaged => return StageStatus::Unstaged,
2173 TargetStatus::Reverted => continue,
2174 TargetStatus::Unchanged => continue,
2175 }
2176 }
2177 }
2178 entry.staging
2179 }
2180
2181 pub(crate) fn has_staged_changes(&self) -> bool {
2182 self.tracked_staged_count > 0
2183 || self.new_staged_count > 0
2184 || self.conflicted_staged_count > 0
2185 }
2186
2187 pub(crate) fn has_unstaged_changes(&self) -> bool {
2188 self.tracked_count > self.tracked_staged_count
2189 || self.new_count > self.new_staged_count
2190 || self.conflicted_count > self.conflicted_staged_count
2191 }
2192
2193 fn has_conflicts(&self) -> bool {
2194 self.conflicted_count > 0
2195 }
2196
2197 fn has_tracked_changes(&self) -> bool {
2198 self.tracked_count > 0
2199 }
2200
2201 pub fn has_unstaged_conflicts(&self) -> bool {
2202 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2203 }
2204
2205 fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
2206 let Some(workspace) = self.workspace.upgrade() else {
2207 return;
2208 };
2209 let notif_id = NotificationId::Named("git-operation-error".into());
2210
2211 let message = e.to_string().trim().to_string();
2212 let toast;
2213 if message
2214 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2215 .next()
2216 .is_some()
2217 {
2218 return; // Hide the cancelled by user message
2219 } else {
2220 toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
2221 window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
2222 });
2223 }
2224 workspace.update(cx, |workspace, cx| {
2225 workspace.show_toast(toast, cx);
2226 });
2227 }
2228
2229 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2230 let Some(workspace) = self.workspace.upgrade() else {
2231 return;
2232 };
2233
2234 let notification_id = NotificationId::Named("git-remote-info".into());
2235
2236 workspace.update(cx, |workspace, cx| {
2237 workspace.show_notification(notification_id.clone(), cx, |cx| {
2238 let workspace = cx.weak_entity();
2239 cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
2240 });
2241 });
2242 }
2243
2244 pub fn render_spinner(&self) -> Option<impl IntoElement> {
2245 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2246 Icon::new(IconName::ArrowCircle)
2247 .size(IconSize::XSmall)
2248 .color(Color::Info)
2249 .with_animation(
2250 "arrow-circle",
2251 Animation::new(Duration::from_secs(2)).repeat(),
2252 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2253 )
2254 .into_any_element()
2255 })
2256 }
2257
2258 pub fn can_commit(&self) -> bool {
2259 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2260 }
2261
2262 pub fn can_stage_all(&self) -> bool {
2263 self.has_unstaged_changes()
2264 }
2265
2266 pub fn can_unstage_all(&self) -> bool {
2267 self.has_staged_changes()
2268 }
2269
2270 pub(crate) fn render_generate_commit_message_button(
2271 &self,
2272 cx: &Context<Self>,
2273 ) -> Option<AnyElement> {
2274 current_language_model(cx).is_some().then(|| {
2275 if self.generate_commit_message_task.is_some() {
2276 return h_flex()
2277 .gap_1()
2278 .child(
2279 Icon::new(IconName::ArrowCircle)
2280 .size(IconSize::XSmall)
2281 .color(Color::Info)
2282 .with_animation(
2283 "arrow-circle",
2284 Animation::new(Duration::from_secs(2)).repeat(),
2285 |icon, delta| {
2286 icon.transform(Transformation::rotate(percentage(delta)))
2287 },
2288 ),
2289 )
2290 .child(
2291 Label::new("Generating Commit...")
2292 .size(LabelSize::Small)
2293 .color(Color::Muted),
2294 )
2295 .into_any_element();
2296 }
2297
2298 let can_commit = self.can_commit();
2299 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2300 IconButton::new("generate-commit-message", IconName::AiEdit)
2301 .shape(ui::IconButtonShape::Square)
2302 .icon_color(Color::Muted)
2303 .tooltip(move |window, cx| {
2304 if can_commit {
2305 Tooltip::for_action_in(
2306 "Generate Commit Message",
2307 &git::GenerateCommitMessage,
2308 &editor_focus_handle,
2309 window,
2310 cx,
2311 )
2312 } else {
2313 Tooltip::simple(
2314 "You must have either staged changes or tracked files to generate a commit message",
2315 cx,
2316 )
2317 }
2318 })
2319 .disabled(!can_commit)
2320 .on_click(cx.listener(move |this, _event, _window, cx| {
2321 this.generate_commit_message(cx);
2322 }))
2323 .into_any_element()
2324 })
2325 }
2326
2327 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2328 let potential_co_authors = self.potential_co_authors(cx);
2329 if potential_co_authors.is_empty() {
2330 None
2331 } else {
2332 Some(
2333 IconButton::new("co-authors", IconName::Person)
2334 .shape(ui::IconButtonShape::Square)
2335 .icon_color(Color::Disabled)
2336 .selected_icon_color(Color::Selected)
2337 .toggle_state(self.add_coauthors)
2338 .tooltip(move |_, cx| {
2339 let title = format!(
2340 "Add co-authored-by:{}{}",
2341 if potential_co_authors.len() == 1 {
2342 ""
2343 } else {
2344 "\n"
2345 },
2346 potential_co_authors
2347 .iter()
2348 .map(|(name, email)| format!(" {} <{}>", name, email))
2349 .join("\n")
2350 );
2351 Tooltip::simple(title, cx)
2352 })
2353 .on_click(cx.listener(|this, _, _, cx| {
2354 this.add_coauthors = !this.add_coauthors;
2355 cx.notify();
2356 }))
2357 .into_any_element(),
2358 )
2359 }
2360 }
2361
2362 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2363 if self.has_unstaged_conflicts() {
2364 (false, "You must resolve conflicts before committing")
2365 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2366 (
2367 false,
2368 "You must have either staged changes or tracked files to commit",
2369 )
2370 } else if self.pending_commit.is_some() {
2371 (false, "Commit in progress")
2372 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2373 (false, "No commit message")
2374 } else if !self.has_write_access(cx) {
2375 (false, "You do not have write access to this project")
2376 } else {
2377 (true, self.commit_button_title())
2378 }
2379 }
2380
2381 pub fn commit_button_title(&self) -> &'static str {
2382 if self.has_staged_changes() {
2383 "Commit"
2384 } else {
2385 "Commit Tracked"
2386 }
2387 }
2388
2389 fn expand_commit_editor(
2390 &mut self,
2391 _: &git::ExpandCommitEditor,
2392 window: &mut Window,
2393 cx: &mut Context<Self>,
2394 ) {
2395 let workspace = self.workspace.clone();
2396 window.defer(cx, move |window, cx| {
2397 workspace
2398 .update(cx, |workspace, cx| {
2399 CommitModal::toggle(workspace, window, cx)
2400 })
2401 .ok();
2402 })
2403 }
2404
2405 pub fn render_footer(
2406 &self,
2407 window: &mut Window,
2408 cx: &mut Context<Self>,
2409 ) -> Option<impl IntoElement> {
2410 let active_repository = self.active_repository.clone()?;
2411 let (can_commit, tooltip) = self.configure_commit_button(cx);
2412 let project = self.project.clone().read(cx);
2413 let panel_editor_style = panel_editor_style(true, window, cx);
2414
2415 let enable_coauthors = self.render_co_authors(cx);
2416 let title = self.commit_button_title();
2417
2418 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2419 let commit_tooltip_focus_handle = editor_focus_handle.clone();
2420 let expand_tooltip_focus_handle = editor_focus_handle.clone();
2421
2422 let branch = active_repository.read(cx).current_branch().cloned();
2423
2424 let footer_size = px(32.);
2425 let gap = px(8.0);
2426 let max_height = window.line_height() * 5. + gap + footer_size;
2427
2428 let git_panel = cx.entity().clone();
2429 let display_name = SharedString::from(Arc::from(
2430 active_repository
2431 .read(cx)
2432 .display_name(project, cx)
2433 .trim_end_matches("/"),
2434 ));
2435
2436 let footer = v_flex()
2437 .child(PanelRepoFooter::new(
2438 "footer-button",
2439 display_name,
2440 branch,
2441 Some(git_panel),
2442 ))
2443 .child(
2444 panel_editor_container(window, cx)
2445 .id("commit-editor-container")
2446 .relative()
2447 .h(max_height)
2448 .w_full()
2449 .border_t_1()
2450 .border_color(cx.theme().colors().border_variant)
2451 .bg(cx.theme().colors().editor_background)
2452 .cursor_text()
2453 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2454 window.focus(&this.commit_editor.focus_handle(cx));
2455 }))
2456 .child(
2457 h_flex()
2458 .id("commit-footer")
2459 .absolute()
2460 .bottom_0()
2461 .left_0()
2462 .w_full()
2463 .px_2()
2464 .h(footer_size)
2465 .flex_none()
2466 .justify_between()
2467 .child(
2468 self.render_generate_commit_message_button(cx)
2469 .unwrap_or_else(|| div().into_any_element()),
2470 )
2471 .child(
2472 h_flex().gap_0p5().children(enable_coauthors).child(
2473 panel_filled_button(title)
2474 .tooltip(move |window, cx| {
2475 if can_commit {
2476 Tooltip::for_action_in(
2477 tooltip,
2478 &Commit,
2479 &commit_tooltip_focus_handle,
2480 window,
2481 cx,
2482 )
2483 } else {
2484 Tooltip::simple(tooltip, cx)
2485 }
2486 })
2487 .disabled(!can_commit || self.modal_open)
2488 .on_click({
2489 cx.listener(move |this, _: &ClickEvent, window, cx| {
2490 this.commit_changes(window, cx)
2491 })
2492 }),
2493 ),
2494 ),
2495 )
2496 .child(
2497 div()
2498 .pr_2p5()
2499 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2500 )
2501 .child(
2502 h_flex()
2503 .absolute()
2504 .top_2()
2505 .right_2()
2506 .opacity(0.5)
2507 .hover(|this| this.opacity(1.0))
2508 .child(
2509 panel_icon_button("expand-commit-editor", IconName::Maximize)
2510 .icon_size(IconSize::Small)
2511 .size(ui::ButtonSize::Default)
2512 .tooltip(move |window, cx| {
2513 Tooltip::for_action_in(
2514 "Open Commit Modal",
2515 &git::ExpandCommitEditor,
2516 &expand_tooltip_focus_handle,
2517 window,
2518 cx,
2519 )
2520 })
2521 .on_click(cx.listener({
2522 move |_, _, window, cx| {
2523 window.dispatch_action(
2524 git::ExpandCommitEditor.boxed_clone(),
2525 cx,
2526 )
2527 }
2528 })),
2529 ),
2530 ),
2531 );
2532
2533 Some(footer)
2534 }
2535
2536 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2537 let active_repository = self.active_repository.as_ref()?;
2538 let branch = active_repository.read(cx).current_branch()?;
2539 let commit = branch.most_recent_commit.as_ref()?.clone();
2540
2541 let this = cx.entity();
2542 Some(
2543 h_flex()
2544 .items_center()
2545 .py_2()
2546 .px(px(8.))
2547 // .bg(cx.theme().colors().background)
2548 // .border_t_1()
2549 .border_color(cx.theme().colors().border)
2550 .gap_1p5()
2551 .child(
2552 div()
2553 .flex_grow()
2554 .overflow_hidden()
2555 .max_w(relative(0.6))
2556 .h_full()
2557 .child(
2558 Label::new(commit.subject.clone())
2559 .size(LabelSize::Small)
2560 .truncate(),
2561 )
2562 .id("commit-msg-hover")
2563 .hoverable_tooltip(move |window, cx| {
2564 GitPanelMessageTooltip::new(
2565 this.clone(),
2566 commit.sha.clone(),
2567 window,
2568 cx,
2569 )
2570 .into()
2571 }),
2572 )
2573 .child(div().flex_1())
2574 .when(commit.has_parent, |this| {
2575 let has_unstaged = self.has_unstaged_changes();
2576 this.child(
2577 panel_icon_button("undo", IconName::Undo)
2578 .icon_size(IconSize::Small)
2579 .icon_color(Color::Muted)
2580 .tooltip(move |window, cx| {
2581 Tooltip::with_meta(
2582 "Uncommit",
2583 Some(&git::Uncommit),
2584 if has_unstaged {
2585 "git reset HEAD^ --soft"
2586 } else {
2587 "git reset HEAD^"
2588 },
2589 window,
2590 cx,
2591 )
2592 })
2593 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2594 )
2595 }),
2596 )
2597 }
2598
2599 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2600 h_flex()
2601 .h_full()
2602 .flex_grow()
2603 .justify_center()
2604 .items_center()
2605 .child(
2606 v_flex()
2607 .gap_3()
2608 .child(if self.active_repository.is_some() {
2609 "No changes to commit"
2610 } else {
2611 "No Git repositories"
2612 })
2613 .text_ui_sm(cx)
2614 .mx_auto()
2615 .text_color(Color::Placeholder.color(cx)),
2616 )
2617 }
2618
2619 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2620 let scroll_bar_style = self.show_scrollbar(cx);
2621 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2622
2623 if !self.should_show_scrollbar(cx)
2624 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2625 {
2626 return None;
2627 }
2628
2629 Some(
2630 div()
2631 .id("git-panel-vertical-scroll")
2632 .occlude()
2633 .flex_none()
2634 .h_full()
2635 .cursor_default()
2636 .when(show_container, |this| this.pl_1().px_1p5())
2637 .when(!show_container, |this| {
2638 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2639 })
2640 .on_mouse_move(cx.listener(|_, _, _, cx| {
2641 cx.notify();
2642 cx.stop_propagation()
2643 }))
2644 .on_hover(|_, _, cx| {
2645 cx.stop_propagation();
2646 })
2647 .on_any_mouse_down(|_, _, cx| {
2648 cx.stop_propagation();
2649 })
2650 .on_mouse_up(
2651 MouseButton::Left,
2652 cx.listener(|this, _, window, cx| {
2653 if !this.scrollbar_state.is_dragging()
2654 && !this.focus_handle.contains_focused(window, cx)
2655 {
2656 this.hide_scrollbar(window, cx);
2657 cx.notify();
2658 }
2659
2660 cx.stop_propagation();
2661 }),
2662 )
2663 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2664 cx.notify();
2665 }))
2666 .children(Scrollbar::vertical(
2667 // percentage as f32..end_offset as f32,
2668 self.scrollbar_state.clone(),
2669 )),
2670 )
2671 }
2672
2673 fn render_buffer_header_controls(
2674 &self,
2675 entity: &Entity<Self>,
2676 file: &Arc<dyn File>,
2677 _: &Window,
2678 cx: &App,
2679 ) -> Option<AnyElement> {
2680 let repo = self.active_repository.as_ref()?.read(cx);
2681 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2682 let ix = self.entry_by_path(&repo_path)?;
2683 let entry = self.entries.get(ix)?;
2684
2685 let entry_staging = self.entry_staging(entry.status_entry()?);
2686
2687 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
2688 .disabled(!self.has_write_access(cx))
2689 .fill()
2690 .elevation(ElevationIndex::Surface)
2691 .on_click({
2692 let entry = entry.clone();
2693 let git_panel = entity.downgrade();
2694 move |_, window, cx| {
2695 git_panel
2696 .update(cx, |this, cx| {
2697 this.toggle_staged_for_entry(&entry, window, cx);
2698 cx.stop_propagation();
2699 })
2700 .ok();
2701 }
2702 });
2703 Some(
2704 h_flex()
2705 .id("start-slot")
2706 .text_lg()
2707 .child(checkbox)
2708 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2709 // prevent the list item active state triggering when toggling checkbox
2710 cx.stop_propagation();
2711 })
2712 .into_any_element(),
2713 )
2714 }
2715
2716 fn render_entries(
2717 &self,
2718 has_write_access: bool,
2719 _: &Window,
2720 cx: &mut Context<Self>,
2721 ) -> impl IntoElement {
2722 let entry_count = self.entries.len();
2723
2724 h_flex()
2725 .size_full()
2726 .flex_grow()
2727 .overflow_hidden()
2728 .child(
2729 uniform_list(cx.entity().clone(), "entries", entry_count, {
2730 move |this, range, window, cx| {
2731 let mut items = Vec::with_capacity(range.end - range.start);
2732
2733 for ix in range {
2734 match &this.entries.get(ix) {
2735 Some(GitListEntry::GitStatusEntry(entry)) => {
2736 items.push(this.render_entry(
2737 ix,
2738 entry,
2739 has_write_access,
2740 window,
2741 cx,
2742 ));
2743 }
2744 Some(GitListEntry::Header(header)) => {
2745 items.push(this.render_list_header(
2746 ix,
2747 header,
2748 has_write_access,
2749 window,
2750 cx,
2751 ));
2752 }
2753 None => {}
2754 }
2755 }
2756
2757 items
2758 }
2759 })
2760 .size_full()
2761 .with_sizing_behavior(ListSizingBehavior::Auto)
2762 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2763 .track_scroll(self.scroll_handle.clone()),
2764 )
2765 .on_mouse_down(
2766 MouseButton::Right,
2767 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2768 this.deploy_panel_context_menu(event.position, window, cx)
2769 }),
2770 )
2771 .children(self.render_scrollbar(cx))
2772 }
2773
2774 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2775 Label::new(label.into()).color(color).single_line()
2776 }
2777
2778 fn list_item_height(&self) -> Rems {
2779 rems(1.75)
2780 }
2781
2782 fn render_list_header(
2783 &self,
2784 ix: usize,
2785 header: &GitHeaderEntry,
2786 _: bool,
2787 _: &Window,
2788 _: &Context<Self>,
2789 ) -> AnyElement {
2790 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2791
2792 h_flex()
2793 .id(id)
2794 .h(self.list_item_height())
2795 .w_full()
2796 .items_end()
2797 .px(rems(0.75)) // ~12px
2798 .pb(rems(0.3125)) // ~ 5px
2799 .child(
2800 Label::new(header.title())
2801 .color(Color::Muted)
2802 .size(LabelSize::Small)
2803 .line_height_style(LineHeightStyle::UiLabel)
2804 .single_line(),
2805 )
2806 .into_any_element()
2807 }
2808
2809 fn load_commit_details(
2810 &self,
2811 sha: &str,
2812 cx: &mut Context<Self>,
2813 ) -> Task<anyhow::Result<CommitDetails>> {
2814 let Some(repo) = self.active_repository.clone() else {
2815 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2816 };
2817 repo.update(cx, |repo, cx| {
2818 let show = repo.show(sha);
2819 cx.spawn(|_, _| async move { show.await? })
2820 })
2821 }
2822
2823 fn deploy_entry_context_menu(
2824 &mut self,
2825 position: Point<Pixels>,
2826 ix: usize,
2827 window: &mut Window,
2828 cx: &mut Context<Self>,
2829 ) {
2830 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2831 return;
2832 };
2833 let stage_title = if entry.status.staging().is_fully_staged() {
2834 "Unstage File"
2835 } else {
2836 "Stage File"
2837 };
2838 let restore_title = if entry.status.is_created() {
2839 "Trash File"
2840 } else {
2841 "Restore File"
2842 };
2843 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2844 context_menu
2845 .action(stage_title, ToggleStaged.boxed_clone())
2846 .action(restore_title, git::RestoreFile.boxed_clone())
2847 .separator()
2848 .action("Open Diff", Confirm.boxed_clone())
2849 .action("Open File", SecondaryConfirm.boxed_clone())
2850 });
2851 self.selected_entry = Some(ix);
2852 self.set_context_menu(context_menu, position, window, cx);
2853 }
2854
2855 fn deploy_panel_context_menu(
2856 &mut self,
2857 position: Point<Pixels>,
2858 window: &mut Window,
2859 cx: &mut Context<Self>,
2860 ) {
2861 let context_menu = git_panel_context_menu(window, cx);
2862 self.set_context_menu(context_menu, position, window, cx);
2863 }
2864
2865 fn set_context_menu(
2866 &mut self,
2867 context_menu: Entity<ContextMenu>,
2868 position: Point<Pixels>,
2869 window: &Window,
2870 cx: &mut Context<Self>,
2871 ) {
2872 let subscription = cx.subscribe_in(
2873 &context_menu,
2874 window,
2875 |this, _, _: &DismissEvent, window, cx| {
2876 if this.context_menu.as_ref().is_some_and(|context_menu| {
2877 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2878 }) {
2879 cx.focus_self(window);
2880 }
2881 this.context_menu.take();
2882 cx.notify();
2883 },
2884 );
2885 self.context_menu = Some((context_menu, position, subscription));
2886 cx.notify();
2887 }
2888
2889 fn render_entry(
2890 &self,
2891 ix: usize,
2892 entry: &GitStatusEntry,
2893 has_write_access: bool,
2894 window: &Window,
2895 cx: &Context<Self>,
2896 ) -> AnyElement {
2897 let display_name = entry
2898 .worktree_path
2899 .file_name()
2900 .map(|name| name.to_string_lossy().into_owned())
2901 .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2902
2903 let worktree_path = entry.worktree_path.clone();
2904 let selected = self.selected_entry == Some(ix);
2905 let marked = self.marked_entries.contains(&ix);
2906 let status_style = GitPanelSettings::get_global(cx).status_style;
2907 let status = entry.status;
2908 let has_conflict = status.is_conflicted();
2909 let is_modified = status.is_modified();
2910 let is_deleted = status.is_deleted();
2911
2912 let label_color = if status_style == StatusStyle::LabelColor {
2913 if has_conflict {
2914 Color::Conflict
2915 } else if is_modified {
2916 Color::Modified
2917 } else if is_deleted {
2918 // We don't want a bunch of red labels in the list
2919 Color::Disabled
2920 } else {
2921 Color::Created
2922 }
2923 } else {
2924 Color::Default
2925 };
2926
2927 let path_color = if status.is_deleted() {
2928 Color::Disabled
2929 } else {
2930 Color::Muted
2931 };
2932
2933 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2934 let checkbox_wrapper_id: ElementId =
2935 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2936 let checkbox_id: ElementId =
2937 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2938
2939 let entry_staging = self.entry_staging(entry);
2940 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
2941
2942 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2943 is_staged = ToggleState::Selected;
2944 }
2945
2946 let handle = cx.weak_entity();
2947
2948 let selected_bg_alpha = 0.08;
2949 let marked_bg_alpha = 0.12;
2950 let state_opacity_step = 0.04;
2951
2952 let base_bg = match (selected, marked) {
2953 (true, true) => cx
2954 .theme()
2955 .status()
2956 .info
2957 .alpha(selected_bg_alpha + marked_bg_alpha),
2958 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2959 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2960 _ => cx.theme().colors().ghost_element_background,
2961 };
2962
2963 let hover_bg = if selected {
2964 cx.theme()
2965 .status()
2966 .info
2967 .alpha(selected_bg_alpha + state_opacity_step)
2968 } else {
2969 cx.theme().colors().ghost_element_hover
2970 };
2971
2972 let active_bg = if selected {
2973 cx.theme()
2974 .status()
2975 .info
2976 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2977 } else {
2978 cx.theme().colors().ghost_element_active
2979 };
2980
2981 h_flex()
2982 .id(id)
2983 .h(self.list_item_height())
2984 .w_full()
2985 .items_center()
2986 .border_1()
2987 .when(selected && self.focus_handle.is_focused(window), |el| {
2988 el.border_color(cx.theme().colors().border_focused)
2989 })
2990 .px(rems(0.75)) // ~12px
2991 .overflow_hidden()
2992 .flex_none()
2993 .gap(DynamicSpacing::Base04.rems(cx))
2994 .bg(base_bg)
2995 .hover(|this| this.bg(hover_bg))
2996 .active(|this| this.bg(active_bg))
2997 .on_click({
2998 cx.listener(move |this, event: &ClickEvent, window, cx| {
2999 this.selected_entry = Some(ix);
3000 cx.notify();
3001 if event.modifiers().secondary() {
3002 this.open_file(&Default::default(), window, cx)
3003 } else {
3004 this.open_diff(&Default::default(), window, cx);
3005 this.focus_handle.focus(window);
3006 }
3007 })
3008 })
3009 .on_mouse_down(
3010 MouseButton::Right,
3011 move |event: &MouseDownEvent, window, cx| {
3012 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3013 if event.button != MouseButton::Right {
3014 return;
3015 }
3016
3017 let Some(this) = handle.upgrade() else {
3018 return;
3019 };
3020 this.update(cx, |this, cx| {
3021 this.deploy_entry_context_menu(event.position, ix, window, cx);
3022 });
3023 cx.stop_propagation();
3024 },
3025 )
3026 // .on_secondary_mouse_down(cx.listener(
3027 // move |this, event: &MouseDownEvent, window, cx| {
3028 // this.deploy_entry_context_menu(event.position, ix, window, cx);
3029 // cx.stop_propagation();
3030 // },
3031 // ))
3032 .child(
3033 div()
3034 .id(checkbox_wrapper_id)
3035 .flex_none()
3036 .occlude()
3037 .cursor_pointer()
3038 .child(
3039 Checkbox::new(checkbox_id, is_staged)
3040 .disabled(!has_write_access)
3041 .fill()
3042 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
3043 .elevation(ElevationIndex::Surface)
3044 .on_click({
3045 let entry = entry.clone();
3046 cx.listener(move |this, _, window, cx| {
3047 if !has_write_access {
3048 return;
3049 }
3050 this.toggle_staged_for_entry(
3051 &GitListEntry::GitStatusEntry(entry.clone()),
3052 window,
3053 cx,
3054 );
3055 cx.stop_propagation();
3056 })
3057 })
3058 .tooltip(move |window, cx| {
3059 let tooltip_name = if entry_staging.is_fully_staged() {
3060 "Unstage"
3061 } else {
3062 "Stage"
3063 };
3064
3065 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
3066 }),
3067 ),
3068 )
3069 .child(git_status_icon(status, cx))
3070 .child(
3071 h_flex()
3072 .items_center()
3073 .overflow_hidden()
3074 .when_some(worktree_path.parent(), |this, parent| {
3075 let parent_str = parent.to_string_lossy();
3076 if !parent_str.is_empty() {
3077 this.child(
3078 self.entry_label(format!("{}/", parent_str), path_color)
3079 .when(status.is_deleted(), |this| this.strikethrough()),
3080 )
3081 } else {
3082 this
3083 }
3084 })
3085 .child(
3086 self.entry_label(display_name.clone(), label_color)
3087 .when(status.is_deleted(), |this| this.strikethrough()),
3088 ),
3089 )
3090 .into_any_element()
3091 }
3092
3093 fn has_write_access(&self, cx: &App) -> bool {
3094 !self.project.read(cx).is_read_only(cx)
3095 }
3096}
3097
3098fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3099 let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3100 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3101 provider.is_authenticated(cx).then(|| model)
3102}
3103
3104impl Render for GitPanel {
3105 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3106 let project = self.project.read(cx);
3107 let has_entries = self.entries.len() > 0;
3108 let room = self
3109 .workspace
3110 .upgrade()
3111 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3112
3113 let has_write_access = self.has_write_access(cx);
3114
3115 let has_co_authors = room.map_or(false, |room| {
3116 room.read(cx)
3117 .remote_participants()
3118 .values()
3119 .any(|remote_participant| remote_participant.can_write())
3120 });
3121
3122 v_flex()
3123 .id("git_panel")
3124 .key_context(self.dispatch_context(window, cx))
3125 .track_focus(&self.focus_handle)
3126 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3127 .when(has_write_access && !project.is_read_only(cx), |this| {
3128 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
3129 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
3130 }))
3131 .on_action(cx.listener(GitPanel::commit))
3132 })
3133 .on_action(cx.listener(Self::select_first))
3134 .on_action(cx.listener(Self::select_next))
3135 .on_action(cx.listener(Self::select_previous))
3136 .on_action(cx.listener(Self::select_last))
3137 .on_action(cx.listener(Self::close_panel))
3138 .on_action(cx.listener(Self::open_diff))
3139 .on_action(cx.listener(Self::open_file))
3140 .on_action(cx.listener(Self::revert_selected))
3141 .on_action(cx.listener(Self::focus_changes_list))
3142 .on_action(cx.listener(Self::focus_editor))
3143 .on_action(cx.listener(Self::toggle_staged_for_selected))
3144 .on_action(cx.listener(Self::stage_all))
3145 .on_action(cx.listener(Self::unstage_all))
3146 .on_action(cx.listener(Self::restore_tracked_files))
3147 .on_action(cx.listener(Self::clean_all))
3148 .on_action(cx.listener(Self::expand_commit_editor))
3149 .on_action(cx.listener(Self::generate_commit_message_action))
3150 .when(has_write_access && has_co_authors, |git_panel| {
3151 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3152 })
3153 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3154 .on_hover(cx.listener(|this, hovered, window, cx| {
3155 if *hovered {
3156 this.show_scrollbar = true;
3157 this.hide_scrollbar_task.take();
3158 cx.notify();
3159 } else if !this.focus_handle.contains_focused(window, cx) {
3160 this.hide_scrollbar(window, cx);
3161 }
3162 }))
3163 .size_full()
3164 .overflow_hidden()
3165 .bg(ElevationIndex::Surface.bg(cx))
3166 .child(
3167 v_flex()
3168 .size_full()
3169 .map(|this| {
3170 if has_entries {
3171 this.child(self.render_entries(has_write_access, window, cx))
3172 } else {
3173 this.child(self.render_empty_state(cx).into_any_element())
3174 }
3175 })
3176 .children(self.render_footer(window, cx))
3177 .children(self.render_previous_commit(cx))
3178 .into_any_element(),
3179 )
3180 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3181 deferred(
3182 anchored()
3183 .position(*position)
3184 .anchor(gpui::Corner::TopLeft)
3185 .child(menu.clone()),
3186 )
3187 .with_priority(1)
3188 }))
3189 }
3190}
3191
3192impl Focusable for GitPanel {
3193 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3194 self.focus_handle.clone()
3195 }
3196}
3197
3198impl EventEmitter<Event> for GitPanel {}
3199
3200impl EventEmitter<PanelEvent> for GitPanel {}
3201
3202pub(crate) struct GitPanelAddon {
3203 pub(crate) workspace: WeakEntity<Workspace>,
3204}
3205
3206impl editor::Addon for GitPanelAddon {
3207 fn to_any(&self) -> &dyn std::any::Any {
3208 self
3209 }
3210
3211 fn render_buffer_header_controls(
3212 &self,
3213 excerpt_info: &ExcerptInfo,
3214 window: &Window,
3215 cx: &App,
3216 ) -> Option<AnyElement> {
3217 let file = excerpt_info.buffer.file()?;
3218 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3219
3220 git_panel
3221 .read(cx)
3222 .render_buffer_header_controls(&git_panel, &file, window, cx)
3223 }
3224}
3225
3226impl Panel for GitPanel {
3227 fn persistent_name() -> &'static str {
3228 "GitPanel"
3229 }
3230
3231 fn position(&self, _: &Window, cx: &App) -> DockPosition {
3232 GitPanelSettings::get_global(cx).dock
3233 }
3234
3235 fn position_is_valid(&self, position: DockPosition) -> bool {
3236 matches!(position, DockPosition::Left | DockPosition::Right)
3237 }
3238
3239 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3240 settings::update_settings_file::<GitPanelSettings>(
3241 self.fs.clone(),
3242 cx,
3243 move |settings, _| settings.dock = Some(position),
3244 );
3245 }
3246
3247 fn size(&self, _: &Window, cx: &App) -> Pixels {
3248 self.width
3249 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3250 }
3251
3252 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3253 self.width = size;
3254 self.serialize(cx);
3255 cx.notify();
3256 }
3257
3258 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3259 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3260 }
3261
3262 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3263 Some("Git Panel")
3264 }
3265
3266 fn toggle_action(&self) -> Box<dyn Action> {
3267 Box::new(ToggleFocus)
3268 }
3269
3270 fn activation_priority(&self) -> u32 {
3271 2
3272 }
3273}
3274
3275impl PanelHeader for GitPanel {}
3276
3277struct GitPanelMessageTooltip {
3278 commit_tooltip: Option<Entity<CommitTooltip>>,
3279}
3280
3281impl GitPanelMessageTooltip {
3282 fn new(
3283 git_panel: Entity<GitPanel>,
3284 sha: SharedString,
3285 window: &mut Window,
3286 cx: &mut App,
3287 ) -> Entity<Self> {
3288 cx.new(|cx| {
3289 cx.spawn_in(window, |this, mut cx| async move {
3290 let details = git_panel
3291 .update(&mut cx, |git_panel, cx| {
3292 git_panel.load_commit_details(&sha, cx)
3293 })?
3294 .await?;
3295
3296 let commit_details = editor::commit_tooltip::CommitDetails {
3297 sha: details.sha.clone(),
3298 committer_name: details.committer_name.clone(),
3299 committer_email: details.committer_email.clone(),
3300 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3301 message: Some(editor::commit_tooltip::ParsedCommitMessage {
3302 message: details.message.clone(),
3303 ..Default::default()
3304 }),
3305 };
3306
3307 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3308 this.commit_tooltip =
3309 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3310 cx.notify();
3311 })
3312 })
3313 .detach();
3314
3315 Self {
3316 commit_tooltip: None,
3317 }
3318 })
3319 }
3320}
3321
3322impl Render for GitPanelMessageTooltip {
3323 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3324 if let Some(commit_tooltip) = &self.commit_tooltip {
3325 commit_tooltip.clone().into_any_element()
3326 } else {
3327 gpui::Empty.into_any_element()
3328 }
3329 }
3330}
3331
3332#[derive(IntoElement, IntoComponent)]
3333#[component(scope = "Version Control")]
3334pub struct PanelRepoFooter {
3335 id: SharedString,
3336 active_repository: SharedString,
3337 branch: Option<Branch>,
3338 // Getting a GitPanel in previews will be difficult.
3339 //
3340 // For now just take an option here, and we won't bind handlers to buttons in previews.
3341 git_panel: Option<Entity<GitPanel>>,
3342}
3343
3344impl PanelRepoFooter {
3345 pub fn new(
3346 id: impl Into<SharedString>,
3347 active_repository: SharedString,
3348 branch: Option<Branch>,
3349 git_panel: Option<Entity<GitPanel>>,
3350 ) -> Self {
3351 Self {
3352 id: id.into(),
3353 active_repository,
3354 branch,
3355 git_panel,
3356 }
3357 }
3358
3359 pub fn new_preview(
3360 id: impl Into<SharedString>,
3361 active_repository: SharedString,
3362 branch: Option<Branch>,
3363 ) -> Self {
3364 Self {
3365 id: id.into(),
3366 active_repository,
3367 branch,
3368 git_panel: None,
3369 }
3370 }
3371
3372 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3373 PopoverMenu::new(id.into())
3374 .trigger(
3375 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3376 .icon_size(IconSize::Small)
3377 .icon_color(Color::Muted),
3378 )
3379 .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3380 .anchor(Corner::TopRight)
3381 }
3382}
3383
3384impl RenderOnce for PanelRepoFooter {
3385 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3386 let active_repo = self.active_repository.clone();
3387 let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3388 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3389 .style(ButtonStyle::Transparent)
3390 .size(ButtonSize::None)
3391 .label_size(LabelSize::Small)
3392 .color(Color::Muted);
3393
3394 let project = self
3395 .git_panel
3396 .as_ref()
3397 .map(|panel| panel.read(cx).project.clone());
3398
3399 let repo = self
3400 .git_panel
3401 .as_ref()
3402 .and_then(|panel| panel.read(cx).active_repository.clone());
3403
3404 let single_repo = project
3405 .as_ref()
3406 .map(|project| {
3407 filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3408 })
3409 .unwrap_or(true);
3410
3411 let repo_selector = PopoverMenu::new("repository-switcher")
3412 .menu({
3413 let project = project.clone();
3414 move |window, cx| {
3415 let project = project.clone()?;
3416 Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3417 }
3418 })
3419 .trigger_with_tooltip(
3420 repo_selector_trigger.disabled(single_repo).truncate(true),
3421 Tooltip::text("Switch active repository"),
3422 )
3423 .attach(gpui::Corner::BottomLeft)
3424 .into_any_element();
3425
3426 let branch = self.branch.clone();
3427 let branch_name = branch
3428 .as_ref()
3429 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3430
3431 let branch_selector_button = Button::new("branch-selector", branch_name)
3432 .style(ButtonStyle::Transparent)
3433 .size(ButtonSize::None)
3434 .label_size(LabelSize::Small)
3435 .truncate(true)
3436 .tooltip(Tooltip::for_action_title(
3437 "Switch Branch",
3438 &zed_actions::git::Branch,
3439 ))
3440 .on_click(|_, window, cx| {
3441 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3442 });
3443
3444 let branch_selector = PopoverMenu::new("popover-button")
3445 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3446 .trigger_with_tooltip(
3447 branch_selector_button,
3448 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3449 )
3450 .anchor(Corner::TopLeft)
3451 .offset(gpui::Point {
3452 x: px(0.0),
3453 y: px(-2.0),
3454 });
3455
3456 let spinner = self
3457 .git_panel
3458 .as_ref()
3459 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3460
3461 h_flex()
3462 .w_full()
3463 .px_2()
3464 .h(px(36.))
3465 .items_center()
3466 .justify_between()
3467 .child(
3468 h_flex()
3469 .flex_1()
3470 .overflow_hidden()
3471 .items_center()
3472 .child(
3473 div().child(
3474 Icon::new(IconName::GitBranchSmall)
3475 .size(IconSize::Small)
3476 .color(Color::Muted),
3477 ),
3478 )
3479 .child(repo_selector)
3480 .when_some(branch.clone(), |this, _| {
3481 this.child(
3482 div()
3483 .text_color(cx.theme().colors().text_muted)
3484 .text_sm()
3485 .child("/"),
3486 )
3487 })
3488 .child(branch_selector),
3489 )
3490 .child(
3491 h_flex()
3492 .gap_1()
3493 .flex_shrink_0()
3494 .children(spinner)
3495 .child(self.render_overflow_menu(overflow_menu_id))
3496 .when_some(branch, |this, branch| {
3497 let mut focus_handle = None;
3498 if let Some(git_panel) = self.git_panel.as_ref() {
3499 if !git_panel.read(cx).can_push_and_pull(cx) {
3500 return this;
3501 }
3502 focus_handle = Some(git_panel.focus_handle(cx));
3503 }
3504
3505 this.children(render_remote_button(
3506 self.id.clone(),
3507 &branch,
3508 focus_handle,
3509 true,
3510 ))
3511 }),
3512 )
3513 }
3514}
3515
3516impl ComponentPreview for PanelRepoFooter {
3517 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3518 let unknown_upstream = None;
3519 let no_remote_upstream = Some(UpstreamTracking::Gone);
3520 let ahead_of_upstream = Some(
3521 UpstreamTrackingStatus {
3522 ahead: 2,
3523 behind: 0,
3524 }
3525 .into(),
3526 );
3527 let behind_upstream = Some(
3528 UpstreamTrackingStatus {
3529 ahead: 0,
3530 behind: 2,
3531 }
3532 .into(),
3533 );
3534 let ahead_and_behind_upstream = Some(
3535 UpstreamTrackingStatus {
3536 ahead: 3,
3537 behind: 1,
3538 }
3539 .into(),
3540 );
3541
3542 let not_ahead_or_behind_upstream = Some(
3543 UpstreamTrackingStatus {
3544 ahead: 0,
3545 behind: 0,
3546 }
3547 .into(),
3548 );
3549
3550 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3551 Branch {
3552 is_head: true,
3553 name: "some-branch".into(),
3554 upstream: upstream.map(|tracking| Upstream {
3555 ref_name: "origin/some-branch".into(),
3556 tracking,
3557 }),
3558 most_recent_commit: Some(CommitSummary {
3559 sha: "abc123".into(),
3560 subject: "Modify stuff".into(),
3561 commit_timestamp: 1710932954,
3562 has_parent: true,
3563 }),
3564 }
3565 }
3566
3567 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3568 Branch {
3569 is_head: true,
3570 name: branch_name.to_string().into(),
3571 upstream: upstream.map(|tracking| Upstream {
3572 ref_name: format!("zed/{}", branch_name).into(),
3573 tracking,
3574 }),
3575 most_recent_commit: Some(CommitSummary {
3576 sha: "abc123".into(),
3577 subject: "Modify stuff".into(),
3578 commit_timestamp: 1710932954,
3579 has_parent: true,
3580 }),
3581 }
3582 }
3583
3584 fn active_repository(id: usize) -> SharedString {
3585 format!("repo-{}", id).into()
3586 }
3587
3588 let example_width = px(340.);
3589
3590 v_flex()
3591 .gap_6()
3592 .w_full()
3593 .flex_none()
3594 .children(vec![example_group_with_title(
3595 "Action Button States",
3596 vec![
3597 single_example(
3598 "No Branch",
3599 div()
3600 .w(example_width)
3601 .overflow_hidden()
3602 .child(PanelRepoFooter::new_preview(
3603 "no-branch",
3604 active_repository(1).clone(),
3605 None,
3606 ))
3607 .into_any_element(),
3608 )
3609 .grow(),
3610 single_example(
3611 "Remote status unknown",
3612 div()
3613 .w(example_width)
3614 .overflow_hidden()
3615 .child(PanelRepoFooter::new_preview(
3616 "unknown-upstream",
3617 active_repository(2).clone(),
3618 Some(branch(unknown_upstream)),
3619 ))
3620 .into_any_element(),
3621 )
3622 .grow(),
3623 single_example(
3624 "No Remote Upstream",
3625 div()
3626 .w(example_width)
3627 .overflow_hidden()
3628 .child(PanelRepoFooter::new_preview(
3629 "no-remote-upstream",
3630 active_repository(3).clone(),
3631 Some(branch(no_remote_upstream)),
3632 ))
3633 .into_any_element(),
3634 )
3635 .grow(),
3636 single_example(
3637 "Not Ahead or Behind",
3638 div()
3639 .w(example_width)
3640 .overflow_hidden()
3641 .child(PanelRepoFooter::new_preview(
3642 "not-ahead-or-behind",
3643 active_repository(4).clone(),
3644 Some(branch(not_ahead_or_behind_upstream)),
3645 ))
3646 .into_any_element(),
3647 )
3648 .grow(),
3649 single_example(
3650 "Behind remote",
3651 div()
3652 .w(example_width)
3653 .overflow_hidden()
3654 .child(PanelRepoFooter::new_preview(
3655 "behind-remote",
3656 active_repository(5).clone(),
3657 Some(branch(behind_upstream)),
3658 ))
3659 .into_any_element(),
3660 )
3661 .grow(),
3662 single_example(
3663 "Ahead of remote",
3664 div()
3665 .w(example_width)
3666 .overflow_hidden()
3667 .child(PanelRepoFooter::new_preview(
3668 "ahead-of-remote",
3669 active_repository(6).clone(),
3670 Some(branch(ahead_of_upstream)),
3671 ))
3672 .into_any_element(),
3673 )
3674 .grow(),
3675 single_example(
3676 "Ahead and behind remote",
3677 div()
3678 .w(example_width)
3679 .overflow_hidden()
3680 .child(PanelRepoFooter::new_preview(
3681 "ahead-and-behind",
3682 active_repository(7).clone(),
3683 Some(branch(ahead_and_behind_upstream)),
3684 ))
3685 .into_any_element(),
3686 )
3687 .grow(),
3688 ],
3689 )
3690 .grow()
3691 .vertical()])
3692 .children(vec![example_group_with_title(
3693 "Labels",
3694 vec![
3695 single_example(
3696 "Short Branch & Repo",
3697 div()
3698 .w(example_width)
3699 .overflow_hidden()
3700 .child(PanelRepoFooter::new_preview(
3701 "short-branch",
3702 SharedString::from("zed"),
3703 Some(custom("main", behind_upstream)),
3704 ))
3705 .into_any_element(),
3706 )
3707 .grow(),
3708 single_example(
3709 "Long Branch",
3710 div()
3711 .w(example_width)
3712 .overflow_hidden()
3713 .child(PanelRepoFooter::new_preview(
3714 "long-branch",
3715 SharedString::from("zed"),
3716 Some(custom(
3717 "redesign-and-update-git-ui-list-entry-style",
3718 behind_upstream,
3719 )),
3720 ))
3721 .into_any_element(),
3722 )
3723 .grow(),
3724 single_example(
3725 "Long Repo",
3726 div()
3727 .w(example_width)
3728 .overflow_hidden()
3729 .child(PanelRepoFooter::new_preview(
3730 "long-repo",
3731 SharedString::from("zed-industries-community-examples"),
3732 Some(custom("gpui", ahead_of_upstream)),
3733 ))
3734 .into_any_element(),
3735 )
3736 .grow(),
3737 single_example(
3738 "Long Repo & Branch",
3739 div()
3740 .w(example_width)
3741 .overflow_hidden()
3742 .child(PanelRepoFooter::new_preview(
3743 "long-repo-and-branch",
3744 SharedString::from("zed-industries-community-examples"),
3745 Some(custom(
3746 "redesign-and-update-git-ui-list-entry-style",
3747 behind_upstream,
3748 )),
3749 ))
3750 .into_any_element(),
3751 )
3752 .grow(),
3753 single_example(
3754 "Uppercase Repo",
3755 div()
3756 .w(example_width)
3757 .overflow_hidden()
3758 .child(PanelRepoFooter::new_preview(
3759 "uppercase-repo",
3760 SharedString::from("LICENSES"),
3761 Some(custom("main", ahead_of_upstream)),
3762 ))
3763 .into_any_element(),
3764 )
3765 .grow(),
3766 single_example(
3767 "Uppercase Branch",
3768 div()
3769 .w(example_width)
3770 .overflow_hidden()
3771 .child(PanelRepoFooter::new_preview(
3772 "uppercase-branch",
3773 SharedString::from("zed"),
3774 Some(custom("update-README", behind_upstream)),
3775 ))
3776 .into_any_element(),
3777 )
3778 .grow(),
3779 ],
3780 )
3781 .grow()
3782 .vertical()])
3783 .into_any_element()
3784 }
3785}
3786
3787#[cfg(test)]
3788mod tests {
3789 use git::status::StatusCode;
3790 use gpui::TestAppContext;
3791 use project::{FakeFs, WorktreeSettings};
3792 use serde_json::json;
3793 use settings::SettingsStore;
3794 use theme::LoadThemes;
3795 use util::path;
3796
3797 use super::*;
3798
3799 fn init_test(cx: &mut gpui::TestAppContext) {
3800 if std::env::var("RUST_LOG").is_ok() {
3801 env_logger::try_init().ok();
3802 }
3803
3804 cx.update(|cx| {
3805 let settings_store = SettingsStore::test(cx);
3806 cx.set_global(settings_store);
3807 WorktreeSettings::register(cx);
3808 workspace::init_settings(cx);
3809 theme::init(LoadThemes::JustBase, cx);
3810 language::init(cx);
3811 editor::init(cx);
3812 Project::init_settings(cx);
3813 crate::init(cx);
3814 });
3815 }
3816
3817 #[gpui::test]
3818 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
3819 init_test(cx);
3820 let fs = FakeFs::new(cx.background_executor.clone());
3821 fs.insert_tree(
3822 "/root",
3823 json!({
3824 "zed": {
3825 ".git": {},
3826 "crates": {
3827 "gpui": {
3828 "gpui.rs": "fn main() {}"
3829 },
3830 "util": {
3831 "util.rs": "fn do_it() {}"
3832 }
3833 }
3834 },
3835 }),
3836 )
3837 .await;
3838
3839 fs.set_status_for_repo_via_git_operation(
3840 Path::new(path!("/root/zed/.git")),
3841 &[
3842 (
3843 Path::new("crates/gpui/gpui.rs"),
3844 StatusCode::Modified.worktree(),
3845 ),
3846 (
3847 Path::new("crates/util/util.rs"),
3848 StatusCode::Modified.worktree(),
3849 ),
3850 ],
3851 );
3852
3853 let project =
3854 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
3855 let (workspace, cx) =
3856 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3857
3858 cx.read(|cx| {
3859 project
3860 .read(cx)
3861 .worktrees(cx)
3862 .nth(0)
3863 .unwrap()
3864 .read(cx)
3865 .as_local()
3866 .unwrap()
3867 .scan_complete()
3868 })
3869 .await;
3870
3871 cx.executor().run_until_parked();
3872
3873 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
3874 let panel = cx.new_window_entity(|window, cx| {
3875 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
3876 });
3877
3878 let handle = cx.update_window_entity(&panel, |panel, _, _| {
3879 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3880 });
3881 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3882 handle.await;
3883
3884 let entries = panel.update(cx, |panel, _| panel.entries.clone());
3885 pretty_assertions::assert_eq!(
3886 entries,
3887 [
3888 GitListEntry::Header(GitHeaderEntry {
3889 header: Section::Tracked
3890 }),
3891 GitListEntry::GitStatusEntry(GitStatusEntry {
3892 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
3893 repo_path: "crates/gpui/gpui.rs".into(),
3894 worktree_path: Path::new("gpui.rs").into(),
3895 status: StatusCode::Modified.worktree(),
3896 staging: StageStatus::Unstaged,
3897 }),
3898 GitListEntry::GitStatusEntry(GitStatusEntry {
3899 abs_path: path!("/root/zed/crates/util/util.rs").into(),
3900 repo_path: "crates/util/util.rs".into(),
3901 worktree_path: Path::new("../util/util.rs").into(),
3902 status: StatusCode::Modified.worktree(),
3903 staging: StageStatus::Unstaged,
3904 },),
3905 ],
3906 );
3907
3908 cx.update_window_entity(&panel, |panel, window, cx| {
3909 panel.select_last(&Default::default(), window, cx);
3910 assert_eq!(panel.selected_entry, Some(2));
3911 panel.open_diff(&Default::default(), window, cx);
3912 });
3913 cx.run_until_parked();
3914
3915 let worktree_roots = workspace.update(cx, |workspace, cx| {
3916 workspace
3917 .worktrees(cx)
3918 .map(|worktree| worktree.read(cx).abs_path())
3919 .collect::<Vec<_>>()
3920 });
3921 pretty_assertions::assert_eq!(
3922 worktree_roots,
3923 vec![
3924 Path::new(path!("/root/zed/crates/gpui")).into(),
3925 Path::new(path!("/root/zed/crates/util/util.rs")).into(),
3926 ]
3927 );
3928
3929 let repo_from_single_file_worktree = project.update(cx, |project, cx| {
3930 let git_store = project.git_store().read(cx);
3931 // The repo that comes from the single-file worktree can't be selected through the UI.
3932 let filtered_entries = filtered_repository_entries(git_store, cx)
3933 .iter()
3934 .map(|repo| repo.read(cx).worktree_abs_path.clone())
3935 .collect::<Vec<_>>();
3936 assert_eq!(
3937 filtered_entries,
3938 [Path::new(path!("/root/zed/crates/gpui")).into()]
3939 );
3940 // But we can select it artificially here.
3941 git_store
3942 .all_repositories()
3943 .into_iter()
3944 .find(|repo| {
3945 &*repo.read(cx).worktree_abs_path
3946 == Path::new(path!("/root/zed/crates/util/util.rs"))
3947 })
3948 .unwrap()
3949 });
3950
3951 // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
3952 repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
3953 let handle = cx.update_window_entity(&panel, |panel, _, _| {
3954 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3955 });
3956 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3957 handle.await;
3958 let entries = panel.update(cx, |panel, _| panel.entries.clone());
3959 pretty_assertions::assert_eq!(
3960 entries,
3961 [
3962 GitListEntry::Header(GitHeaderEntry {
3963 header: Section::Tracked
3964 }),
3965 GitListEntry::GitStatusEntry(GitStatusEntry {
3966 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
3967 repo_path: "crates/gpui/gpui.rs".into(),
3968 worktree_path: Path::new("../../gpui/gpui.rs").into(),
3969 status: StatusCode::Modified.worktree(),
3970 staging: StageStatus::Unstaged,
3971 }),
3972 GitListEntry::GitStatusEntry(GitStatusEntry {
3973 abs_path: path!("/root/zed/crates/util/util.rs").into(),
3974 repo_path: "crates/util/util.rs".into(),
3975 worktree_path: Path::new("util.rs").into(),
3976 status: StatusCode::Modified.worktree(),
3977 staging: StageStatus::Unstaged,
3978 },),
3979 ],
3980 );
3981 }
3982}