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