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