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