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