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