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