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