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