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