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