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