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