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