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