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