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, DiffType, PushOptions, Remote, RemoteCommandOutput,
23 ResetMode, 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 fn generate_commit_message_action(
1433 &mut self,
1434 _: &git::GenerateCommitMessage,
1435 _window: &mut Window,
1436 cx: &mut Context<Self>,
1437 ) {
1438 self.generate_commit_message(cx);
1439 }
1440
1441 /// Generates a commit message using an LLM.
1442 fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1443 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1444 return;
1445 };
1446 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1447 return;
1448 };
1449
1450 if !provider.is_authenticated(cx) {
1451 return;
1452 }
1453
1454 let Some(repo) = self.active_repository.as_ref() else {
1455 return;
1456 };
1457
1458 let diff = repo.update(cx, |repo, cx| {
1459 if self.has_staged_changes() {
1460 repo.diff(DiffType::HeadToIndex, cx)
1461 } else {
1462 repo.diff(DiffType::HeadToWorktree, cx)
1463 }
1464 });
1465
1466 self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1467 async move {
1468 let _defer = util::defer({
1469 let mut cx = cx.clone();
1470 let this = this.clone();
1471 move || {
1472 this.update(&mut cx, |this, _cx| {
1473 this.generate_commit_message_task.take();
1474 })
1475 .ok();
1476 }
1477 });
1478
1479 let mut diff_text = diff.await??;
1480 const ONE_MB: usize = 1_000_000;
1481 if diff_text.len() > ONE_MB {
1482 diff_text = diff_text.chars().take(ONE_MB).collect()
1483 }
1484
1485 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1486
1487 let request = LanguageModelRequest {
1488 messages: vec![LanguageModelRequestMessage {
1489 role: Role::User,
1490 content: vec![format!("{PROMPT}\n{diff_text}").into()],
1491 cache: false,
1492 }],
1493 tools: Vec::new(),
1494 stop: Vec::new(),
1495 temperature: None,
1496 };
1497
1498 let stream = model.stream_completion_text(request, &cx);
1499 let mut messages = stream.await?;
1500
1501 while let Some(message) = messages.stream.next().await {
1502 let text = message?;
1503
1504 this.update(&mut cx, |this, cx| {
1505 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1506 let insert_position = buffer.anchor_before(buffer.len());
1507 buffer.edit([(insert_position..insert_position, text)], None, cx);
1508 });
1509 })?;
1510 }
1511
1512 anyhow::Ok(())
1513 }
1514 .log_err()
1515 }));
1516 }
1517
1518 fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1519 let suggested_commit_message = self.suggest_commit_message();
1520 let placeholder_text = suggested_commit_message
1521 .as_deref()
1522 .unwrap_or("Enter commit message");
1523
1524 self.commit_editor.update(cx, |editor, cx| {
1525 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1526 });
1527
1528 cx.notify();
1529 }
1530
1531 pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1532 if !self.can_push_and_pull(cx) {
1533 return;
1534 }
1535
1536 let Some(repo) = self.active_repository.clone() else {
1537 return;
1538 };
1539 telemetry::event!("Git Fetched");
1540 let guard = self.start_remote_operation();
1541 let askpass = self.askpass_delegate("git fetch", window, cx);
1542 cx.spawn(|this, mut cx| async move {
1543 let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1544
1545 let remote_message = fetch.await?;
1546 drop(guard);
1547 this.update(&mut cx, |this, cx| {
1548 match remote_message {
1549 Ok(remote_message) => {
1550 this.show_remote_output(RemoteAction::Fetch, remote_message, cx);
1551 }
1552 Err(e) => {
1553 this.show_err_toast(e, cx);
1554 }
1555 }
1556
1557 anyhow::Ok(())
1558 })
1559 .ok();
1560 anyhow::Ok(())
1561 })
1562 .detach_and_log_err(cx);
1563 }
1564
1565 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1566 if !self.can_push_and_pull(cx) {
1567 return;
1568 }
1569 let Some(repo) = self.active_repository.clone() else {
1570 return;
1571 };
1572 let Some(branch) = repo.read(cx).current_branch() else {
1573 return;
1574 };
1575 telemetry::event!("Git Pulled");
1576 let branch = branch.clone();
1577 let remote = self.get_current_remote(window, cx);
1578 cx.spawn_in(window, move |this, mut cx| async move {
1579 let remote = match remote.await {
1580 Ok(Some(remote)) => remote,
1581 Ok(None) => {
1582 return Ok(());
1583 }
1584 Err(e) => {
1585 log::error!("Failed to get current remote: {}", e);
1586 this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1587 .ok();
1588 return Ok(());
1589 }
1590 };
1591
1592 let askpass = this.update_in(&mut cx, |this, window, cx| {
1593 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1594 })?;
1595
1596 let guard = this
1597 .update(&mut cx, |this, _| this.start_remote_operation())
1598 .ok();
1599
1600 let pull = repo.update(&mut cx, |repo, cx| {
1601 repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1602 })?;
1603
1604 let remote_message = pull.await?;
1605 drop(guard);
1606
1607 this.update(&mut cx, |this, cx| match remote_message {
1608 Ok(remote_message) => {
1609 this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1610 }
1611 Err(err) => this.show_err_toast(err, cx),
1612 })
1613 .ok();
1614
1615 anyhow::Ok(())
1616 })
1617 .detach_and_log_err(cx);
1618 }
1619
1620 pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1621 if !self.can_push_and_pull(cx) {
1622 return;
1623 }
1624 let Some(repo) = self.active_repository.clone() else {
1625 return;
1626 };
1627 let Some(branch) = repo.read(cx).current_branch() else {
1628 return;
1629 };
1630 telemetry::event!("Git Pushed");
1631 let branch = branch.clone();
1632 let options = if force_push {
1633 PushOptions::Force
1634 } else {
1635 PushOptions::SetUpstream
1636 };
1637 let remote = self.get_current_remote(window, cx);
1638
1639 cx.spawn_in(window, move |this, mut cx| async move {
1640 let remote = match remote.await {
1641 Ok(Some(remote)) => remote,
1642 Ok(None) => {
1643 return Ok(());
1644 }
1645 Err(e) => {
1646 log::error!("Failed to get current remote: {}", e);
1647 this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1648 .ok();
1649 return Ok(());
1650 }
1651 };
1652
1653 let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1654 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1655 })?;
1656
1657 let guard = this
1658 .update(&mut cx, |this, _| this.start_remote_operation())
1659 .ok();
1660
1661 let push = repo.update(&mut cx, |repo, cx| {
1662 repo.push(
1663 branch.name.clone(),
1664 remote.name.clone(),
1665 Some(options),
1666 askpass_delegate,
1667 cx,
1668 )
1669 })?;
1670
1671 let remote_output = push.await?;
1672 drop(guard);
1673
1674 this.update(&mut cx, |this, cx| match remote_output {
1675 Ok(remote_message) => {
1676 this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1677 }
1678 Err(e) => {
1679 this.show_err_toast(e, cx);
1680 }
1681 })?;
1682
1683 anyhow::Ok(())
1684 })
1685 .detach_and_log_err(cx);
1686 }
1687
1688 fn askpass_delegate(
1689 &self,
1690 operation: impl Into<SharedString>,
1691 window: &mut Window,
1692 cx: &mut Context<Self>,
1693 ) -> AskPassDelegate {
1694 let this = cx.weak_entity();
1695 let operation = operation.into();
1696 let window = window.window_handle();
1697 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1698 window
1699 .update(cx, |_, window, cx| {
1700 this.update(cx, |this, cx| {
1701 this.workspace.update(cx, |workspace, cx| {
1702 workspace.toggle_modal(window, cx, |window, cx| {
1703 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1704 });
1705 })
1706 })
1707 })
1708 .ok();
1709 })
1710 }
1711
1712 fn can_push_and_pull(&self, cx: &App) -> bool {
1713 !self.project.read(cx).is_via_collab()
1714 }
1715
1716 fn get_current_remote(
1717 &mut self,
1718 window: &mut Window,
1719 cx: &mut Context<Self>,
1720 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
1721 let repo = self.active_repository.clone();
1722 let workspace = self.workspace.clone();
1723 let mut cx = window.to_async(cx);
1724
1725 async move {
1726 let Some(repo) = repo else {
1727 return Err(anyhow::anyhow!("No active repository"));
1728 };
1729
1730 let mut current_remotes: Vec<Remote> = repo
1731 .update(&mut cx, |repo, _| {
1732 let Some(current_branch) = repo.current_branch() else {
1733 return Err(anyhow::anyhow!("No active branch"));
1734 };
1735
1736 Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1737 })??
1738 .await??;
1739
1740 if current_remotes.len() == 0 {
1741 return Err(anyhow::anyhow!("No active remote"));
1742 } else if current_remotes.len() == 1 {
1743 return Ok(Some(current_remotes.pop().unwrap()));
1744 } else {
1745 let current_remotes: Vec<_> = current_remotes
1746 .into_iter()
1747 .map(|remotes| remotes.name)
1748 .collect();
1749 let selection = cx
1750 .update(|window, cx| {
1751 picker_prompt::prompt(
1752 "Pick which remote to push to",
1753 current_remotes.clone(),
1754 workspace,
1755 window,
1756 cx,
1757 )
1758 })?
1759 .await?;
1760
1761 Ok(selection.map(|selection| Remote {
1762 name: current_remotes[selection].clone(),
1763 }))
1764 }
1765 }
1766 }
1767
1768 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1769 let mut new_co_authors = Vec::new();
1770 let project = self.project.read(cx);
1771
1772 let Some(room) = self
1773 .workspace
1774 .upgrade()
1775 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1776 else {
1777 return Vec::default();
1778 };
1779
1780 let room = room.read(cx);
1781
1782 for (peer_id, collaborator) in project.collaborators() {
1783 if collaborator.is_host {
1784 continue;
1785 }
1786
1787 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1788 continue;
1789 };
1790 if participant.can_write() && participant.user.email.is_some() {
1791 let email = participant.user.email.clone().unwrap();
1792
1793 new_co_authors.push((
1794 participant
1795 .user
1796 .name
1797 .clone()
1798 .unwrap_or_else(|| participant.user.github_login.clone()),
1799 email,
1800 ))
1801 }
1802 }
1803 if !project.is_local() && !project.is_read_only(cx) {
1804 if let Some(user) = room.local_participant_user(cx) {
1805 if let Some(email) = user.email.clone() {
1806 new_co_authors.push((
1807 user.name
1808 .clone()
1809 .unwrap_or_else(|| user.github_login.clone()),
1810 email.clone(),
1811 ))
1812 }
1813 }
1814 }
1815 new_co_authors
1816 }
1817
1818 fn toggle_fill_co_authors(
1819 &mut self,
1820 _: &ToggleFillCoAuthors,
1821 _: &mut Window,
1822 cx: &mut Context<Self>,
1823 ) {
1824 self.add_coauthors = !self.add_coauthors;
1825 cx.notify();
1826 }
1827
1828 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1829 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1830
1831 let existing_text = message.to_ascii_lowercase();
1832 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1833 let mut ends_with_co_authors = false;
1834 let existing_co_authors = existing_text
1835 .lines()
1836 .filter_map(|line| {
1837 let line = line.trim();
1838 if line.starts_with(&lowercase_co_author_prefix) {
1839 ends_with_co_authors = true;
1840 Some(line)
1841 } else {
1842 ends_with_co_authors = false;
1843 None
1844 }
1845 })
1846 .collect::<HashSet<_>>();
1847
1848 let new_co_authors = self
1849 .potential_co_authors(cx)
1850 .into_iter()
1851 .filter(|(_, email)| {
1852 !existing_co_authors
1853 .iter()
1854 .any(|existing| existing.contains(email.as_str()))
1855 })
1856 .collect::<Vec<_>>();
1857
1858 if new_co_authors.is_empty() {
1859 return;
1860 }
1861
1862 if !ends_with_co_authors {
1863 message.push('\n');
1864 }
1865 for (name, email) in new_co_authors {
1866 message.push('\n');
1867 message.push_str(CO_AUTHOR_PREFIX);
1868 message.push_str(&name);
1869 message.push_str(" <");
1870 message.push_str(&email);
1871 message.push('>');
1872 }
1873 message.push('\n');
1874 }
1875
1876 fn schedule_update(
1877 &mut self,
1878 clear_pending: bool,
1879 window: &mut Window,
1880 cx: &mut Context<Self>,
1881 ) {
1882 let handle = cx.entity().downgrade();
1883 self.reopen_commit_buffer(window, cx);
1884 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1885 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1886 if let Some(git_panel) = handle.upgrade() {
1887 git_panel
1888 .update_in(&mut cx, |git_panel, _, cx| {
1889 if clear_pending {
1890 git_panel.clear_pending();
1891 }
1892 git_panel.update_visible_entries(cx);
1893 git_panel.update_editor_placeholder(cx);
1894 })
1895 .ok();
1896 }
1897 });
1898 }
1899
1900 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1901 let Some(active_repo) = self.active_repository.as_ref() else {
1902 return;
1903 };
1904 let load_buffer = active_repo.update(cx, |active_repo, cx| {
1905 let project = self.project.read(cx);
1906 active_repo.open_commit_buffer(
1907 Some(project.languages().clone()),
1908 project.buffer_store().clone(),
1909 cx,
1910 )
1911 });
1912
1913 cx.spawn_in(window, |git_panel, mut cx| async move {
1914 let buffer = load_buffer.await?;
1915 git_panel.update_in(&mut cx, |git_panel, window, cx| {
1916 if git_panel
1917 .commit_editor
1918 .read(cx)
1919 .buffer()
1920 .read(cx)
1921 .as_singleton()
1922 .as_ref()
1923 != Some(&buffer)
1924 {
1925 git_panel.commit_editor = cx.new(|cx| {
1926 commit_message_editor(
1927 buffer,
1928 git_panel.suggest_commit_message().as_deref(),
1929 git_panel.project.clone(),
1930 true,
1931 window,
1932 cx,
1933 )
1934 });
1935 }
1936 })
1937 })
1938 .detach_and_log_err(cx);
1939 }
1940
1941 fn clear_pending(&mut self) {
1942 self.pending.retain(|v| !v.finished)
1943 }
1944
1945 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1946 self.entries.clear();
1947 let mut changed_entries = Vec::new();
1948 let mut new_entries = Vec::new();
1949 let mut conflict_entries = Vec::new();
1950
1951 let Some(repo) = self.active_repository.as_ref() else {
1952 // Just clear entries if no repository is active.
1953 cx.notify();
1954 return;
1955 };
1956
1957 let repo = repo.read(cx);
1958
1959 for entry in repo.status() {
1960 let is_conflict = repo.has_conflict(&entry.repo_path);
1961 let is_new = entry.status.is_created();
1962 let is_staged = entry.status.is_staged();
1963
1964 if self.pending.iter().any(|pending| {
1965 pending.target_status == TargetStatus::Reverted
1966 && !pending.finished
1967 && pending.repo_paths.contains(&entry.repo_path)
1968 }) {
1969 continue;
1970 }
1971
1972 // dot_git_abs path always has at least one component, namely .git.
1973 let abs_path = repo
1974 .dot_git_abs_path
1975 .parent()
1976 .unwrap()
1977 .join(&entry.repo_path);
1978 let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
1979 let entry = GitStatusEntry {
1980 repo_path: entry.repo_path.clone(),
1981 worktree_path,
1982 abs_path,
1983 status: entry.status,
1984 is_staged,
1985 };
1986
1987 if is_conflict {
1988 conflict_entries.push(entry);
1989 } else if is_new {
1990 new_entries.push(entry);
1991 } else {
1992 changed_entries.push(entry);
1993 }
1994 }
1995
1996 if conflict_entries.len() > 0 {
1997 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1998 header: Section::Conflict,
1999 }));
2000 self.entries.extend(
2001 conflict_entries
2002 .into_iter()
2003 .map(GitListEntry::GitStatusEntry),
2004 );
2005 }
2006
2007 if changed_entries.len() > 0 {
2008 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2009 header: Section::Tracked,
2010 }));
2011 self.entries.extend(
2012 changed_entries
2013 .into_iter()
2014 .map(GitListEntry::GitStatusEntry),
2015 );
2016 }
2017 if new_entries.len() > 0 {
2018 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2019 header: Section::New,
2020 }));
2021 self.entries
2022 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2023 }
2024
2025 self.update_counts(repo);
2026
2027 self.select_first_entry_if_none(cx);
2028
2029 cx.notify();
2030 }
2031
2032 fn header_state(&self, header_type: Section) -> ToggleState {
2033 let (staged_count, count) = match header_type {
2034 Section::New => (self.new_staged_count, self.new_count),
2035 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2036 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2037 };
2038 if staged_count == 0 {
2039 ToggleState::Unselected
2040 } else if count == staged_count {
2041 ToggleState::Selected
2042 } else {
2043 ToggleState::Indeterminate
2044 }
2045 }
2046
2047 fn update_counts(&mut self, repo: &Repository) {
2048 self.conflicted_count = 0;
2049 self.conflicted_staged_count = 0;
2050 self.new_count = 0;
2051 self.tracked_count = 0;
2052 self.new_staged_count = 0;
2053 self.tracked_staged_count = 0;
2054 for entry in &self.entries {
2055 let Some(status_entry) = entry.status_entry() else {
2056 continue;
2057 };
2058 if repo.has_conflict(&status_entry.repo_path) {
2059 self.conflicted_count += 1;
2060 if self.entry_is_staged(status_entry) != Some(false) {
2061 self.conflicted_staged_count += 1;
2062 }
2063 } else if status_entry.status.is_created() {
2064 self.new_count += 1;
2065 if self.entry_is_staged(status_entry) != Some(false) {
2066 self.new_staged_count += 1;
2067 }
2068 } else {
2069 self.tracked_count += 1;
2070 if self.entry_is_staged(status_entry) != Some(false) {
2071 self.tracked_staged_count += 1;
2072 }
2073 }
2074 }
2075 }
2076
2077 fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
2078 for pending in self.pending.iter().rev() {
2079 if pending.repo_paths.contains(&entry.repo_path) {
2080 match pending.target_status {
2081 TargetStatus::Staged => return Some(true),
2082 TargetStatus::Unstaged => return Some(false),
2083 TargetStatus::Reverted => continue,
2084 TargetStatus::Unchanged => continue,
2085 }
2086 }
2087 }
2088 entry.is_staged
2089 }
2090
2091 pub(crate) fn has_staged_changes(&self) -> bool {
2092 self.tracked_staged_count > 0
2093 || self.new_staged_count > 0
2094 || self.conflicted_staged_count > 0
2095 }
2096
2097 pub(crate) fn has_unstaged_changes(&self) -> bool {
2098 self.tracked_count > self.tracked_staged_count
2099 || self.new_count > self.new_staged_count
2100 || self.conflicted_count > self.conflicted_staged_count
2101 }
2102
2103 fn has_conflicts(&self) -> bool {
2104 self.conflicted_count > 0
2105 }
2106
2107 fn has_tracked_changes(&self) -> bool {
2108 self.tracked_count > 0
2109 }
2110
2111 pub fn has_unstaged_conflicts(&self) -> bool {
2112 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2113 }
2114
2115 fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
2116 let Some(workspace) = self.workspace.upgrade() else {
2117 return;
2118 };
2119 let notif_id = NotificationId::Named("git-operation-error".into());
2120
2121 let message = e.to_string().trim().to_string();
2122 let toast;
2123 if message
2124 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2125 .next()
2126 .is_some()
2127 {
2128 return; // Hide the cancelled by user message
2129 } else {
2130 toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
2131 window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
2132 });
2133 }
2134 workspace.update(cx, |workspace, cx| {
2135 workspace.show_toast(toast, cx);
2136 });
2137 }
2138
2139 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2140 let Some(workspace) = self.workspace.upgrade() else {
2141 return;
2142 };
2143
2144 let notification_id = NotificationId::Named("git-remote-info".into());
2145
2146 workspace.update(cx, |workspace, cx| {
2147 workspace.show_notification(notification_id.clone(), cx, |cx| {
2148 let workspace = cx.weak_entity();
2149 cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
2150 });
2151 });
2152 }
2153
2154 pub fn render_spinner(&self) -> Option<impl IntoElement> {
2155 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2156 Icon::new(IconName::ArrowCircle)
2157 .size(IconSize::XSmall)
2158 .color(Color::Info)
2159 .with_animation(
2160 "arrow-circle",
2161 Animation::new(Duration::from_secs(2)).repeat(),
2162 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2163 )
2164 .into_any_element()
2165 })
2166 }
2167
2168 pub fn can_commit(&self) -> bool {
2169 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2170 }
2171
2172 pub fn can_stage_all(&self) -> bool {
2173 self.has_unstaged_changes()
2174 }
2175
2176 pub fn can_unstage_all(&self) -> bool {
2177 self.has_staged_changes()
2178 }
2179
2180 pub(crate) fn render_generate_commit_message_button(&self, cx: &Context<Self>) -> AnyElement {
2181 if self.generate_commit_message_task.is_some() {
2182 return Icon::new(IconName::ArrowCircle)
2183 .size(IconSize::XSmall)
2184 .color(Color::Info)
2185 .with_animation(
2186 "arrow-circle",
2187 Animation::new(Duration::from_secs(2)).repeat(),
2188 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2189 )
2190 .into_any_element();
2191 }
2192
2193 IconButton::new("generate-commit-message", IconName::ZedAssistant)
2194 .shape(ui::IconButtonShape::Square)
2195 .tooltip(Tooltip::for_action_title_in(
2196 "Generate commit message",
2197 &git::GenerateCommitMessage,
2198 &self.commit_editor.focus_handle(cx),
2199 ))
2200 .on_click(cx.listener(move |this, _event, _window, cx| {
2201 this.generate_commit_message(cx);
2202 }))
2203 .into_any_element()
2204 }
2205
2206 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2207 let potential_co_authors = self.potential_co_authors(cx);
2208 if potential_co_authors.is_empty() {
2209 None
2210 } else {
2211 Some(
2212 IconButton::new("co-authors", IconName::Person)
2213 .icon_color(Color::Disabled)
2214 .selected_icon_color(Color::Selected)
2215 .toggle_state(self.add_coauthors)
2216 .tooltip(move |_, cx| {
2217 let title = format!(
2218 "Add co-authored-by:{}{}",
2219 if potential_co_authors.len() == 1 {
2220 ""
2221 } else {
2222 "\n"
2223 },
2224 potential_co_authors
2225 .iter()
2226 .map(|(name, email)| format!(" {} <{}>", name, email))
2227 .join("\n")
2228 );
2229 Tooltip::simple(title, cx)
2230 })
2231 .on_click(cx.listener(|this, _, _, cx| {
2232 this.add_coauthors = !this.add_coauthors;
2233 cx.notify();
2234 }))
2235 .into_any_element(),
2236 )
2237 }
2238 }
2239
2240 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2241 if self.has_unstaged_conflicts() {
2242 (false, "You must resolve conflicts before committing")
2243 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2244 (
2245 false,
2246 "You must have either staged changes or tracked files to commit",
2247 )
2248 } else if self.pending_commit.is_some() {
2249 (false, "Commit in progress")
2250 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2251 (false, "No commit message")
2252 } else if !self.has_write_access(cx) {
2253 (false, "You do not have write access to this project")
2254 } else {
2255 (true, self.commit_button_title())
2256 }
2257 }
2258
2259 pub fn commit_button_title(&self) -> &'static str {
2260 if self.has_staged_changes() {
2261 "Commit"
2262 } else {
2263 "Commit Tracked"
2264 }
2265 }
2266
2267 fn expand_commit_editor(
2268 &mut self,
2269 _: &git::ExpandCommitEditor,
2270 window: &mut Window,
2271 cx: &mut Context<Self>,
2272 ) {
2273 let workspace = self.workspace.clone();
2274 window.defer(cx, move |window, cx| {
2275 workspace
2276 .update(cx, |workspace, cx| {
2277 CommitModal::toggle(workspace, window, cx)
2278 })
2279 .ok();
2280 })
2281 }
2282
2283 pub fn render_footer(
2284 &self,
2285 window: &mut Window,
2286 cx: &mut Context<Self>,
2287 ) -> Option<impl IntoElement> {
2288 let active_repository = self.active_repository.clone()?;
2289 let (can_commit, tooltip) = self.configure_commit_button(cx);
2290 let project = self.project.clone().read(cx);
2291 let panel_editor_style = panel_editor_style(true, window, cx);
2292
2293 let enable_coauthors = self.render_co_authors(cx);
2294
2295 let title = self.commit_button_title();
2296 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2297
2298 let branch = active_repository.read(cx).current_branch().cloned();
2299
2300 let footer_size = px(32.);
2301 let gap = px(8.0);
2302
2303 let max_height = window.line_height() * 5. + gap + footer_size;
2304
2305 let expand_button_size = px(16.);
2306
2307 let git_panel = cx.entity().clone();
2308 let display_name = SharedString::from(Arc::from(
2309 active_repository
2310 .read(cx)
2311 .display_name(project, cx)
2312 .trim_end_matches("/"),
2313 ));
2314
2315 let footer = v_flex()
2316 .child(PanelRepoFooter::new(
2317 "footer-button",
2318 display_name,
2319 branch,
2320 Some(git_panel),
2321 ))
2322 .child(
2323 panel_editor_container(window, cx)
2324 .id("commit-editor-container")
2325 .relative()
2326 .h(max_height)
2327 // .w_full()
2328 // .border_t_1()
2329 // .border_color(cx.theme().colors().border)
2330 .bg(cx.theme().colors().editor_background)
2331 .cursor_text()
2332 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2333 window.focus(&this.commit_editor.focus_handle(cx));
2334 }))
2335 .child(
2336 h_flex()
2337 .id("commit-footer")
2338 .absolute()
2339 .bottom_0()
2340 .right_2()
2341 .gap_0p5()
2342 .h(footer_size)
2343 .flex_none()
2344 .children(enable_coauthors)
2345 .child(self.render_generate_commit_message_button(cx))
2346 .child(
2347 panel_filled_button(title)
2348 .tooltip(move |window, cx| {
2349 if can_commit {
2350 Tooltip::for_action_in(
2351 tooltip,
2352 &Commit,
2353 &editor_focus_handle,
2354 window,
2355 cx,
2356 )
2357 } else {
2358 Tooltip::simple(tooltip, cx)
2359 }
2360 })
2361 .disabled(!can_commit || self.modal_open)
2362 .on_click({
2363 cx.listener(move |this, _: &ClickEvent, window, cx| {
2364 telemetry::event!(
2365 "Git Committed",
2366 source = "Git Panel"
2367 );
2368 this.commit_changes(window, cx)
2369 })
2370 }),
2371 ),
2372 )
2373 // .when(!self.modal_open, |el| {
2374 .child(EditorElement::new(&self.commit_editor, panel_editor_style))
2375 .child(
2376 div()
2377 .absolute()
2378 .top_1()
2379 .right_2()
2380 .opacity(0.5)
2381 .hover(|this| this.opacity(1.0))
2382 .w(expand_button_size)
2383 .child(
2384 panel_icon_button("expand-commit-editor", IconName::Maximize)
2385 .icon_size(IconSize::Small)
2386 .style(ButtonStyle::Transparent)
2387 .width(expand_button_size.into())
2388 .on_click(cx.listener({
2389 move |_, _, window, cx| {
2390 window.dispatch_action(
2391 git::ExpandCommitEditor.boxed_clone(),
2392 cx,
2393 )
2394 }
2395 })),
2396 ),
2397 ),
2398 );
2399
2400 Some(footer)
2401 }
2402
2403 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2404 let active_repository = self.active_repository.as_ref()?;
2405 let branch = active_repository.read(cx).current_branch()?;
2406 let commit = branch.most_recent_commit.as_ref()?.clone();
2407
2408 let this = cx.entity();
2409 Some(
2410 h_flex()
2411 .items_center()
2412 .py_2()
2413 .px(px(8.))
2414 // .bg(cx.theme().colors().background)
2415 // .border_t_1()
2416 .border_color(cx.theme().colors().border)
2417 .gap_1p5()
2418 .child(
2419 div()
2420 .flex_grow()
2421 .overflow_hidden()
2422 .max_w(relative(0.6))
2423 .h_full()
2424 .child(
2425 Label::new(commit.subject.clone())
2426 .size(LabelSize::Small)
2427 .truncate(),
2428 )
2429 .id("commit-msg-hover")
2430 .hoverable_tooltip(move |window, cx| {
2431 GitPanelMessageTooltip::new(
2432 this.clone(),
2433 commit.sha.clone(),
2434 window,
2435 cx,
2436 )
2437 .into()
2438 }),
2439 )
2440 .child(div().flex_1())
2441 .child(
2442 panel_icon_button("undo", IconName::Undo)
2443 .icon_size(IconSize::Small)
2444 .icon_color(Color::Muted)
2445 .tooltip(Tooltip::for_action_title(
2446 if self.has_staged_changes() {
2447 "git reset HEAD^ --soft"
2448 } else {
2449 "git reset HEAD^"
2450 },
2451 &git::Uncommit,
2452 ))
2453 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2454 ),
2455 )
2456 }
2457
2458 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2459 h_flex()
2460 .h_full()
2461 .flex_grow()
2462 .justify_center()
2463 .items_center()
2464 .child(
2465 v_flex()
2466 .gap_3()
2467 .child(if self.active_repository.is_some() {
2468 "No changes to commit"
2469 } else {
2470 "No Git repositories"
2471 })
2472 .text_ui_sm(cx)
2473 .mx_auto()
2474 .text_color(Color::Placeholder.color(cx)),
2475 )
2476 }
2477
2478 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2479 let scroll_bar_style = self.show_scrollbar(cx);
2480 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2481
2482 if !self.should_show_scrollbar(cx)
2483 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2484 {
2485 return None;
2486 }
2487
2488 Some(
2489 div()
2490 .id("git-panel-vertical-scroll")
2491 .occlude()
2492 .flex_none()
2493 .h_full()
2494 .cursor_default()
2495 .when(show_container, |this| this.pl_1().px_1p5())
2496 .when(!show_container, |this| {
2497 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2498 })
2499 .on_mouse_move(cx.listener(|_, _, _, cx| {
2500 cx.notify();
2501 cx.stop_propagation()
2502 }))
2503 .on_hover(|_, _, cx| {
2504 cx.stop_propagation();
2505 })
2506 .on_any_mouse_down(|_, _, cx| {
2507 cx.stop_propagation();
2508 })
2509 .on_mouse_up(
2510 MouseButton::Left,
2511 cx.listener(|this, _, window, cx| {
2512 if !this.scrollbar_state.is_dragging()
2513 && !this.focus_handle.contains_focused(window, cx)
2514 {
2515 this.hide_scrollbar(window, cx);
2516 cx.notify();
2517 }
2518
2519 cx.stop_propagation();
2520 }),
2521 )
2522 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2523 cx.notify();
2524 }))
2525 .children(Scrollbar::vertical(
2526 // percentage as f32..end_offset as f32,
2527 self.scrollbar_state.clone(),
2528 )),
2529 )
2530 }
2531
2532 fn render_buffer_header_controls(
2533 &self,
2534 entity: &Entity<Self>,
2535 file: &Arc<dyn File>,
2536 _: &Window,
2537 cx: &App,
2538 ) -> Option<AnyElement> {
2539 let repo = self.active_repository.as_ref()?.read(cx);
2540 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2541 let ix = self.entry_by_path(&repo_path)?;
2542 let entry = self.entries.get(ix)?;
2543
2544 let is_staged = self.entry_is_staged(entry.status_entry()?);
2545
2546 let checkbox = Checkbox::new("stage-file", is_staged.into())
2547 .disabled(!self.has_write_access(cx))
2548 .fill()
2549 .elevation(ElevationIndex::Surface)
2550 .on_click({
2551 let entry = entry.clone();
2552 let git_panel = entity.downgrade();
2553 move |_, window, cx| {
2554 git_panel
2555 .update(cx, |this, cx| {
2556 this.toggle_staged_for_entry(&entry, window, cx);
2557 cx.stop_propagation();
2558 })
2559 .ok();
2560 }
2561 });
2562 Some(
2563 h_flex()
2564 .id("start-slot")
2565 .text_lg()
2566 .child(checkbox)
2567 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2568 // prevent the list item active state triggering when toggling checkbox
2569 cx.stop_propagation();
2570 })
2571 .into_any_element(),
2572 )
2573 }
2574
2575 fn render_entries(
2576 &self,
2577 has_write_access: bool,
2578 _: &Window,
2579 cx: &mut Context<Self>,
2580 ) -> impl IntoElement {
2581 let entry_count = self.entries.len();
2582
2583 h_flex()
2584 .size_full()
2585 .flex_grow()
2586 .overflow_hidden()
2587 .child(
2588 uniform_list(cx.entity().clone(), "entries", entry_count, {
2589 move |this, range, window, cx| {
2590 let mut items = Vec::with_capacity(range.end - range.start);
2591
2592 for ix in range {
2593 match &this.entries.get(ix) {
2594 Some(GitListEntry::GitStatusEntry(entry)) => {
2595 items.push(this.render_entry(
2596 ix,
2597 entry,
2598 has_write_access,
2599 window,
2600 cx,
2601 ));
2602 }
2603 Some(GitListEntry::Header(header)) => {
2604 items.push(this.render_list_header(
2605 ix,
2606 header,
2607 has_write_access,
2608 window,
2609 cx,
2610 ));
2611 }
2612 None => {}
2613 }
2614 }
2615
2616 items
2617 }
2618 })
2619 .size_full()
2620 .with_sizing_behavior(ListSizingBehavior::Auto)
2621 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2622 .track_scroll(self.scroll_handle.clone()),
2623 )
2624 .on_mouse_down(
2625 MouseButton::Right,
2626 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2627 this.deploy_panel_context_menu(event.position, window, cx)
2628 }),
2629 )
2630 .children(self.render_scrollbar(cx))
2631 }
2632
2633 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2634 Label::new(label.into()).color(color).single_line()
2635 }
2636
2637 fn list_item_height(&self) -> Rems {
2638 rems(1.75)
2639 }
2640
2641 fn render_list_header(
2642 &self,
2643 ix: usize,
2644 header: &GitHeaderEntry,
2645 _: bool,
2646 _: &Window,
2647 _: &Context<Self>,
2648 ) -> AnyElement {
2649 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2650
2651 h_flex()
2652 .id(id)
2653 .h(self.list_item_height())
2654 .w_full()
2655 .items_end()
2656 .px(rems(0.75)) // ~12px
2657 .pb(rems(0.3125)) // ~ 5px
2658 .child(
2659 Label::new(header.title())
2660 .color(Color::Muted)
2661 .size(LabelSize::Small)
2662 .line_height_style(LineHeightStyle::UiLabel)
2663 .single_line(),
2664 )
2665 .into_any_element()
2666 }
2667
2668 fn load_commit_details(
2669 &self,
2670 sha: &str,
2671 cx: &mut Context<Self>,
2672 ) -> Task<anyhow::Result<CommitDetails>> {
2673 let Some(repo) = self.active_repository.clone() else {
2674 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2675 };
2676 repo.update(cx, |repo, cx| {
2677 let show = repo.show(sha);
2678 cx.spawn(|_, _| async move { show.await? })
2679 })
2680 }
2681
2682 fn deploy_entry_context_menu(
2683 &mut self,
2684 position: Point<Pixels>,
2685 ix: usize,
2686 window: &mut Window,
2687 cx: &mut Context<Self>,
2688 ) {
2689 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2690 return;
2691 };
2692 let stage_title = if entry.status.is_staged() == Some(true) {
2693 "Unstage File"
2694 } else {
2695 "Stage File"
2696 };
2697 let restore_title = if entry.status.is_created() {
2698 "Trash File"
2699 } else {
2700 "Restore File"
2701 };
2702 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2703 context_menu
2704 .action(stage_title, ToggleStaged.boxed_clone())
2705 .action(restore_title, git::RestoreFile.boxed_clone())
2706 .separator()
2707 .action("Open Diff", Confirm.boxed_clone())
2708 .action("Open File", SecondaryConfirm.boxed_clone())
2709 });
2710 self.selected_entry = Some(ix);
2711 self.set_context_menu(context_menu, position, window, cx);
2712 }
2713
2714 fn deploy_panel_context_menu(
2715 &mut self,
2716 position: Point<Pixels>,
2717 window: &mut Window,
2718 cx: &mut Context<Self>,
2719 ) {
2720 let context_menu = git_panel_context_menu(window, cx);
2721 self.set_context_menu(context_menu, position, window, cx);
2722 }
2723
2724 fn set_context_menu(
2725 &mut self,
2726 context_menu: Entity<ContextMenu>,
2727 position: Point<Pixels>,
2728 window: &Window,
2729 cx: &mut Context<Self>,
2730 ) {
2731 let subscription = cx.subscribe_in(
2732 &context_menu,
2733 window,
2734 |this, _, _: &DismissEvent, window, cx| {
2735 if this.context_menu.as_ref().is_some_and(|context_menu| {
2736 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2737 }) {
2738 cx.focus_self(window);
2739 }
2740 this.context_menu.take();
2741 cx.notify();
2742 },
2743 );
2744 self.context_menu = Some((context_menu, position, subscription));
2745 cx.notify();
2746 }
2747
2748 fn render_entry(
2749 &self,
2750 ix: usize,
2751 entry: &GitStatusEntry,
2752 has_write_access: bool,
2753 window: &Window,
2754 cx: &Context<Self>,
2755 ) -> AnyElement {
2756 let display_name = entry
2757 .worktree_path
2758 .file_name()
2759 .map(|name| name.to_string_lossy().into_owned())
2760 .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2761
2762 let worktree_path = entry.worktree_path.clone();
2763 let selected = self.selected_entry == Some(ix);
2764 let marked = self.marked_entries.contains(&ix);
2765 let status_style = GitPanelSettings::get_global(cx).status_style;
2766 let status = entry.status;
2767 let has_conflict = status.is_conflicted();
2768 let is_modified = status.is_modified();
2769 let is_deleted = status.is_deleted();
2770
2771 let label_color = if status_style == StatusStyle::LabelColor {
2772 if has_conflict {
2773 Color::Conflict
2774 } else if is_modified {
2775 Color::Modified
2776 } else if is_deleted {
2777 // We don't want a bunch of red labels in the list
2778 Color::Disabled
2779 } else {
2780 Color::Created
2781 }
2782 } else {
2783 Color::Default
2784 };
2785
2786 let path_color = if status.is_deleted() {
2787 Color::Disabled
2788 } else {
2789 Color::Muted
2790 };
2791
2792 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2793 let checkbox_wrapper_id: ElementId =
2794 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2795 let checkbox_id: ElementId =
2796 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2797
2798 let is_entry_staged = self.entry_is_staged(entry);
2799 let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2800
2801 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2802 is_staged = ToggleState::Selected;
2803 }
2804
2805 let handle = cx.weak_entity();
2806
2807 let selected_bg_alpha = 0.08;
2808 let marked_bg_alpha = 0.12;
2809 let state_opacity_step = 0.04;
2810
2811 let base_bg = match (selected, marked) {
2812 (true, true) => cx
2813 .theme()
2814 .status()
2815 .info
2816 .alpha(selected_bg_alpha + marked_bg_alpha),
2817 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2818 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2819 _ => cx.theme().colors().ghost_element_background,
2820 };
2821
2822 let hover_bg = if selected {
2823 cx.theme()
2824 .status()
2825 .info
2826 .alpha(selected_bg_alpha + state_opacity_step)
2827 } else {
2828 cx.theme().colors().ghost_element_hover
2829 };
2830
2831 let active_bg = if selected {
2832 cx.theme()
2833 .status()
2834 .info
2835 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2836 } else {
2837 cx.theme().colors().ghost_element_active
2838 };
2839
2840 h_flex()
2841 .id(id)
2842 .h(self.list_item_height())
2843 .w_full()
2844 .items_center()
2845 .border_1()
2846 .when(selected && self.focus_handle.is_focused(window), |el| {
2847 el.border_color(cx.theme().colors().border_focused)
2848 })
2849 .px(rems(0.75)) // ~12px
2850 .overflow_hidden()
2851 .flex_none()
2852 .gap(DynamicSpacing::Base04.rems(cx))
2853 .bg(base_bg)
2854 .hover(|this| this.bg(hover_bg))
2855 .active(|this| this.bg(active_bg))
2856 .on_click({
2857 cx.listener(move |this, event: &ClickEvent, window, cx| {
2858 this.selected_entry = Some(ix);
2859 cx.notify();
2860 if event.modifiers().secondary() {
2861 this.open_file(&Default::default(), window, cx)
2862 } else {
2863 this.open_diff(&Default::default(), window, cx);
2864 this.focus_handle.focus(window);
2865 }
2866 })
2867 })
2868 .on_mouse_down(
2869 MouseButton::Right,
2870 move |event: &MouseDownEvent, window, cx| {
2871 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2872 if event.button != MouseButton::Right {
2873 return;
2874 }
2875
2876 let Some(this) = handle.upgrade() else {
2877 return;
2878 };
2879 this.update(cx, |this, cx| {
2880 this.deploy_entry_context_menu(event.position, ix, window, cx);
2881 });
2882 cx.stop_propagation();
2883 },
2884 )
2885 // .on_secondary_mouse_down(cx.listener(
2886 // move |this, event: &MouseDownEvent, window, cx| {
2887 // this.deploy_entry_context_menu(event.position, ix, window, cx);
2888 // cx.stop_propagation();
2889 // },
2890 // ))
2891 .child(
2892 div()
2893 .id(checkbox_wrapper_id)
2894 .flex_none()
2895 .occlude()
2896 .cursor_pointer()
2897 .child(
2898 Checkbox::new(checkbox_id, is_staged)
2899 .disabled(!has_write_access)
2900 .fill()
2901 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2902 .elevation(ElevationIndex::Surface)
2903 .on_click({
2904 let entry = entry.clone();
2905 cx.listener(move |this, _, window, cx| {
2906 if !has_write_access {
2907 return;
2908 }
2909 this.toggle_staged_for_entry(
2910 &GitListEntry::GitStatusEntry(entry.clone()),
2911 window,
2912 cx,
2913 );
2914 cx.stop_propagation();
2915 })
2916 })
2917 .tooltip(move |window, cx| {
2918 let tooltip_name = if is_entry_staged.unwrap_or(false) {
2919 "Unstage"
2920 } else {
2921 "Stage"
2922 };
2923
2924 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2925 }),
2926 ),
2927 )
2928 .child(git_status_icon(status, cx))
2929 .child(
2930 h_flex()
2931 .items_center()
2932 .overflow_hidden()
2933 .when_some(worktree_path.parent(), |this, parent| {
2934 let parent_str = parent.to_string_lossy();
2935 if !parent_str.is_empty() {
2936 this.child(
2937 self.entry_label(format!("{}/", parent_str), path_color)
2938 .when(status.is_deleted(), |this| this.strikethrough()),
2939 )
2940 } else {
2941 this
2942 }
2943 })
2944 .child(
2945 self.entry_label(display_name.clone(), label_color)
2946 .when(status.is_deleted(), |this| this.strikethrough()),
2947 ),
2948 )
2949 .into_any_element()
2950 }
2951
2952 fn has_write_access(&self, cx: &App) -> bool {
2953 !self.project.read(cx).is_read_only(cx)
2954 }
2955}
2956
2957impl Render for GitPanel {
2958 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2959 let project = self.project.read(cx);
2960 let has_entries = self.entries.len() > 0;
2961 let room = self
2962 .workspace
2963 .upgrade()
2964 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2965
2966 let has_write_access = self.has_write_access(cx);
2967
2968 let has_co_authors = room.map_or(false, |room| {
2969 room.read(cx)
2970 .remote_participants()
2971 .values()
2972 .any(|remote_participant| remote_participant.can_write())
2973 });
2974
2975 v_flex()
2976 .id("git_panel")
2977 .key_context(self.dispatch_context(window, cx))
2978 .track_focus(&self.focus_handle)
2979 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2980 .when(has_write_access && !project.is_read_only(cx), |this| {
2981 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2982 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2983 }))
2984 .on_action(cx.listener(GitPanel::commit))
2985 })
2986 .on_action(cx.listener(Self::select_first))
2987 .on_action(cx.listener(Self::select_next))
2988 .on_action(cx.listener(Self::select_previous))
2989 .on_action(cx.listener(Self::select_last))
2990 .on_action(cx.listener(Self::close_panel))
2991 .on_action(cx.listener(Self::open_diff))
2992 .on_action(cx.listener(Self::open_file))
2993 .on_action(cx.listener(Self::revert_selected))
2994 .on_action(cx.listener(Self::focus_changes_list))
2995 .on_action(cx.listener(Self::focus_editor))
2996 .on_action(cx.listener(Self::toggle_staged_for_selected))
2997 .on_action(cx.listener(Self::stage_all))
2998 .on_action(cx.listener(Self::unstage_all))
2999 .on_action(cx.listener(Self::restore_tracked_files))
3000 .on_action(cx.listener(Self::clean_all))
3001 .on_action(cx.listener(Self::expand_commit_editor))
3002 .on_action(cx.listener(Self::generate_commit_message_action))
3003 .when(has_write_access && has_co_authors, |git_panel| {
3004 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3005 })
3006 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3007 .on_hover(cx.listener(|this, hovered, window, cx| {
3008 if *hovered {
3009 this.show_scrollbar = true;
3010 this.hide_scrollbar_task.take();
3011 cx.notify();
3012 } else if !this.focus_handle.contains_focused(window, cx) {
3013 this.hide_scrollbar(window, cx);
3014 }
3015 }))
3016 .size_full()
3017 .overflow_hidden()
3018 .bg(ElevationIndex::Surface.bg(cx))
3019 .child(
3020 v_flex()
3021 .size_full()
3022 .map(|this| {
3023 if has_entries {
3024 this.child(self.render_entries(has_write_access, window, cx))
3025 } else {
3026 this.child(self.render_empty_state(cx).into_any_element())
3027 }
3028 })
3029 .children(self.render_footer(window, cx))
3030 .children(self.render_previous_commit(cx))
3031 .into_any_element(),
3032 )
3033 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3034 deferred(
3035 anchored()
3036 .position(*position)
3037 .anchor(gpui::Corner::TopLeft)
3038 .child(menu.clone()),
3039 )
3040 .with_priority(1)
3041 }))
3042 }
3043}
3044
3045impl Focusable for GitPanel {
3046 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3047 self.focus_handle.clone()
3048 }
3049}
3050
3051impl EventEmitter<Event> for GitPanel {}
3052
3053impl EventEmitter<PanelEvent> for GitPanel {}
3054
3055pub(crate) struct GitPanelAddon {
3056 pub(crate) workspace: WeakEntity<Workspace>,
3057}
3058
3059impl editor::Addon for GitPanelAddon {
3060 fn to_any(&self) -> &dyn std::any::Any {
3061 self
3062 }
3063
3064 fn render_buffer_header_controls(
3065 &self,
3066 excerpt_info: &ExcerptInfo,
3067 window: &Window,
3068 cx: &App,
3069 ) -> Option<AnyElement> {
3070 let file = excerpt_info.buffer.file()?;
3071 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3072
3073 git_panel
3074 .read(cx)
3075 .render_buffer_header_controls(&git_panel, &file, window, cx)
3076 }
3077}
3078
3079impl Panel for GitPanel {
3080 fn persistent_name() -> &'static str {
3081 "GitPanel"
3082 }
3083
3084 fn position(&self, _: &Window, cx: &App) -> DockPosition {
3085 GitPanelSettings::get_global(cx).dock
3086 }
3087
3088 fn position_is_valid(&self, position: DockPosition) -> bool {
3089 matches!(position, DockPosition::Left | DockPosition::Right)
3090 }
3091
3092 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3093 settings::update_settings_file::<GitPanelSettings>(
3094 self.fs.clone(),
3095 cx,
3096 move |settings, _| settings.dock = Some(position),
3097 );
3098 }
3099
3100 fn size(&self, _: &Window, cx: &App) -> Pixels {
3101 self.width
3102 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3103 }
3104
3105 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3106 self.width = size;
3107 self.serialize(cx);
3108 cx.notify();
3109 }
3110
3111 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3112 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3113 }
3114
3115 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3116 Some("Git Panel")
3117 }
3118
3119 fn toggle_action(&self) -> Box<dyn Action> {
3120 Box::new(ToggleFocus)
3121 }
3122
3123 fn activation_priority(&self) -> u32 {
3124 2
3125 }
3126}
3127
3128impl PanelHeader for GitPanel {}
3129
3130struct GitPanelMessageTooltip {
3131 commit_tooltip: Option<Entity<CommitTooltip>>,
3132}
3133
3134impl GitPanelMessageTooltip {
3135 fn new(
3136 git_panel: Entity<GitPanel>,
3137 sha: SharedString,
3138 window: &mut Window,
3139 cx: &mut App,
3140 ) -> Entity<Self> {
3141 cx.new(|cx| {
3142 cx.spawn_in(window, |this, mut cx| async move {
3143 let details = git_panel
3144 .update(&mut cx, |git_panel, cx| {
3145 git_panel.load_commit_details(&sha, cx)
3146 })?
3147 .await?;
3148
3149 let commit_details = editor::commit_tooltip::CommitDetails {
3150 sha: details.sha.clone(),
3151 committer_name: details.committer_name.clone(),
3152 committer_email: details.committer_email.clone(),
3153 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3154 message: Some(editor::commit_tooltip::ParsedCommitMessage {
3155 message: details.message.clone(),
3156 ..Default::default()
3157 }),
3158 };
3159
3160 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3161 this.commit_tooltip =
3162 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3163 cx.notify();
3164 })
3165 })
3166 .detach();
3167
3168 Self {
3169 commit_tooltip: None,
3170 }
3171 })
3172 }
3173}
3174
3175impl Render for GitPanelMessageTooltip {
3176 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3177 if let Some(commit_tooltip) = &self.commit_tooltip {
3178 commit_tooltip.clone().into_any_element()
3179 } else {
3180 gpui::Empty.into_any_element()
3181 }
3182 }
3183}
3184
3185fn git_action_tooltip(
3186 label: impl Into<SharedString>,
3187 action: &dyn Action,
3188 command: impl Into<SharedString>,
3189 focus_handle: Option<FocusHandle>,
3190 window: &mut Window,
3191 cx: &mut App,
3192) -> AnyView {
3193 let label = label.into();
3194 let command = command.into();
3195
3196 if let Some(handle) = focus_handle {
3197 Tooltip::with_meta_in(
3198 label.clone(),
3199 Some(action),
3200 command.clone(),
3201 &handle,
3202 window,
3203 cx,
3204 )
3205 } else {
3206 Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
3207 }
3208}
3209
3210#[derive(IntoElement)]
3211struct SplitButton {
3212 pub left: ButtonLike,
3213 pub right: AnyElement,
3214}
3215
3216impl SplitButton {
3217 fn new(
3218 id: impl Into<SharedString>,
3219 left_label: impl Into<SharedString>,
3220 ahead_count: usize,
3221 behind_count: usize,
3222 left_icon: Option<IconName>,
3223 left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
3224 tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
3225 ) -> Self {
3226 let id = id.into();
3227
3228 fn count(count: usize) -> impl IntoElement {
3229 h_flex()
3230 .ml_neg_px()
3231 .h(rems(0.875))
3232 .items_center()
3233 .overflow_hidden()
3234 .px_0p5()
3235 .child(
3236 Label::new(count.to_string())
3237 .size(LabelSize::XSmall)
3238 .line_height_style(LineHeightStyle::UiLabel),
3239 )
3240 }
3241
3242 let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
3243
3244 let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
3245 format!("split-button-left-{}", id).into(),
3246 ))
3247 .layer(ui::ElevationIndex::ModalSurface)
3248 .size(ui::ButtonSize::Compact)
3249 .when(should_render_counts, |this| {
3250 this.child(
3251 h_flex()
3252 .ml_neg_0p5()
3253 .mr_1()
3254 .when(behind_count > 0, |this| {
3255 this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
3256 .child(count(behind_count))
3257 })
3258 .when(ahead_count > 0, |this| {
3259 this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
3260 .child(count(ahead_count))
3261 }),
3262 )
3263 })
3264 .when_some(left_icon, |this, left_icon| {
3265 this.child(
3266 h_flex()
3267 .ml_neg_0p5()
3268 .mr_1()
3269 .child(Icon::new(left_icon).size(IconSize::XSmall)),
3270 )
3271 })
3272 .child(
3273 div()
3274 .child(Label::new(left_label).size(LabelSize::Small))
3275 .mr_0p5(),
3276 )
3277 .on_click(left_on_click)
3278 .tooltip(tooltip);
3279
3280 let right =
3281 render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
3282 .into_any_element();
3283 // .on_click(right_on_click);
3284
3285 Self { left, right }
3286 }
3287}
3288
3289impl RenderOnce for SplitButton {
3290 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3291 h_flex()
3292 .rounded_md()
3293 .border_1()
3294 .border_color(cx.theme().colors().text_muted.alpha(0.12))
3295 .child(self.left)
3296 .child(
3297 div()
3298 .h_full()
3299 .w_px()
3300 .bg(cx.theme().colors().text_muted.alpha(0.16)),
3301 )
3302 .child(self.right)
3303 .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3304 .shadow(smallvec![BoxShadow {
3305 color: hsla(0.0, 0.0, 0.0, 0.16),
3306 offset: point(px(0.), px(1.)),
3307 blur_radius: px(0.),
3308 spread_radius: px(0.),
3309 }])
3310 }
3311}
3312
3313fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3314 PopoverMenu::new(id.into())
3315 .trigger(
3316 ui::ButtonLike::new_rounded_right("split-button-right")
3317 .layer(ui::ElevationIndex::ModalSurface)
3318 .size(ui::ButtonSize::None)
3319 .child(
3320 div()
3321 .px_1()
3322 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3323 ),
3324 )
3325 .menu(move |window, cx| {
3326 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3327 context_menu
3328 .action("Fetch", git::Fetch.boxed_clone())
3329 .action("Pull", git::Pull.boxed_clone())
3330 .separator()
3331 .action("Push", git::Push.boxed_clone())
3332 .action("Force Push", git::ForcePush.boxed_clone())
3333 }))
3334 })
3335 .anchor(Corner::TopRight)
3336}
3337
3338#[derive(IntoElement, IntoComponent)]
3339#[component(scope = "git_panel")]
3340pub struct PanelRepoFooter {
3341 id: SharedString,
3342 active_repository: SharedString,
3343 branch: Option<Branch>,
3344 // Getting a GitPanel in previews will be difficult.
3345 //
3346 // For now just take an option here, and we won't bind handlers to buttons in previews.
3347 git_panel: Option<Entity<GitPanel>>,
3348}
3349
3350impl PanelRepoFooter {
3351 pub fn new(
3352 id: impl Into<SharedString>,
3353 active_repository: SharedString,
3354 branch: Option<Branch>,
3355 git_panel: Option<Entity<GitPanel>>,
3356 ) -> Self {
3357 Self {
3358 id: id.into(),
3359 active_repository,
3360 branch,
3361 git_panel,
3362 }
3363 }
3364
3365 pub fn new_preview(
3366 id: impl Into<SharedString>,
3367 active_repository: SharedString,
3368 branch: Option<Branch>,
3369 ) -> Self {
3370 Self {
3371 id: id.into(),
3372 active_repository,
3373 branch,
3374 git_panel: None,
3375 }
3376 }
3377
3378 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3379 PopoverMenu::new(id.into())
3380 .trigger(
3381 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3382 .icon_size(IconSize::Small)
3383 .icon_color(Color::Muted),
3384 )
3385 .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3386 .anchor(Corner::TopRight)
3387 }
3388
3389 fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3390 if let Some(git_panel) = self.git_panel.clone() {
3391 Some(git_panel.focus_handle(cx))
3392 } else {
3393 None
3394 }
3395 }
3396
3397 fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3398 let panel = self.git_panel.clone();
3399 let panel_focus_handle = self.panel_focus_handle(cx);
3400
3401 SplitButton::new(
3402 id,
3403 "Push",
3404 ahead as usize,
3405 0,
3406 None,
3407 move |_, window, cx| {
3408 if let Some(panel) = panel.as_ref() {
3409 panel.update(cx, |panel, cx| {
3410 panel.push(false, window, cx);
3411 });
3412 }
3413 },
3414 move |window, cx| {
3415 git_action_tooltip(
3416 "Push committed changes to remote",
3417 &git::Push,
3418 "git push",
3419 panel_focus_handle.clone(),
3420 window,
3421 cx,
3422 )
3423 },
3424 )
3425 }
3426
3427 fn render_pull_button(
3428 &self,
3429 id: SharedString,
3430 ahead: u32,
3431 behind: u32,
3432 cx: &mut App,
3433 ) -> SplitButton {
3434 let panel = self.git_panel.clone();
3435 let panel_focus_handle = self.panel_focus_handle(cx);
3436
3437 SplitButton::new(
3438 id,
3439 "Pull",
3440 ahead as usize,
3441 behind as usize,
3442 None,
3443 move |_, window, cx| {
3444 if let Some(panel) = panel.as_ref() {
3445 panel.update(cx, |panel, cx| {
3446 panel.pull(window, cx);
3447 });
3448 }
3449 },
3450 move |window, cx| {
3451 git_action_tooltip(
3452 "Pull",
3453 &git::Pull,
3454 "git pull",
3455 panel_focus_handle.clone(),
3456 window,
3457 cx,
3458 )
3459 },
3460 )
3461 }
3462
3463 fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3464 let panel = self.git_panel.clone();
3465 let panel_focus_handle = self.panel_focus_handle(cx);
3466
3467 SplitButton::new(
3468 id,
3469 "Fetch",
3470 0,
3471 0,
3472 Some(IconName::ArrowCircle),
3473 move |_, window, cx| {
3474 if let Some(panel) = panel.as_ref() {
3475 panel.update(cx, |panel, cx| {
3476 panel.fetch(window, cx);
3477 });
3478 }
3479 },
3480 move |window, cx| {
3481 git_action_tooltip(
3482 "Fetch updates from remote",
3483 &git::Fetch,
3484 "git fetch",
3485 panel_focus_handle.clone(),
3486 window,
3487 cx,
3488 )
3489 },
3490 )
3491 }
3492
3493 fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3494 let panel = self.git_panel.clone();
3495 let panel_focus_handle = self.panel_focus_handle(cx);
3496
3497 SplitButton::new(
3498 id,
3499 "Publish",
3500 0,
3501 0,
3502 Some(IconName::ArrowUpFromLine),
3503 move |_, window, cx| {
3504 if let Some(panel) = panel.as_ref() {
3505 panel.update(cx, |panel, cx| {
3506 panel.push(false, window, cx);
3507 });
3508 }
3509 },
3510 move |window, cx| {
3511 git_action_tooltip(
3512 "Publish branch to remote",
3513 &git::Push,
3514 "git push --set-upstream",
3515 panel_focus_handle.clone(),
3516 window,
3517 cx,
3518 )
3519 },
3520 )
3521 }
3522
3523 fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3524 let panel = self.git_panel.clone();
3525 let panel_focus_handle = self.panel_focus_handle(cx);
3526
3527 SplitButton::new(
3528 id,
3529 "Republish",
3530 0,
3531 0,
3532 Some(IconName::ArrowUpFromLine),
3533 move |_, window, cx| {
3534 if let Some(panel) = panel.as_ref() {
3535 panel.update(cx, |panel, cx| {
3536 panel.push(false, window, cx);
3537 });
3538 }
3539 },
3540 move |window, cx| {
3541 git_action_tooltip(
3542 "Re-publish branch to remote",
3543 &git::Push,
3544 "git push --set-upstream",
3545 panel_focus_handle.clone(),
3546 window,
3547 cx,
3548 )
3549 },
3550 )
3551 }
3552
3553 fn render_relevant_button(
3554 &self,
3555 id: impl Into<SharedString>,
3556 branch: &Branch,
3557 cx: &mut App,
3558 ) -> Option<impl IntoElement> {
3559 if let Some(git_panel) = self.git_panel.as_ref() {
3560 if !git_panel.read(cx).can_push_and_pull(cx) {
3561 return None;
3562 }
3563 }
3564 let id = id.into();
3565 let upstream = branch.upstream.as_ref();
3566 Some(match upstream {
3567 Some(Upstream {
3568 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3569 ..
3570 }) => match (*ahead, *behind) {
3571 (0, 0) => self.render_fetch_button(id, cx),
3572 (ahead, 0) => self.render_push_button(id, ahead, cx),
3573 (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3574 },
3575 Some(Upstream {
3576 tracking: UpstreamTracking::Gone,
3577 ..
3578 }) => self.render_republish_button(id, cx),
3579 None => self.render_publish_button(id, cx),
3580 })
3581 }
3582}
3583
3584impl RenderOnce for PanelRepoFooter {
3585 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3586 let active_repo = self.active_repository.clone();
3587 let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3588 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3589 .style(ButtonStyle::Transparent)
3590 .size(ButtonSize::None)
3591 .label_size(LabelSize::Small)
3592 .color(Color::Muted);
3593
3594 let project = self
3595 .git_panel
3596 .as_ref()
3597 .map(|panel| panel.read(cx).project.clone());
3598
3599 let repo = self
3600 .git_panel
3601 .as_ref()
3602 .and_then(|panel| panel.read(cx).active_repository.clone());
3603
3604 let single_repo = project
3605 .as_ref()
3606 .map(|project| {
3607 filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3608 })
3609 .unwrap_or(true);
3610
3611 let repo_selector = PopoverMenu::new("repository-switcher")
3612 .menu({
3613 let project = project.clone();
3614 move |window, cx| {
3615 let project = project.clone()?;
3616 Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3617 }
3618 })
3619 .trigger_with_tooltip(
3620 repo_selector_trigger.disabled(single_repo).truncate(true),
3621 Tooltip::text("Switch active repository"),
3622 )
3623 .attach(gpui::Corner::BottomLeft)
3624 .into_any_element();
3625
3626 let branch = self.branch.clone();
3627 let branch_name = branch
3628 .as_ref()
3629 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3630
3631 let branch_selector_button = Button::new("branch-selector", branch_name)
3632 .style(ButtonStyle::Transparent)
3633 .size(ButtonSize::None)
3634 .label_size(LabelSize::Small)
3635 .truncate(true)
3636 .tooltip(Tooltip::for_action_title(
3637 "Switch Branch",
3638 &zed_actions::git::Branch,
3639 ))
3640 .on_click(|_, window, cx| {
3641 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3642 });
3643
3644 let branch_selector = PopoverMenu::new("popover-button")
3645 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3646 .trigger_with_tooltip(
3647 branch_selector_button,
3648 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3649 )
3650 .anchor(Corner::TopLeft)
3651 .offset(gpui::Point {
3652 x: px(0.0),
3653 y: px(-2.0),
3654 });
3655
3656 let spinner = self
3657 .git_panel
3658 .as_ref()
3659 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3660
3661 h_flex()
3662 .w_full()
3663 .px_2()
3664 .h(px(36.))
3665 .items_center()
3666 .justify_between()
3667 .child(
3668 h_flex()
3669 .flex_1()
3670 .overflow_hidden()
3671 .items_center()
3672 .child(
3673 div().child(
3674 Icon::new(IconName::GitBranchSmall)
3675 .size(IconSize::Small)
3676 .color(Color::Muted),
3677 ),
3678 )
3679 .child(repo_selector)
3680 .when_some(branch.clone(), |this, _| {
3681 this.child(
3682 div()
3683 .text_color(cx.theme().colors().text_muted)
3684 .text_sm()
3685 .child("/"),
3686 )
3687 })
3688 .child(branch_selector),
3689 )
3690 .child(
3691 h_flex()
3692 .gap_1()
3693 .flex_shrink_0()
3694 .children(spinner)
3695 .child(self.render_overflow_menu(overflow_menu_id))
3696 .when_some(branch, |this, branch| {
3697 let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3698 this.children(button)
3699 }),
3700 )
3701 }
3702}
3703
3704impl ComponentPreview for PanelRepoFooter {
3705 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3706 let unknown_upstream = None;
3707 let no_remote_upstream = Some(UpstreamTracking::Gone);
3708 let ahead_of_upstream = Some(
3709 UpstreamTrackingStatus {
3710 ahead: 2,
3711 behind: 0,
3712 }
3713 .into(),
3714 );
3715 let behind_upstream = Some(
3716 UpstreamTrackingStatus {
3717 ahead: 0,
3718 behind: 2,
3719 }
3720 .into(),
3721 );
3722 let ahead_and_behind_upstream = Some(
3723 UpstreamTrackingStatus {
3724 ahead: 3,
3725 behind: 1,
3726 }
3727 .into(),
3728 );
3729
3730 let not_ahead_or_behind_upstream = Some(
3731 UpstreamTrackingStatus {
3732 ahead: 0,
3733 behind: 0,
3734 }
3735 .into(),
3736 );
3737
3738 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3739 Branch {
3740 is_head: true,
3741 name: "some-branch".into(),
3742 upstream: upstream.map(|tracking| Upstream {
3743 ref_name: "origin/some-branch".into(),
3744 tracking,
3745 }),
3746 most_recent_commit: Some(CommitSummary {
3747 sha: "abc123".into(),
3748 subject: "Modify stuff".into(),
3749 commit_timestamp: 1710932954,
3750 }),
3751 }
3752 }
3753
3754 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3755 Branch {
3756 is_head: true,
3757 name: branch_name.to_string().into(),
3758 upstream: upstream.map(|tracking| Upstream {
3759 ref_name: format!("zed/{}", branch_name).into(),
3760 tracking,
3761 }),
3762 most_recent_commit: Some(CommitSummary {
3763 sha: "abc123".into(),
3764 subject: "Modify stuff".into(),
3765 commit_timestamp: 1710932954,
3766 }),
3767 }
3768 }
3769
3770 fn active_repository(id: usize) -> SharedString {
3771 format!("repo-{}", id).into()
3772 }
3773
3774 let example_width = px(340.);
3775
3776 v_flex()
3777 .gap_6()
3778 .w_full()
3779 .flex_none()
3780 .children(vec![example_group_with_title(
3781 "Action Button States",
3782 vec![
3783 single_example(
3784 "No Branch",
3785 div()
3786 .w(example_width)
3787 .overflow_hidden()
3788 .child(PanelRepoFooter::new_preview(
3789 "no-branch",
3790 active_repository(1).clone(),
3791 None,
3792 ))
3793 .into_any_element(),
3794 )
3795 .grow(),
3796 single_example(
3797 "Remote status unknown",
3798 div()
3799 .w(example_width)
3800 .overflow_hidden()
3801 .child(PanelRepoFooter::new_preview(
3802 "unknown-upstream",
3803 active_repository(2).clone(),
3804 Some(branch(unknown_upstream)),
3805 ))
3806 .into_any_element(),
3807 )
3808 .grow(),
3809 single_example(
3810 "No Remote Upstream",
3811 div()
3812 .w(example_width)
3813 .overflow_hidden()
3814 .child(PanelRepoFooter::new_preview(
3815 "no-remote-upstream",
3816 active_repository(3).clone(),
3817 Some(branch(no_remote_upstream)),
3818 ))
3819 .into_any_element(),
3820 )
3821 .grow(),
3822 single_example(
3823 "Not Ahead or Behind",
3824 div()
3825 .w(example_width)
3826 .overflow_hidden()
3827 .child(PanelRepoFooter::new_preview(
3828 "not-ahead-or-behind",
3829 active_repository(4).clone(),
3830 Some(branch(not_ahead_or_behind_upstream)),
3831 ))
3832 .into_any_element(),
3833 )
3834 .grow(),
3835 single_example(
3836 "Behind remote",
3837 div()
3838 .w(example_width)
3839 .overflow_hidden()
3840 .child(PanelRepoFooter::new_preview(
3841 "behind-remote",
3842 active_repository(5).clone(),
3843 Some(branch(behind_upstream)),
3844 ))
3845 .into_any_element(),
3846 )
3847 .grow(),
3848 single_example(
3849 "Ahead of remote",
3850 div()
3851 .w(example_width)
3852 .overflow_hidden()
3853 .child(PanelRepoFooter::new_preview(
3854 "ahead-of-remote",
3855 active_repository(6).clone(),
3856 Some(branch(ahead_of_upstream)),
3857 ))
3858 .into_any_element(),
3859 )
3860 .grow(),
3861 single_example(
3862 "Ahead and behind remote",
3863 div()
3864 .w(example_width)
3865 .overflow_hidden()
3866 .child(PanelRepoFooter::new_preview(
3867 "ahead-and-behind",
3868 active_repository(7).clone(),
3869 Some(branch(ahead_and_behind_upstream)),
3870 ))
3871 .into_any_element(),
3872 )
3873 .grow(),
3874 ],
3875 )
3876 .grow()
3877 .vertical()])
3878 .children(vec![example_group_with_title(
3879 "Labels",
3880 vec![
3881 single_example(
3882 "Short Branch & Repo",
3883 div()
3884 .w(example_width)
3885 .overflow_hidden()
3886 .child(PanelRepoFooter::new_preview(
3887 "short-branch",
3888 SharedString::from("zed"),
3889 Some(custom("main", behind_upstream)),
3890 ))
3891 .into_any_element(),
3892 )
3893 .grow(),
3894 single_example(
3895 "Long Branch",
3896 div()
3897 .w(example_width)
3898 .overflow_hidden()
3899 .child(PanelRepoFooter::new_preview(
3900 "long-branch",
3901 SharedString::from("zed"),
3902 Some(custom(
3903 "redesign-and-update-git-ui-list-entry-style",
3904 behind_upstream,
3905 )),
3906 ))
3907 .into_any_element(),
3908 )
3909 .grow(),
3910 single_example(
3911 "Long Repo",
3912 div()
3913 .w(example_width)
3914 .overflow_hidden()
3915 .child(PanelRepoFooter::new_preview(
3916 "long-repo",
3917 SharedString::from("zed-industries-community-examples"),
3918 Some(custom("gpui", ahead_of_upstream)),
3919 ))
3920 .into_any_element(),
3921 )
3922 .grow(),
3923 single_example(
3924 "Long Repo & Branch",
3925 div()
3926 .w(example_width)
3927 .overflow_hidden()
3928 .child(PanelRepoFooter::new_preview(
3929 "long-repo-and-branch",
3930 SharedString::from("zed-industries-community-examples"),
3931 Some(custom(
3932 "redesign-and-update-git-ui-list-entry-style",
3933 behind_upstream,
3934 )),
3935 ))
3936 .into_any_element(),
3937 )
3938 .grow(),
3939 single_example(
3940 "Uppercase Repo",
3941 div()
3942 .w(example_width)
3943 .overflow_hidden()
3944 .child(PanelRepoFooter::new_preview(
3945 "uppercase-repo",
3946 SharedString::from("LICENSES"),
3947 Some(custom("main", ahead_of_upstream)),
3948 ))
3949 .into_any_element(),
3950 )
3951 .grow(),
3952 single_example(
3953 "Uppercase Branch",
3954 div()
3955 .w(example_width)
3956 .overflow_hidden()
3957 .child(PanelRepoFooter::new_preview(
3958 "uppercase-branch",
3959 SharedString::from("zed"),
3960 Some(custom("update-README", behind_upstream)),
3961 ))
3962 .into_any_element(),
3963 )
3964 .grow(),
3965 ],
3966 )
3967 .grow()
3968 .vertical()])
3969 .into_any_element()
3970 }
3971}
3972
3973#[cfg(test)]
3974mod tests {
3975 use git::status::StatusCode;
3976 use gpui::TestAppContext;
3977 use project::{FakeFs, WorktreeSettings};
3978 use serde_json::json;
3979 use settings::SettingsStore;
3980 use theme::LoadThemes;
3981 use util::path;
3982
3983 use super::*;
3984
3985 fn init_test(cx: &mut gpui::TestAppContext) {
3986 if std::env::var("RUST_LOG").is_ok() {
3987 env_logger::try_init().ok();
3988 }
3989
3990 cx.update(|cx| {
3991 let settings_store = SettingsStore::test(cx);
3992 cx.set_global(settings_store);
3993 WorktreeSettings::register(cx);
3994 workspace::init_settings(cx);
3995 theme::init(LoadThemes::JustBase, cx);
3996 language::init(cx);
3997 editor::init(cx);
3998 Project::init_settings(cx);
3999 crate::init(cx);
4000 });
4001 }
4002
4003 #[gpui::test]
4004 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4005 init_test(cx);
4006 let fs = FakeFs::new(cx.background_executor.clone());
4007 fs.insert_tree(
4008 "/root",
4009 json!({
4010 "zed": {
4011 ".git": {},
4012 "crates": {
4013 "gpui": {
4014 "gpui.rs": "fn main() {}"
4015 },
4016 "util": {
4017 "util.rs": "fn do_it() {}"
4018 }
4019 }
4020 },
4021 }),
4022 )
4023 .await;
4024
4025 fs.set_status_for_repo_via_git_operation(
4026 Path::new("/root/zed/.git"),
4027 &[
4028 (
4029 Path::new("crates/gpui/gpui.rs"),
4030 StatusCode::Modified.worktree(),
4031 ),
4032 (
4033 Path::new("crates/util/util.rs"),
4034 StatusCode::Modified.worktree(),
4035 ),
4036 ],
4037 );
4038
4039 let project =
4040 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4041 let (workspace, cx) =
4042 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4043
4044 cx.read(|cx| {
4045 project
4046 .read(cx)
4047 .worktrees(cx)
4048 .nth(0)
4049 .unwrap()
4050 .read(cx)
4051 .as_local()
4052 .unwrap()
4053 .scan_complete()
4054 })
4055 .await;
4056
4057 cx.executor().run_until_parked();
4058
4059 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4060 let panel = cx.new_window_entity(|window, cx| {
4061 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4062 });
4063
4064 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4065 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4066 });
4067 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4068 handle.await;
4069
4070 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4071 pretty_assertions::assert_eq!(
4072 entries,
4073 [
4074 GitListEntry::Header(GitHeaderEntry {
4075 header: Section::Tracked
4076 }),
4077 GitListEntry::GitStatusEntry(GitStatusEntry {
4078 abs_path: "/root/zed/crates/gpui/gpui.rs".into(),
4079 repo_path: "crates/gpui/gpui.rs".into(),
4080 worktree_path: Path::new("gpui.rs").into(),
4081 status: StatusCode::Modified.worktree(),
4082 is_staged: Some(false),
4083 }),
4084 GitListEntry::GitStatusEntry(GitStatusEntry {
4085 abs_path: "/root/zed/crates/util/util.rs".into(),
4086 repo_path: "crates/util/util.rs".into(),
4087 worktree_path: Path::new("../util/util.rs").into(),
4088 status: StatusCode::Modified.worktree(),
4089 is_staged: Some(false),
4090 },),
4091 ],
4092 );
4093
4094 cx.update_window_entity(&panel, |panel, window, cx| {
4095 panel.select_last(&Default::default(), window, cx);
4096 assert_eq!(panel.selected_entry, Some(2));
4097 panel.open_diff(&Default::default(), window, cx);
4098 });
4099 cx.run_until_parked();
4100
4101 let worktree_roots = workspace.update(cx, |workspace, cx| {
4102 workspace
4103 .worktrees(cx)
4104 .map(|worktree| worktree.read(cx).abs_path())
4105 .collect::<Vec<_>>()
4106 });
4107 pretty_assertions::assert_eq!(
4108 worktree_roots,
4109 vec![
4110 Path::new("/root/zed/crates/gpui").into(),
4111 Path::new("/root/zed/crates/util/util.rs").into(),
4112 ]
4113 );
4114
4115 let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4116 let git_store = project.git_store().read(cx);
4117 // The repo that comes from the single-file worktree can't be selected through the UI.
4118 let filtered_entries = filtered_repository_entries(git_store, cx)
4119 .iter()
4120 .map(|repo| repo.read(cx).worktree_abs_path.clone())
4121 .collect::<Vec<_>>();
4122 assert_eq!(
4123 filtered_entries,
4124 [Path::new("/root/zed/crates/gpui").into()]
4125 );
4126 // But we can select it artificially here.
4127 git_store
4128 .all_repositories()
4129 .into_iter()
4130 .find(|repo| {
4131 &*repo.read(cx).worktree_abs_path == Path::new("/root/zed/crates/util/util.rs")
4132 })
4133 .unwrap()
4134 });
4135
4136 // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4137 repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4138 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4139 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4140 });
4141 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4142 handle.await;
4143 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4144 pretty_assertions::assert_eq!(
4145 entries,
4146 [
4147 GitListEntry::Header(GitHeaderEntry {
4148 header: Section::Tracked
4149 }),
4150 GitListEntry::GitStatusEntry(GitStatusEntry {
4151 abs_path: "/root/zed/crates/gpui/gpui.rs".into(),
4152 repo_path: "crates/gpui/gpui.rs".into(),
4153 worktree_path: Path::new("../../gpui/gpui.rs").into(),
4154 status: StatusCode::Modified.worktree(),
4155 is_staged: Some(false),
4156 }),
4157 GitListEntry::GitStatusEntry(GitStatusEntry {
4158 abs_path: "/root/zed/crates/util/util.rs".into(),
4159 repo_path: "crates/util/util.rs".into(),
4160 worktree_path: Path::new("util.rs").into(),
4161 status: StatusCode::Modified.worktree(),
4162 is_staged: Some(false),
4163 },),
4164 ],
4165 );
4166 }
4167}