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 commit_button_title(&self) -> &'static str {
1989 if self.has_staged_changes() {
1990 "Commit"
1991 } else {
1992 "Commit Tracked"
1993 }
1994 }
1995
1996 pub fn render_footer(
1997 &self,
1998 window: &mut Window,
1999 cx: &mut Context<Self>,
2000 ) -> Option<impl IntoElement> {
2001 let project = self.project.clone().read(cx);
2002 let active_repository = self.active_repository.clone();
2003 let panel_editor_style = panel_editor_style(true, window, cx);
2004
2005 if let Some(active_repo) = active_repository {
2006 let (can_commit, tooltip) = self.configure_commit_button(cx);
2007
2008 let enable_coauthors = self.render_co_authors(cx);
2009
2010 let title = self.commit_button_title();
2011 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2012
2013 let branch = active_repo.read(cx).current_branch().cloned();
2014
2015 let footer_size = px(32.);
2016 let gap = px(8.0);
2017
2018 let max_height = window.line_height() * 5. + gap + footer_size;
2019
2020 let expand_button_size = px(16.);
2021
2022 let git_panel = cx.entity().clone();
2023 let display_name = SharedString::from(Arc::from(
2024 active_repo
2025 .read(cx)
2026 .display_name(project, cx)
2027 .trim_end_matches("/"),
2028 ));
2029 let branches = branch_picker::popover(self.project.clone(), window, cx);
2030 let footer = v_flex()
2031 .child(PanelRepoFooter::new(
2032 "footer-button",
2033 display_name,
2034 branch,
2035 Some(git_panel),
2036 Some(branches),
2037 ))
2038 .child(
2039 panel_editor_container(window, cx)
2040 .id("commit-editor-container")
2041 .relative()
2042 .h(max_height)
2043 // .w_full()
2044 // .border_t_1()
2045 // .border_color(cx.theme().colors().border)
2046 .bg(cx.theme().colors().editor_background)
2047 .cursor_text()
2048 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2049 window.focus(&this.commit_editor.focus_handle(cx));
2050 }))
2051 .child(
2052 h_flex()
2053 .id("commit-footer")
2054 .absolute()
2055 .bottom_0()
2056 .right_2()
2057 .h(footer_size)
2058 .flex_none()
2059 .children(enable_coauthors)
2060 .child(
2061 panel_filled_button(title)
2062 .tooltip(move |window, cx| {
2063 if can_commit {
2064 Tooltip::for_action_in(
2065 tooltip,
2066 &Commit,
2067 &editor_focus_handle,
2068 window,
2069 cx,
2070 )
2071 } else {
2072 Tooltip::simple(tooltip, cx)
2073 }
2074 })
2075 .disabled(!can_commit || self.modal_open)
2076 .on_click({
2077 cx.listener(move |this, _: &ClickEvent, window, cx| {
2078 this.commit_changes(window, cx)
2079 })
2080 }),
2081 ),
2082 )
2083 // .when(!self.modal_open, |el| {
2084 .child(EditorElement::new(&self.commit_editor, panel_editor_style))
2085 .child(
2086 div()
2087 .absolute()
2088 .top_1()
2089 .right_2()
2090 .opacity(0.5)
2091 .hover(|this| this.opacity(1.0))
2092 .w(expand_button_size)
2093 .child(
2094 panel_icon_button("expand-commit-editor", IconName::Maximize)
2095 .icon_size(IconSize::Small)
2096 .style(ButtonStyle::Transparent)
2097 .width(expand_button_size.into())
2098 .on_click(cx.listener({
2099 move |_, _, window, cx| {
2100 window.dispatch_action(
2101 git::ShowCommitEditor.boxed_clone(),
2102 cx,
2103 )
2104 }
2105 })),
2106 ),
2107 ),
2108 );
2109
2110 Some(footer)
2111 } else {
2112 None
2113 }
2114 }
2115
2116 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2117 let active_repository = self.active_repository.as_ref()?;
2118 let branch = active_repository.read(cx).current_branch()?;
2119 let commit = branch.most_recent_commit.as_ref()?.clone();
2120
2121 let this = cx.entity();
2122 Some(
2123 h_flex()
2124 .items_center()
2125 .py_2()
2126 .px(px(8.))
2127 // .bg(cx.theme().colors().background)
2128 // .border_t_1()
2129 .border_color(cx.theme().colors().border)
2130 .gap_1p5()
2131 .child(
2132 div()
2133 .flex_grow()
2134 .overflow_hidden()
2135 .max_w(relative(0.6))
2136 .h_full()
2137 .child(
2138 Label::new(commit.subject.clone())
2139 .size(LabelSize::Small)
2140 .truncate(),
2141 )
2142 .id("commit-msg-hover")
2143 .hoverable_tooltip(move |window, cx| {
2144 GitPanelMessageTooltip::new(
2145 this.clone(),
2146 commit.sha.clone(),
2147 window,
2148 cx,
2149 )
2150 .into()
2151 }),
2152 )
2153 .child(div().flex_1())
2154 .child(
2155 panel_icon_button("undo", IconName::Undo)
2156 .icon_size(IconSize::Small)
2157 .icon_color(Color::Muted)
2158 .tooltip(Tooltip::for_action_title(
2159 if self.has_staged_changes() {
2160 "git reset HEAD^ --soft"
2161 } else {
2162 "git reset HEAD^"
2163 },
2164 &git::Uncommit,
2165 ))
2166 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2167 ),
2168 )
2169 }
2170
2171 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2172 h_flex()
2173 .h_full()
2174 .flex_grow()
2175 .justify_center()
2176 .items_center()
2177 .child(
2178 v_flex()
2179 .gap_3()
2180 .child(if self.active_repository.is_some() {
2181 "No changes to commit"
2182 } else {
2183 "No Git repositories"
2184 })
2185 .text_ui_sm(cx)
2186 .mx_auto()
2187 .text_color(Color::Placeholder.color(cx)),
2188 )
2189 }
2190
2191 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2192 let scroll_bar_style = self.show_scrollbar(cx);
2193 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2194
2195 if !self.should_show_scrollbar(cx)
2196 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2197 {
2198 return None;
2199 }
2200
2201 Some(
2202 div()
2203 .id("git-panel-vertical-scroll")
2204 .occlude()
2205 .flex_none()
2206 .h_full()
2207 .cursor_default()
2208 .when(show_container, |this| this.pl_1().px_1p5())
2209 .when(!show_container, |this| {
2210 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2211 })
2212 .on_mouse_move(cx.listener(|_, _, _, cx| {
2213 cx.notify();
2214 cx.stop_propagation()
2215 }))
2216 .on_hover(|_, _, cx| {
2217 cx.stop_propagation();
2218 })
2219 .on_any_mouse_down(|_, _, cx| {
2220 cx.stop_propagation();
2221 })
2222 .on_mouse_up(
2223 MouseButton::Left,
2224 cx.listener(|this, _, window, cx| {
2225 if !this.scrollbar_state.is_dragging()
2226 && !this.focus_handle.contains_focused(window, cx)
2227 {
2228 this.hide_scrollbar(window, cx);
2229 cx.notify();
2230 }
2231
2232 cx.stop_propagation();
2233 }),
2234 )
2235 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2236 cx.notify();
2237 }))
2238 .children(Scrollbar::vertical(
2239 // percentage as f32..end_offset as f32,
2240 self.scrollbar_state.clone(),
2241 )),
2242 )
2243 }
2244
2245 fn render_buffer_header_controls(
2246 &self,
2247 entity: &Entity<Self>,
2248 file: &Arc<dyn File>,
2249 _: &Window,
2250 cx: &App,
2251 ) -> Option<AnyElement> {
2252 let repo = self.active_repository.as_ref()?.read(cx);
2253 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2254 let ix = self.entry_by_path(&repo_path)?;
2255 let entry = self.entries.get(ix)?;
2256
2257 let is_staged = self.entry_is_staged(entry.status_entry()?);
2258
2259 let checkbox = Checkbox::new("stage-file", is_staged.into())
2260 .disabled(!self.has_write_access(cx))
2261 .fill()
2262 .elevation(ElevationIndex::Surface)
2263 .on_click({
2264 let entry = entry.clone();
2265 let git_panel = entity.downgrade();
2266 move |_, window, cx| {
2267 git_panel
2268 .update(cx, |this, cx| {
2269 this.toggle_staged_for_entry(&entry, window, cx);
2270 cx.stop_propagation();
2271 })
2272 .ok();
2273 }
2274 });
2275 Some(
2276 h_flex()
2277 .id("start-slot")
2278 .text_lg()
2279 .child(checkbox)
2280 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2281 // prevent the list item active state triggering when toggling checkbox
2282 cx.stop_propagation();
2283 })
2284 .into_any_element(),
2285 )
2286 }
2287
2288 fn render_entries(
2289 &self,
2290 has_write_access: bool,
2291 _: &Window,
2292 cx: &mut Context<Self>,
2293 ) -> impl IntoElement {
2294 let entry_count = self.entries.len();
2295
2296 h_flex()
2297 .size_full()
2298 .flex_grow()
2299 .overflow_hidden()
2300 .child(
2301 uniform_list(cx.entity().clone(), "entries", entry_count, {
2302 move |this, range, window, cx| {
2303 let mut items = Vec::with_capacity(range.end - range.start);
2304
2305 for ix in range {
2306 match &this.entries.get(ix) {
2307 Some(GitListEntry::GitStatusEntry(entry)) => {
2308 items.push(this.render_entry(
2309 ix,
2310 entry,
2311 has_write_access,
2312 window,
2313 cx,
2314 ));
2315 }
2316 Some(GitListEntry::Header(header)) => {
2317 items.push(this.render_list_header(
2318 ix,
2319 header,
2320 has_write_access,
2321 window,
2322 cx,
2323 ));
2324 }
2325 None => {}
2326 }
2327 }
2328
2329 items
2330 }
2331 })
2332 .size_full()
2333 .with_sizing_behavior(ListSizingBehavior::Auto)
2334 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2335 .track_scroll(self.scroll_handle.clone()),
2336 )
2337 .on_mouse_down(
2338 MouseButton::Right,
2339 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2340 this.deploy_panel_context_menu(event.position, window, cx)
2341 }),
2342 )
2343 .children(self.render_scrollbar(cx))
2344 }
2345
2346 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2347 Label::new(label.into()).color(color).single_line()
2348 }
2349
2350 fn list_item_height(&self) -> Rems {
2351 rems(1.75)
2352 }
2353
2354 fn render_list_header(
2355 &self,
2356 ix: usize,
2357 header: &GitHeaderEntry,
2358 _: bool,
2359 _: &Window,
2360 _: &Context<Self>,
2361 ) -> AnyElement {
2362 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2363
2364 h_flex()
2365 .id(id)
2366 .h(self.list_item_height())
2367 .w_full()
2368 .items_end()
2369 .px(rems(0.75)) // ~12px
2370 .pb(rems(0.3125)) // ~ 5px
2371 .child(
2372 Label::new(header.title())
2373 .color(Color::Muted)
2374 .size(LabelSize::Small)
2375 .line_height_style(LineHeightStyle::UiLabel)
2376 .single_line(),
2377 )
2378 .into_any_element()
2379 }
2380
2381 fn load_commit_details(
2382 &self,
2383 sha: &str,
2384 cx: &mut Context<Self>,
2385 ) -> Task<anyhow::Result<CommitDetails>> {
2386 let Some(repo) = self.active_repository.clone() else {
2387 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2388 };
2389 repo.update(cx, |repo, cx| {
2390 let show = repo.show(sha);
2391 cx.spawn(|_, _| async move { show.await? })
2392 })
2393 }
2394
2395 fn deploy_entry_context_menu(
2396 &mut self,
2397 position: Point<Pixels>,
2398 ix: usize,
2399 window: &mut Window,
2400 cx: &mut Context<Self>,
2401 ) {
2402 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2403 return;
2404 };
2405 let stage_title = if entry.status.is_staged() == Some(true) {
2406 "Unstage File"
2407 } else {
2408 "Stage File"
2409 };
2410 let restore_title = if entry.status.is_created() {
2411 "Trash File"
2412 } else {
2413 "Restore File"
2414 };
2415 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2416 context_menu
2417 .action(stage_title, ToggleStaged.boxed_clone())
2418 .action(restore_title, git::RestoreFile.boxed_clone())
2419 .separator()
2420 .action("Open Diff", Confirm.boxed_clone())
2421 .action("Open File", SecondaryConfirm.boxed_clone())
2422 });
2423 self.selected_entry = Some(ix);
2424 self.set_context_menu(context_menu, position, window, cx);
2425 }
2426
2427 fn deploy_panel_context_menu(
2428 &mut self,
2429 position: Point<Pixels>,
2430 window: &mut Window,
2431 cx: &mut Context<Self>,
2432 ) {
2433 let context_menu = git_panel_context_menu(window, cx);
2434 self.set_context_menu(context_menu, position, window, cx);
2435 }
2436
2437 fn set_context_menu(
2438 &mut self,
2439 context_menu: Entity<ContextMenu>,
2440 position: Point<Pixels>,
2441 window: &Window,
2442 cx: &mut Context<Self>,
2443 ) {
2444 let subscription = cx.subscribe_in(
2445 &context_menu,
2446 window,
2447 |this, _, _: &DismissEvent, window, cx| {
2448 if this.context_menu.as_ref().is_some_and(|context_menu| {
2449 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2450 }) {
2451 cx.focus_self(window);
2452 }
2453 this.context_menu.take();
2454 cx.notify();
2455 },
2456 );
2457 self.context_menu = Some((context_menu, position, subscription));
2458 cx.notify();
2459 }
2460
2461 fn render_entry(
2462 &self,
2463 ix: usize,
2464 entry: &GitStatusEntry,
2465 has_write_access: bool,
2466 _: &Window,
2467 cx: &Context<Self>,
2468 ) -> AnyElement {
2469 let display_name = entry
2470 .worktree_path
2471 .file_name()
2472 .map(|name| name.to_string_lossy().into_owned())
2473 .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2474
2475 let worktree_path = entry.worktree_path.clone();
2476 let selected = self.selected_entry == Some(ix);
2477 let marked = self.marked_entries.contains(&ix);
2478 let status_style = GitPanelSettings::get_global(cx).status_style;
2479 let status = entry.status;
2480 let has_conflict = status.is_conflicted();
2481 let is_modified = status.is_modified();
2482 let is_deleted = status.is_deleted();
2483
2484 let label_color = if status_style == StatusStyle::LabelColor {
2485 if has_conflict {
2486 Color::Conflict
2487 } else if is_modified {
2488 Color::Modified
2489 } else if is_deleted {
2490 // We don't want a bunch of red labels in the list
2491 Color::Disabled
2492 } else {
2493 Color::Created
2494 }
2495 } else {
2496 Color::Default
2497 };
2498
2499 let path_color = if status.is_deleted() {
2500 Color::Disabled
2501 } else {
2502 Color::Muted
2503 };
2504
2505 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2506 let checkbox_wrapper_id: ElementId =
2507 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2508 let checkbox_id: ElementId =
2509 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2510
2511 let is_entry_staged = self.entry_is_staged(entry);
2512 let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2513
2514 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2515 is_staged = ToggleState::Selected;
2516 }
2517
2518 let handle = cx.weak_entity();
2519
2520 let selected_bg_alpha = 0.08;
2521 let marked_bg_alpha = 0.12;
2522 let state_opacity_step = 0.04;
2523
2524 let base_bg = match (selected, marked) {
2525 (true, true) => cx
2526 .theme()
2527 .status()
2528 .info
2529 .alpha(selected_bg_alpha + marked_bg_alpha),
2530 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2531 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2532 _ => cx.theme().colors().ghost_element_background,
2533 };
2534
2535 let hover_bg = if selected {
2536 cx.theme()
2537 .status()
2538 .info
2539 .alpha(selected_bg_alpha + state_opacity_step)
2540 } else {
2541 cx.theme().colors().ghost_element_hover
2542 };
2543
2544 let active_bg = if selected {
2545 cx.theme()
2546 .status()
2547 .info
2548 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2549 } else {
2550 cx.theme().colors().ghost_element_active
2551 };
2552
2553 h_flex()
2554 .id(id)
2555 .h(self.list_item_height())
2556 .w_full()
2557 .items_center()
2558 .px(rems(0.75)) // ~12px
2559 .overflow_hidden()
2560 .flex_none()
2561 .gap(DynamicSpacing::Base04.rems(cx))
2562 .bg(base_bg)
2563 .hover(|this| this.bg(hover_bg))
2564 .active(|this| this.bg(active_bg))
2565 .on_click({
2566 cx.listener(move |this, event: &ClickEvent, window, cx| {
2567 this.selected_entry = Some(ix);
2568 cx.notify();
2569 if event.modifiers().secondary() {
2570 this.open_file(&Default::default(), window, cx)
2571 } else {
2572 this.open_diff(&Default::default(), window, cx);
2573 }
2574 })
2575 })
2576 .on_mouse_down(
2577 MouseButton::Right,
2578 move |event: &MouseDownEvent, window, cx| {
2579 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2580 if event.button != MouseButton::Right {
2581 return;
2582 }
2583
2584 let Some(this) = handle.upgrade() else {
2585 return;
2586 };
2587 this.update(cx, |this, cx| {
2588 this.deploy_entry_context_menu(event.position, ix, window, cx);
2589 });
2590 cx.stop_propagation();
2591 },
2592 )
2593 // .on_secondary_mouse_down(cx.listener(
2594 // move |this, event: &MouseDownEvent, window, cx| {
2595 // this.deploy_entry_context_menu(event.position, ix, window, cx);
2596 // cx.stop_propagation();
2597 // },
2598 // ))
2599 .child(
2600 div()
2601 .id(checkbox_wrapper_id)
2602 .flex_none()
2603 .occlude()
2604 .cursor_pointer()
2605 .child(
2606 Checkbox::new(checkbox_id, is_staged)
2607 .disabled(!has_write_access)
2608 .fill()
2609 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2610 .elevation(ElevationIndex::Surface)
2611 .on_click({
2612 let entry = entry.clone();
2613 cx.listener(move |this, _, window, cx| {
2614 if !has_write_access {
2615 return;
2616 }
2617 this.toggle_staged_for_entry(
2618 &GitListEntry::GitStatusEntry(entry.clone()),
2619 window,
2620 cx,
2621 );
2622 cx.stop_propagation();
2623 })
2624 })
2625 .tooltip(move |window, cx| {
2626 let tooltip_name = if is_entry_staged.unwrap_or(false) {
2627 "Unstage"
2628 } else {
2629 "Stage"
2630 };
2631
2632 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2633 }),
2634 ),
2635 )
2636 .child(git_status_icon(status, cx))
2637 .child(
2638 h_flex()
2639 .items_center()
2640 .overflow_hidden()
2641 .when_some(worktree_path.parent(), |this, parent| {
2642 let parent_str = parent.to_string_lossy();
2643 if !parent_str.is_empty() {
2644 this.child(
2645 self.entry_label(format!("{}/", parent_str), path_color)
2646 .when(status.is_deleted(), |this| this.strikethrough()),
2647 )
2648 } else {
2649 this
2650 }
2651 })
2652 .child(
2653 self.entry_label(display_name.clone(), label_color)
2654 .when(status.is_deleted(), |this| this.strikethrough()),
2655 ),
2656 )
2657 .into_any_element()
2658 }
2659
2660 fn has_write_access(&self, cx: &App) -> bool {
2661 !self.project.read(cx).is_read_only(cx)
2662 }
2663}
2664
2665impl Render for GitPanel {
2666 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2667 let project = self.project.read(cx);
2668 let has_entries = self.entries.len() > 0;
2669 let room = self
2670 .workspace
2671 .upgrade()
2672 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2673
2674 let has_write_access = self.has_write_access(cx);
2675
2676 let has_co_authors = room.map_or(false, |room| {
2677 room.read(cx)
2678 .remote_participants()
2679 .values()
2680 .any(|remote_participant| remote_participant.can_write())
2681 });
2682
2683 v_flex()
2684 .id("git_panel")
2685 .key_context(self.dispatch_context(window, cx))
2686 .track_focus(&self.focus_handle)
2687 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2688 .when(has_write_access && !project.is_read_only(cx), |this| {
2689 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2690 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2691 }))
2692 .on_action(cx.listener(GitPanel::commit))
2693 })
2694 .on_action(cx.listener(Self::select_first))
2695 .on_action(cx.listener(Self::select_next))
2696 .on_action(cx.listener(Self::select_previous))
2697 .on_action(cx.listener(Self::select_last))
2698 .on_action(cx.listener(Self::close_panel))
2699 .on_action(cx.listener(Self::open_diff))
2700 .on_action(cx.listener(Self::open_file))
2701 .on_action(cx.listener(Self::revert_selected))
2702 .on_action(cx.listener(Self::focus_changes_list))
2703 .on_action(cx.listener(Self::focus_editor))
2704 .on_action(cx.listener(Self::toggle_staged_for_selected))
2705 .on_action(cx.listener(Self::stage_all))
2706 .on_action(cx.listener(Self::unstage_all))
2707 .on_action(cx.listener(Self::restore_tracked_files))
2708 .on_action(cx.listener(Self::clean_all))
2709 .on_action(cx.listener(Self::fetch))
2710 .on_action(cx.listener(Self::pull))
2711 .on_action(cx.listener(Self::push))
2712 .when(has_write_access && has_co_authors, |git_panel| {
2713 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
2714 })
2715 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
2716 .on_hover(cx.listener(|this, hovered, window, cx| {
2717 if *hovered {
2718 this.show_scrollbar = true;
2719 this.hide_scrollbar_task.take();
2720 cx.notify();
2721 } else if !this.focus_handle.contains_focused(window, cx) {
2722 this.hide_scrollbar(window, cx);
2723 }
2724 }))
2725 .size_full()
2726 .overflow_hidden()
2727 .bg(ElevationIndex::Surface.bg(cx))
2728 .child(
2729 v_flex()
2730 .size_full()
2731 .map(|this| {
2732 if has_entries {
2733 this.child(self.render_entries(has_write_access, window, cx))
2734 } else {
2735 this.child(self.render_empty_state(cx).into_any_element())
2736 }
2737 })
2738 .children(self.render_footer(window, cx))
2739 .children(self.render_previous_commit(cx))
2740 .into_any_element(),
2741 )
2742 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2743 deferred(
2744 anchored()
2745 .position(*position)
2746 .anchor(gpui::Corner::TopLeft)
2747 .child(menu.clone()),
2748 )
2749 .with_priority(1)
2750 }))
2751 }
2752}
2753
2754impl Focusable for GitPanel {
2755 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
2756 self.focus_handle.clone()
2757 }
2758}
2759
2760impl EventEmitter<Event> for GitPanel {}
2761
2762impl EventEmitter<PanelEvent> for GitPanel {}
2763
2764pub(crate) struct GitPanelAddon {
2765 pub(crate) workspace: WeakEntity<Workspace>,
2766}
2767
2768impl editor::Addon for GitPanelAddon {
2769 fn to_any(&self) -> &dyn std::any::Any {
2770 self
2771 }
2772
2773 fn render_buffer_header_controls(
2774 &self,
2775 excerpt_info: &ExcerptInfo,
2776 window: &Window,
2777 cx: &App,
2778 ) -> Option<AnyElement> {
2779 let file = excerpt_info.buffer.file()?;
2780 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
2781
2782 git_panel
2783 .read(cx)
2784 .render_buffer_header_controls(&git_panel, &file, window, cx)
2785 }
2786}
2787
2788impl Panel for GitPanel {
2789 fn persistent_name() -> &'static str {
2790 "GitPanel"
2791 }
2792
2793 fn position(&self, _: &Window, cx: &App) -> DockPosition {
2794 GitPanelSettings::get_global(cx).dock
2795 }
2796
2797 fn position_is_valid(&self, position: DockPosition) -> bool {
2798 matches!(position, DockPosition::Left | DockPosition::Right)
2799 }
2800
2801 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
2802 settings::update_settings_file::<GitPanelSettings>(
2803 self.fs.clone(),
2804 cx,
2805 move |settings, _| settings.dock = Some(position),
2806 );
2807 }
2808
2809 fn size(&self, _: &Window, cx: &App) -> Pixels {
2810 self.width
2811 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
2812 }
2813
2814 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
2815 self.width = size;
2816 self.serialize(cx);
2817 cx.notify();
2818 }
2819
2820 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
2821 Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
2822 }
2823
2824 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
2825 Some("Git Panel")
2826 }
2827
2828 fn toggle_action(&self) -> Box<dyn Action> {
2829 Box::new(ToggleFocus)
2830 }
2831
2832 fn activation_priority(&self) -> u32 {
2833 2
2834 }
2835}
2836
2837impl PanelHeader for GitPanel {}
2838
2839struct GitPanelMessageTooltip {
2840 commit_tooltip: Option<Entity<CommitTooltip>>,
2841}
2842
2843impl GitPanelMessageTooltip {
2844 fn new(
2845 git_panel: Entity<GitPanel>,
2846 sha: SharedString,
2847 window: &mut Window,
2848 cx: &mut App,
2849 ) -> Entity<Self> {
2850 cx.new(|cx| {
2851 cx.spawn_in(window, |this, mut cx| async move {
2852 let details = git_panel
2853 .update(&mut cx, |git_panel, cx| {
2854 git_panel.load_commit_details(&sha, cx)
2855 })?
2856 .await?;
2857
2858 let commit_details = editor::commit_tooltip::CommitDetails {
2859 sha: details.sha.clone(),
2860 committer_name: details.committer_name.clone(),
2861 committer_email: details.committer_email.clone(),
2862 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
2863 message: Some(editor::commit_tooltip::ParsedCommitMessage {
2864 message: details.message.clone(),
2865 ..Default::default()
2866 }),
2867 };
2868
2869 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
2870 this.commit_tooltip =
2871 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
2872 cx.notify();
2873 })
2874 })
2875 .detach();
2876
2877 Self {
2878 commit_tooltip: None,
2879 }
2880 })
2881 }
2882}
2883
2884impl Render for GitPanelMessageTooltip {
2885 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
2886 if let Some(commit_tooltip) = &self.commit_tooltip {
2887 commit_tooltip.clone().into_any_element()
2888 } else {
2889 gpui::Empty.into_any_element()
2890 }
2891 }
2892}
2893
2894fn git_action_tooltip(
2895 label: impl Into<SharedString>,
2896 action: &dyn Action,
2897 command: impl Into<SharedString>,
2898 focus_handle: Option<FocusHandle>,
2899 window: &mut Window,
2900 cx: &mut App,
2901) -> AnyView {
2902 let label = label.into();
2903 let command = command.into();
2904
2905 if let Some(handle) = focus_handle {
2906 Tooltip::with_meta_in(
2907 label.clone(),
2908 Some(action),
2909 command.clone(),
2910 &handle,
2911 window,
2912 cx,
2913 )
2914 } else {
2915 Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
2916 }
2917}
2918
2919#[derive(IntoElement)]
2920struct SplitButton {
2921 pub left: ButtonLike,
2922 pub right: AnyElement,
2923}
2924
2925impl SplitButton {
2926 fn new(
2927 id: impl Into<SharedString>,
2928 left_label: impl Into<SharedString>,
2929 ahead_count: usize,
2930 behind_count: usize,
2931 left_icon: Option<IconName>,
2932 left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
2933 tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
2934 ) -> Self {
2935 let id = id.into();
2936
2937 fn count(count: usize) -> impl IntoElement {
2938 h_flex()
2939 .ml_neg_px()
2940 .h(rems(0.875))
2941 .items_center()
2942 .overflow_hidden()
2943 .px_0p5()
2944 .child(
2945 Label::new(count.to_string())
2946 .size(LabelSize::XSmall)
2947 .line_height_style(LineHeightStyle::UiLabel),
2948 )
2949 }
2950
2951 let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
2952
2953 let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
2954 format!("split-button-left-{}", id).into(),
2955 ))
2956 .layer(ui::ElevationIndex::ModalSurface)
2957 .size(ui::ButtonSize::Compact)
2958 .when(should_render_counts, |this| {
2959 this.child(
2960 h_flex()
2961 .ml_neg_0p5()
2962 .mr_1()
2963 .when(behind_count > 0, |this| {
2964 this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
2965 .child(count(behind_count))
2966 })
2967 .when(ahead_count > 0, |this| {
2968 this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
2969 .child(count(ahead_count))
2970 }),
2971 )
2972 })
2973 .when_some(left_icon, |this, left_icon| {
2974 this.child(
2975 h_flex()
2976 .ml_neg_0p5()
2977 .mr_1()
2978 .child(Icon::new(left_icon).size(IconSize::XSmall)),
2979 )
2980 })
2981 .child(
2982 div()
2983 .child(Label::new(left_label).size(LabelSize::Small))
2984 .mr_0p5(),
2985 )
2986 .on_click(left_on_click)
2987 .tooltip(tooltip);
2988
2989 let right =
2990 render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
2991 .into_any_element();
2992 // .on_click(right_on_click);
2993
2994 Self { left, right }
2995 }
2996}
2997
2998impl RenderOnce for SplitButton {
2999 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3000 h_flex()
3001 .rounded_md()
3002 .border_1()
3003 .border_color(cx.theme().colors().text_muted.alpha(0.12))
3004 .child(self.left)
3005 .child(
3006 div()
3007 .h_full()
3008 .w_px()
3009 .bg(cx.theme().colors().text_muted.alpha(0.16)),
3010 )
3011 .child(self.right)
3012 .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3013 .shadow(smallvec![BoxShadow {
3014 color: hsla(0.0, 0.0, 0.0, 0.16),
3015 offset: point(px(0.), px(1.)),
3016 blur_radius: px(0.),
3017 spread_radius: px(0.),
3018 }])
3019 }
3020}
3021
3022fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3023 PopoverMenu::new(id.into())
3024 .trigger(
3025 ui::ButtonLike::new_rounded_right("split-button-right")
3026 .layer(ui::ElevationIndex::ModalSurface)
3027 .size(ui::ButtonSize::None)
3028 .child(
3029 div()
3030 .px_1()
3031 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3032 ),
3033 )
3034 .menu(move |window, cx| {
3035 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3036 context_menu
3037 .action("Fetch", git::Fetch.boxed_clone())
3038 .action("Pull", git::Pull.boxed_clone())
3039 .separator()
3040 .action("Push", git::Push { options: None }.boxed_clone())
3041 .action(
3042 "Force Push",
3043 git::Push {
3044 options: Some(PushOptions::Force),
3045 }
3046 .boxed_clone(),
3047 )
3048 }))
3049 })
3050 .anchor(Corner::TopRight)
3051}
3052
3053#[derive(IntoElement, IntoComponent)]
3054#[component(scope = "git_panel")]
3055pub struct PanelRepoFooter {
3056 id: SharedString,
3057 active_repository: SharedString,
3058 branch: Option<Branch>,
3059 // Getting a GitPanel in previews will be difficult.
3060 //
3061 // For now just take an option here, and we won't bind handlers to buttons in previews.
3062 git_panel: Option<Entity<GitPanel>>,
3063 branches: Option<Entity<BranchList>>,
3064}
3065
3066impl PanelRepoFooter {
3067 pub fn new(
3068 id: impl Into<SharedString>,
3069 active_repository: SharedString,
3070 branch: Option<Branch>,
3071 git_panel: Option<Entity<GitPanel>>,
3072 branches: Option<Entity<BranchList>>,
3073 ) -> Self {
3074 Self {
3075 id: id.into(),
3076 active_repository,
3077 branch,
3078 git_panel,
3079 branches,
3080 }
3081 }
3082
3083 pub fn new_preview(
3084 id: impl Into<SharedString>,
3085 active_repository: SharedString,
3086 branch: Option<Branch>,
3087 ) -> Self {
3088 Self {
3089 id: id.into(),
3090 active_repository,
3091 branch,
3092 git_panel: None,
3093 branches: None,
3094 }
3095 }
3096
3097 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3098 PopoverMenu::new(id.into())
3099 .trigger(
3100 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3101 .icon_size(IconSize::Small)
3102 .icon_color(Color::Muted),
3103 )
3104 .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3105 .anchor(Corner::TopRight)
3106 }
3107
3108 fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3109 if let Some(git_panel) = self.git_panel.clone() {
3110 Some(git_panel.focus_handle(cx))
3111 } else {
3112 None
3113 }
3114 }
3115
3116 fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3117 let panel = self.git_panel.clone();
3118 let panel_focus_handle = self.panel_focus_handle(cx);
3119
3120 SplitButton::new(
3121 id,
3122 "Push",
3123 ahead as usize,
3124 0,
3125 None,
3126 move |_, window, cx| {
3127 if let Some(panel) = panel.as_ref() {
3128 panel.update(cx, |panel, cx| {
3129 panel.push(&git::Push { options: None }, window, cx);
3130 });
3131 }
3132 },
3133 move |window, cx| {
3134 git_action_tooltip(
3135 "Push committed changes to remote",
3136 &git::Push { options: None },
3137 "git push",
3138 panel_focus_handle.clone(),
3139 window,
3140 cx,
3141 )
3142 },
3143 )
3144 }
3145
3146 fn render_pull_button(
3147 &self,
3148 id: SharedString,
3149 ahead: u32,
3150 behind: u32,
3151 cx: &mut App,
3152 ) -> SplitButton {
3153 let panel = self.git_panel.clone();
3154 let panel_focus_handle = self.panel_focus_handle(cx);
3155
3156 SplitButton::new(
3157 id,
3158 "Pull",
3159 ahead as usize,
3160 behind as usize,
3161 None,
3162 move |_, window, cx| {
3163 if let Some(panel) = panel.as_ref() {
3164 panel.update(cx, |panel, cx| {
3165 panel.pull(&git::Pull, window, cx);
3166 });
3167 }
3168 },
3169 move |window, cx| {
3170 git_action_tooltip(
3171 "Pull",
3172 &git::Pull,
3173 "git pull",
3174 panel_focus_handle.clone(),
3175 window,
3176 cx,
3177 )
3178 },
3179 )
3180 }
3181
3182 fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3183 let panel = self.git_panel.clone();
3184 let panel_focus_handle = self.panel_focus_handle(cx);
3185
3186 SplitButton::new(
3187 id,
3188 "Fetch",
3189 0,
3190 0,
3191 Some(IconName::ArrowCircle),
3192 move |_, window, cx| {
3193 if let Some(panel) = panel.as_ref() {
3194 panel.update(cx, |panel, cx| {
3195 panel.fetch(&git::Fetch, window, cx);
3196 });
3197 }
3198 },
3199 move |window, cx| {
3200 git_action_tooltip(
3201 "Fetch updates from remote",
3202 &git::Fetch,
3203 "git fetch",
3204 panel_focus_handle.clone(),
3205 window,
3206 cx,
3207 )
3208 },
3209 )
3210 }
3211
3212 fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3213 let panel = self.git_panel.clone();
3214 let panel_focus_handle = self.panel_focus_handle(cx);
3215
3216 SplitButton::new(
3217 id,
3218 "Publish",
3219 0,
3220 0,
3221 Some(IconName::ArrowUpFromLine),
3222 move |_, window, cx| {
3223 if let Some(panel) = panel.as_ref() {
3224 panel.update(cx, |panel, cx| {
3225 panel.push(
3226 &git::Push {
3227 options: Some(PushOptions::SetUpstream),
3228 },
3229 window,
3230 cx,
3231 );
3232 });
3233 }
3234 },
3235 move |window, cx| {
3236 git_action_tooltip(
3237 "Publish branch to remote",
3238 &git::Push {
3239 options: Some(PushOptions::SetUpstream),
3240 },
3241 "git push --set-upstream",
3242 panel_focus_handle.clone(),
3243 window,
3244 cx,
3245 )
3246 },
3247 )
3248 }
3249
3250 fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3251 let panel = self.git_panel.clone();
3252 let panel_focus_handle = self.panel_focus_handle(cx);
3253
3254 SplitButton::new(
3255 id,
3256 "Republish",
3257 0,
3258 0,
3259 Some(IconName::ArrowUpFromLine),
3260 move |_, window, cx| {
3261 if let Some(panel) = panel.as_ref() {
3262 panel.update(cx, |panel, cx| {
3263 panel.push(
3264 &git::Push {
3265 options: Some(PushOptions::SetUpstream),
3266 },
3267 window,
3268 cx,
3269 );
3270 });
3271 }
3272 },
3273 move |window, cx| {
3274 git_action_tooltip(
3275 "Re-publish branch to remote",
3276 &git::Push {
3277 options: Some(PushOptions::SetUpstream),
3278 },
3279 "git push --set-upstream",
3280 panel_focus_handle.clone(),
3281 window,
3282 cx,
3283 )
3284 },
3285 )
3286 }
3287
3288 fn render_relevant_button(
3289 &self,
3290 id: impl Into<SharedString>,
3291 branch: &Branch,
3292 cx: &mut App,
3293 ) -> impl IntoElement {
3294 let id = id.into();
3295 let upstream = branch.upstream.as_ref();
3296 match upstream {
3297 Some(Upstream {
3298 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3299 ..
3300 }) => match (*ahead, *behind) {
3301 (0, 0) => self.render_fetch_button(id, cx),
3302 (ahead, 0) => self.render_push_button(id, ahead, cx),
3303 (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3304 },
3305 Some(Upstream {
3306 tracking: UpstreamTracking::Gone,
3307 ..
3308 }) => self.render_republish_button(id, cx),
3309 None => self.render_publish_button(id, cx),
3310 }
3311 }
3312}
3313
3314impl RenderOnce for PanelRepoFooter {
3315 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
3316 let active_repo = self.active_repository.clone();
3317 let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3318 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3319 .style(ButtonStyle::Transparent)
3320 .size(ButtonSize::None)
3321 .label_size(LabelSize::Small)
3322 .color(Color::Muted);
3323
3324 let repo_selector = if let Some(panel) = self.git_panel.clone() {
3325 let repo_selector = panel.read(cx).repository_selector.clone();
3326 let repo_count = repo_selector.read(cx).repositories_len(cx);
3327 let single_repo = repo_count == 1;
3328
3329 RepositorySelectorPopoverMenu::new(
3330 panel.read(cx).repository_selector.clone(),
3331 repo_selector_trigger.disabled(single_repo).truncate(true),
3332 Tooltip::text("Switch active repository"),
3333 )
3334 .into_any_element()
3335 } else {
3336 // for rendering preview, we don't have git_panel there
3337 repo_selector_trigger.into_any_element()
3338 };
3339
3340 let branch = self.branch.clone();
3341 let branch_name = branch
3342 .as_ref()
3343 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3344
3345 let branches = self.branches.clone();
3346
3347 let branch_selector_button = Button::new("branch-selector", branch_name)
3348 .style(ButtonStyle::Transparent)
3349 .size(ButtonSize::None)
3350 .label_size(LabelSize::Small)
3351 .truncate(true)
3352 .tooltip(Tooltip::for_action_title(
3353 "Switch Branch",
3354 &zed_actions::git::Branch,
3355 ))
3356 .on_click(|_, window, cx| {
3357 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3358 });
3359
3360 let branch_selector = if let Some(branches) = branches {
3361 PopoverButton::new(
3362 branches,
3363 Corner::BottomLeft,
3364 branch_selector_button,
3365 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3366 )
3367 .render(window, cx)
3368 .into_any_element()
3369 } else {
3370 branch_selector_button.into_any_element()
3371 };
3372
3373 let spinner = self
3374 .git_panel
3375 .as_ref()
3376 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3377
3378 h_flex()
3379 .w_full()
3380 .px_2()
3381 .h(px(36.))
3382 .items_center()
3383 .justify_between()
3384 .child(
3385 h_flex()
3386 .flex_1()
3387 .overflow_hidden()
3388 .items_center()
3389 .child(
3390 div().child(
3391 Icon::new(IconName::GitBranchSmall)
3392 .size(IconSize::Small)
3393 .color(Color::Muted),
3394 ),
3395 )
3396 .child(repo_selector)
3397 .when_some(branch.clone(), |this, _| {
3398 this.child(
3399 div()
3400 .text_color(cx.theme().colors().text_muted)
3401 .text_sm()
3402 .child("/"),
3403 )
3404 })
3405 .child(branch_selector),
3406 )
3407 .child(
3408 h_flex()
3409 .gap_1()
3410 .flex_shrink_0()
3411 .children(spinner)
3412 .child(self.render_overflow_menu(overflow_menu_id))
3413 .when_some(branch, |this, branch| {
3414 let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3415 this.child(button)
3416 }),
3417 )
3418 }
3419}
3420
3421impl ComponentPreview for PanelRepoFooter {
3422 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3423 let unknown_upstream = None;
3424 let no_remote_upstream = Some(UpstreamTracking::Gone);
3425 let ahead_of_upstream = Some(
3426 UpstreamTrackingStatus {
3427 ahead: 2,
3428 behind: 0,
3429 }
3430 .into(),
3431 );
3432 let behind_upstream = Some(
3433 UpstreamTrackingStatus {
3434 ahead: 0,
3435 behind: 2,
3436 }
3437 .into(),
3438 );
3439 let ahead_and_behind_upstream = Some(
3440 UpstreamTrackingStatus {
3441 ahead: 3,
3442 behind: 1,
3443 }
3444 .into(),
3445 );
3446
3447 let not_ahead_or_behind_upstream = Some(
3448 UpstreamTrackingStatus {
3449 ahead: 0,
3450 behind: 0,
3451 }
3452 .into(),
3453 );
3454
3455 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3456 Branch {
3457 is_head: true,
3458 name: "some-branch".into(),
3459 upstream: upstream.map(|tracking| Upstream {
3460 ref_name: "origin/some-branch".into(),
3461 tracking,
3462 }),
3463 most_recent_commit: Some(CommitSummary {
3464 sha: "abc123".into(),
3465 subject: "Modify stuff".into(),
3466 commit_timestamp: 1710932954,
3467 }),
3468 }
3469 }
3470
3471 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3472 Branch {
3473 is_head: true,
3474 name: branch_name.to_string().into(),
3475 upstream: upstream.map(|tracking| Upstream {
3476 ref_name: format!("zed/{}", branch_name).into(),
3477 tracking,
3478 }),
3479 most_recent_commit: Some(CommitSummary {
3480 sha: "abc123".into(),
3481 subject: "Modify stuff".into(),
3482 commit_timestamp: 1710932954,
3483 }),
3484 }
3485 }
3486
3487 fn active_repository(id: usize) -> SharedString {
3488 format!("repo-{}", id).into()
3489 }
3490
3491 let example_width = px(340.);
3492
3493 v_flex()
3494 .gap_6()
3495 .w_full()
3496 .flex_none()
3497 .children(vec![example_group_with_title(
3498 "Action Button States",
3499 vec![
3500 single_example(
3501 "No Branch",
3502 div()
3503 .w(example_width)
3504 .overflow_hidden()
3505 .child(PanelRepoFooter::new_preview(
3506 "no-branch",
3507 active_repository(1).clone(),
3508 None,
3509 ))
3510 .into_any_element(),
3511 )
3512 .grow(),
3513 single_example(
3514 "Remote status unknown",
3515 div()
3516 .w(example_width)
3517 .overflow_hidden()
3518 .child(PanelRepoFooter::new_preview(
3519 "unknown-upstream",
3520 active_repository(2).clone(),
3521 Some(branch(unknown_upstream)),
3522 ))
3523 .into_any_element(),
3524 )
3525 .grow(),
3526 single_example(
3527 "No Remote Upstream",
3528 div()
3529 .w(example_width)
3530 .overflow_hidden()
3531 .child(PanelRepoFooter::new_preview(
3532 "no-remote-upstream",
3533 active_repository(3).clone(),
3534 Some(branch(no_remote_upstream)),
3535 ))
3536 .into_any_element(),
3537 )
3538 .grow(),
3539 single_example(
3540 "Not Ahead or Behind",
3541 div()
3542 .w(example_width)
3543 .overflow_hidden()
3544 .child(PanelRepoFooter::new_preview(
3545 "not-ahead-or-behind",
3546 active_repository(4).clone(),
3547 Some(branch(not_ahead_or_behind_upstream)),
3548 ))
3549 .into_any_element(),
3550 )
3551 .grow(),
3552 single_example(
3553 "Behind remote",
3554 div()
3555 .w(example_width)
3556 .overflow_hidden()
3557 .child(PanelRepoFooter::new_preview(
3558 "behind-remote",
3559 active_repository(5).clone(),
3560 Some(branch(behind_upstream)),
3561 ))
3562 .into_any_element(),
3563 )
3564 .grow(),
3565 single_example(
3566 "Ahead of remote",
3567 div()
3568 .w(example_width)
3569 .overflow_hidden()
3570 .child(PanelRepoFooter::new_preview(
3571 "ahead-of-remote",
3572 active_repository(6).clone(),
3573 Some(branch(ahead_of_upstream)),
3574 ))
3575 .into_any_element(),
3576 )
3577 .grow(),
3578 single_example(
3579 "Ahead and behind remote",
3580 div()
3581 .w(example_width)
3582 .overflow_hidden()
3583 .child(PanelRepoFooter::new_preview(
3584 "ahead-and-behind",
3585 active_repository(7).clone(),
3586 Some(branch(ahead_and_behind_upstream)),
3587 ))
3588 .into_any_element(),
3589 )
3590 .grow(),
3591 ],
3592 )
3593 .grow()
3594 .vertical()])
3595 .children(vec![example_group_with_title(
3596 "Labels",
3597 vec![
3598 single_example(
3599 "Short Branch & Repo",
3600 div()
3601 .w(example_width)
3602 .overflow_hidden()
3603 .child(PanelRepoFooter::new_preview(
3604 "short-branch",
3605 SharedString::from("zed"),
3606 Some(custom("main", behind_upstream)),
3607 ))
3608 .into_any_element(),
3609 )
3610 .grow(),
3611 single_example(
3612 "Long Branch",
3613 div()
3614 .w(example_width)
3615 .overflow_hidden()
3616 .child(PanelRepoFooter::new_preview(
3617 "long-branch",
3618 SharedString::from("zed"),
3619 Some(custom(
3620 "redesign-and-update-git-ui-list-entry-style",
3621 behind_upstream,
3622 )),
3623 ))
3624 .into_any_element(),
3625 )
3626 .grow(),
3627 single_example(
3628 "Long Repo",
3629 div()
3630 .w(example_width)
3631 .overflow_hidden()
3632 .child(PanelRepoFooter::new_preview(
3633 "long-repo",
3634 SharedString::from("zed-industries-community-examples"),
3635 Some(custom("gpui", ahead_of_upstream)),
3636 ))
3637 .into_any_element(),
3638 )
3639 .grow(),
3640 single_example(
3641 "Long Repo & Branch",
3642 div()
3643 .w(example_width)
3644 .overflow_hidden()
3645 .child(PanelRepoFooter::new_preview(
3646 "long-repo-and-branch",
3647 SharedString::from("zed-industries-community-examples"),
3648 Some(custom(
3649 "redesign-and-update-git-ui-list-entry-style",
3650 behind_upstream,
3651 )),
3652 ))
3653 .into_any_element(),
3654 )
3655 .grow(),
3656 single_example(
3657 "Uppercase Repo",
3658 div()
3659 .w(example_width)
3660 .overflow_hidden()
3661 .child(PanelRepoFooter::new_preview(
3662 "uppercase-repo",
3663 SharedString::from("LICENSES"),
3664 Some(custom("main", ahead_of_upstream)),
3665 ))
3666 .into_any_element(),
3667 )
3668 .grow(),
3669 single_example(
3670 "Uppercase Branch",
3671 div()
3672 .w(example_width)
3673 .overflow_hidden()
3674 .child(PanelRepoFooter::new_preview(
3675 "uppercase-branch",
3676 SharedString::from("zed"),
3677 Some(custom("update-README", behind_upstream)),
3678 ))
3679 .into_any_element(),
3680 )
3681 .grow(),
3682 ],
3683 )
3684 .grow()
3685 .vertical()])
3686 .into_any_element()
3687 }
3688}
3689
3690#[cfg(test)]
3691mod tests {
3692 use git::status::StatusCode;
3693 use gpui::TestAppContext;
3694 use project::{FakeFs, WorktreeSettings};
3695 use serde_json::json;
3696 use settings::SettingsStore;
3697 use theme::LoadThemes;
3698 use util::path;
3699
3700 use super::*;
3701
3702 fn init_test(cx: &mut gpui::TestAppContext) {
3703 if std::env::var("RUST_LOG").is_ok() {
3704 env_logger::try_init().ok();
3705 }
3706
3707 cx.update(|cx| {
3708 let settings_store = SettingsStore::test(cx);
3709 cx.set_global(settings_store);
3710 WorktreeSettings::register(cx);
3711 workspace::init_settings(cx);
3712 theme::init(LoadThemes::JustBase, cx);
3713 language::init(cx);
3714 editor::init(cx);
3715 Project::init_settings(cx);
3716 crate::init(cx);
3717 });
3718 }
3719
3720 #[gpui::test]
3721 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
3722 init_test(cx);
3723 let fs = FakeFs::new(cx.background_executor.clone());
3724 fs.insert_tree(
3725 "/root",
3726 json!({
3727 "zed": {
3728 ".git": {},
3729 "crates": {
3730 "gpui": {
3731 "gpui.rs": "fn main() {}"
3732 },
3733 "util": {
3734 "util.rs": "fn do_it() {}"
3735 }
3736 }
3737 },
3738 }),
3739 )
3740 .await;
3741
3742 fs.set_status_for_repo_via_git_operation(
3743 Path::new("/root/zed/.git"),
3744 &[
3745 (
3746 Path::new("crates/gpui/gpui.rs"),
3747 StatusCode::Modified.worktree(),
3748 ),
3749 (
3750 Path::new("crates/util/util.rs"),
3751 StatusCode::Modified.worktree(),
3752 ),
3753 ],
3754 );
3755
3756 let project =
3757 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
3758 let (workspace, cx) =
3759 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3760
3761 cx.read(|cx| {
3762 project
3763 .read(cx)
3764 .worktrees(cx)
3765 .nth(0)
3766 .unwrap()
3767 .read(cx)
3768 .as_local()
3769 .unwrap()
3770 .scan_complete()
3771 })
3772 .await;
3773
3774 cx.executor().run_until_parked();
3775
3776 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
3777 let panel = cx.new_window_entity(|window, cx| {
3778 GitPanel::new(workspace, project, app_state, window, cx)
3779 });
3780
3781 let handle = cx.update_window_entity(&panel, |panel, window, cx| {
3782 panel.schedule_update(false, window, cx);
3783 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3784 });
3785 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3786 handle.await;
3787
3788 let entries = panel.update(cx, |panel, _| panel.entries.clone());
3789 pretty_assertions::assert_eq!(
3790 entries,
3791 [
3792 GitListEntry::Header(GitHeaderEntry {
3793 header: Section::Tracked
3794 }),
3795 GitListEntry::GitStatusEntry(GitStatusEntry {
3796 repo_path: "crates/gpui/gpui.rs".into(),
3797 worktree_path: Path::new("gpui.rs").into(),
3798 status: StatusCode::Modified.worktree(),
3799 is_staged: Some(false),
3800 })
3801 ],
3802 )
3803 }
3804}