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 let project = self.project.clone();
2499 workspace.update(cx, |workspace, cx| {
2500 let workspace_weak = cx.weak_entity();
2501 let toast =
2502 StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2503 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2504 .action("View Log", move |window, cx| {
2505 let message = message.clone();
2506 let project = project.clone();
2507 let action = action.clone();
2508 workspace_weak
2509 .update(cx, move |workspace, cx| {
2510 Self::open_output(
2511 project, action, workspace, &message, window, cx,
2512 )
2513 })
2514 .ok();
2515 })
2516 });
2517 workspace.toggle_status_toast(toast, cx)
2518 });
2519 }
2520 }
2521
2522 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2523 let Some(workspace) = self.workspace.upgrade() else {
2524 return;
2525 };
2526
2527 workspace.update(cx, |workspace, cx| {
2528 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2529 let workspace_weak = cx.weak_entity();
2530 let operation = action.name();
2531
2532 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2533 use remote_output::SuccessStyle::*;
2534 let project = self.project.clone();
2535 match style {
2536 Toast { .. } => this,
2537 ToastWithLog { output } => this
2538 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2539 .action("View Log", move |window, cx| {
2540 let output = output.clone();
2541 let project = project.clone();
2542 let output =
2543 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2544 workspace_weak
2545 .update(cx, move |workspace, cx| {
2546 Self::open_output(
2547 project, operation, workspace, &output, window, cx,
2548 )
2549 })
2550 .ok();
2551 }),
2552 PushPrLink { link } => this
2553 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2554 .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2555 }
2556 });
2557 workspace.toggle_status_toast(status_toast, cx)
2558 });
2559 }
2560
2561 fn open_output(
2562 project: Entity<Project>,
2563 operation: impl Into<SharedString>,
2564 workspace: &mut Workspace,
2565 output: &str,
2566 window: &mut Window,
2567 cx: &mut Context<Workspace>,
2568 ) {
2569 let operation = operation.into();
2570 let buffer = cx.new(|cx| Buffer::local(output, cx));
2571 let editor = cx.new(|cx| {
2572 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2573 editor.buffer().update(cx, |buffer, cx| {
2574 buffer.set_title(format!("Output from git {operation}"), cx);
2575 });
2576 editor.set_read_only(true);
2577 editor
2578 });
2579
2580 workspace.add_item_to_center(Box::new(editor), window, cx);
2581 }
2582
2583 pub fn render_spinner(&self) -> Option<impl IntoElement> {
2584 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2585 Icon::new(IconName::ArrowCircle)
2586 .size(IconSize::XSmall)
2587 .color(Color::Info)
2588 .with_animation(
2589 "arrow-circle",
2590 Animation::new(Duration::from_secs(2)).repeat(),
2591 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2592 )
2593 .into_any_element()
2594 })
2595 }
2596
2597 pub fn can_commit(&self) -> bool {
2598 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2599 }
2600
2601 pub fn can_stage_all(&self) -> bool {
2602 self.has_unstaged_changes()
2603 }
2604
2605 pub fn can_unstage_all(&self) -> bool {
2606 self.has_staged_changes()
2607 }
2608
2609 // eventually we'll need to take depth into account here
2610 // if we add a tree view
2611 fn item_width_estimate(path: usize, file_name: usize) -> usize {
2612 path + file_name
2613 }
2614
2615 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2616 let focus_handle = self.focus_handle.clone();
2617 PopoverMenu::new(id.into())
2618 .trigger(
2619 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2620 .icon_size(IconSize::Small)
2621 .icon_color(Color::Muted),
2622 )
2623 .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
2624 .anchor(Corner::TopRight)
2625 }
2626
2627 pub(crate) fn render_generate_commit_message_button(
2628 &self,
2629 cx: &Context<Self>,
2630 ) -> Option<AnyElement> {
2631 current_language_model(cx).is_some().then(|| {
2632 if self.generate_commit_message_task.is_some() {
2633 return h_flex()
2634 .gap_1()
2635 .child(
2636 Icon::new(IconName::ArrowCircle)
2637 .size(IconSize::XSmall)
2638 .color(Color::Info)
2639 .with_animation(
2640 "arrow-circle",
2641 Animation::new(Duration::from_secs(2)).repeat(),
2642 |icon, delta| {
2643 icon.transform(Transformation::rotate(percentage(delta)))
2644 },
2645 ),
2646 )
2647 .child(
2648 Label::new("Generating Commit...")
2649 .size(LabelSize::Small)
2650 .color(Color::Muted),
2651 )
2652 .into_any_element();
2653 }
2654
2655 let can_commit = self.can_commit();
2656 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2657 IconButton::new("generate-commit-message", IconName::AiEdit)
2658 .shape(ui::IconButtonShape::Square)
2659 .icon_color(Color::Muted)
2660 .tooltip(move |window, cx| {
2661 if can_commit {
2662 Tooltip::for_action_in(
2663 "Generate Commit Message",
2664 &git::GenerateCommitMessage,
2665 &editor_focus_handle,
2666 window,
2667 cx,
2668 )
2669 } else {
2670 Tooltip::simple("No changes to commit", cx)
2671 }
2672 })
2673 .disabled(!can_commit)
2674 .on_click(cx.listener(move |this, _event, _window, cx| {
2675 this.generate_commit_message(cx);
2676 }))
2677 .into_any_element()
2678 })
2679 }
2680
2681 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2682 let potential_co_authors = self.potential_co_authors(cx);
2683 if potential_co_authors.is_empty() {
2684 None
2685 } else {
2686 Some(
2687 IconButton::new("co-authors", IconName::Person)
2688 .shape(ui::IconButtonShape::Square)
2689 .icon_color(Color::Disabled)
2690 .selected_icon_color(Color::Selected)
2691 .toggle_state(self.add_coauthors)
2692 .tooltip(move |_, cx| {
2693 let title = format!(
2694 "Add co-authored-by:{}{}",
2695 if potential_co_authors.len() == 1 {
2696 ""
2697 } else {
2698 "\n"
2699 },
2700 potential_co_authors
2701 .iter()
2702 .map(|(name, email)| format!(" {} <{}>", name, email))
2703 .join("\n")
2704 );
2705 Tooltip::simple(title, cx)
2706 })
2707 .on_click(cx.listener(|this, _, _, cx| {
2708 this.add_coauthors = !this.add_coauthors;
2709 cx.notify();
2710 }))
2711 .into_any_element(),
2712 )
2713 }
2714 }
2715
2716 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2717 if self.has_unstaged_conflicts() {
2718 (false, "You must resolve conflicts before committing")
2719 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2720 (false, "No changes to commit")
2721 } else if self.pending_commit.is_some() {
2722 (false, "Commit in progress")
2723 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2724 (false, "No commit message")
2725 } else if !self.has_write_access(cx) {
2726 (false, "You do not have write access to this project")
2727 } else {
2728 (true, self.commit_button_title())
2729 }
2730 }
2731
2732 pub fn commit_button_title(&self) -> &'static str {
2733 if self.has_staged_changes() {
2734 "Commit"
2735 } else {
2736 "Commit Tracked"
2737 }
2738 }
2739
2740 fn expand_commit_editor(
2741 &mut self,
2742 _: &git::ExpandCommitEditor,
2743 window: &mut Window,
2744 cx: &mut Context<Self>,
2745 ) {
2746 let workspace = self.workspace.clone();
2747 window.defer(cx, move |window, cx| {
2748 workspace
2749 .update(cx, |workspace, cx| {
2750 CommitModal::toggle(workspace, window, cx)
2751 })
2752 .ok();
2753 })
2754 }
2755
2756 fn render_panel_header(
2757 &self,
2758 window: &mut Window,
2759 cx: &mut Context<Self>,
2760 ) -> Option<impl IntoElement> {
2761 self.active_repository.as_ref()?;
2762
2763 let text;
2764 let action;
2765 let tooltip;
2766 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2767 text = "Unstage All";
2768 action = git::UnstageAll.boxed_clone();
2769 tooltip = "git reset";
2770 } else {
2771 text = "Stage All";
2772 action = git::StageAll.boxed_clone();
2773 tooltip = "git add --all ."
2774 }
2775
2776 let change_string = match self.entry_count {
2777 0 => "No Changes".to_string(),
2778 1 => "1 Change".to_string(),
2779 _ => format!("{} Changes", self.entry_count),
2780 };
2781
2782 Some(
2783 self.panel_header_container(window, cx)
2784 .px_2()
2785 .child(
2786 panel_button(change_string)
2787 .color(Color::Muted)
2788 .tooltip(Tooltip::for_action_title_in(
2789 "Open Diff",
2790 &Diff,
2791 &self.focus_handle,
2792 ))
2793 .on_click(|_, _, cx| {
2794 cx.defer(|cx| {
2795 cx.dispatch_action(&Diff);
2796 })
2797 }),
2798 )
2799 .child(div().flex_grow()) // spacer
2800 .child(self.render_overflow_menu("overflow_menu"))
2801 .child(div().w_2()) // another spacer
2802 .child(
2803 panel_filled_button(text)
2804 .tooltip(Tooltip::for_action_title_in(
2805 tooltip,
2806 action.as_ref(),
2807 &self.focus_handle,
2808 ))
2809 .disabled(self.entry_count == 0)
2810 .on_click(move |_, _, cx| {
2811 let action = action.boxed_clone();
2812 cx.defer(move |cx| {
2813 cx.dispatch_action(action.as_ref());
2814 })
2815 }),
2816 ),
2817 )
2818 }
2819
2820 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2821 let branch = self
2822 .active_repository
2823 .as_ref()?
2824 .read(cx)
2825 .current_branch()
2826 .cloned();
2827 if !self.can_push_and_pull(cx) {
2828 return None;
2829 }
2830 let spinner = self.render_spinner();
2831 Some(
2832 h_flex()
2833 .gap_1()
2834 .flex_shrink_0()
2835 .children(spinner)
2836 .when_some(branch, |this, branch| {
2837 let focus_handle = Some(self.focus_handle(cx));
2838
2839 this.children(render_remote_button(
2840 "remote-button",
2841 &branch,
2842 focus_handle,
2843 true,
2844 ))
2845 })
2846 .into_any_element(),
2847 )
2848 }
2849
2850 pub fn render_footer(
2851 &self,
2852 window: &mut Window,
2853 cx: &mut Context<Self>,
2854 ) -> Option<impl IntoElement> {
2855 let active_repository = self.active_repository.clone()?;
2856 let (can_commit, tooltip) = self.configure_commit_button(cx);
2857 let project = self.project.clone().read(cx);
2858 let panel_editor_style = panel_editor_style(true, window, cx);
2859
2860 let enable_coauthors = self.render_co_authors(cx);
2861 let title = self.commit_button_title();
2862
2863 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2864 let commit_tooltip_focus_handle = editor_focus_handle.clone();
2865 let expand_tooltip_focus_handle = editor_focus_handle.clone();
2866
2867 let branch = active_repository.read(cx).current_branch().cloned();
2868
2869 let footer_size = px(32.);
2870 let gap = px(9.0);
2871 let max_height = panel_editor_style
2872 .text
2873 .line_height_in_pixels(window.rem_size())
2874 * MAX_PANEL_EDITOR_LINES
2875 + gap;
2876
2877 let git_panel = cx.entity().clone();
2878 let display_name = SharedString::from(Arc::from(
2879 active_repository
2880 .read(cx)
2881 .display_name(project, cx)
2882 .trim_end_matches("/"),
2883 ));
2884 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2885 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
2886 });
2887
2888 let footer = v_flex()
2889 .child(PanelRepoFooter::new(display_name, branch, Some(git_panel)))
2890 .child(
2891 panel_editor_container(window, cx)
2892 .id("commit-editor-container")
2893 .relative()
2894 .w_full()
2895 .h(max_height + footer_size)
2896 .border_t_1()
2897 .border_color(cx.theme().colors().border_variant)
2898 .cursor_text()
2899 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2900 window.focus(&this.commit_editor.focus_handle(cx));
2901 }))
2902 .child(
2903 h_flex()
2904 .id("commit-footer")
2905 .border_t_1()
2906 .when(editor_is_long, |el| {
2907 el.border_color(cx.theme().colors().border_variant)
2908 })
2909 .absolute()
2910 .bottom_0()
2911 .left_0()
2912 .w_full()
2913 .px_2()
2914 .h(footer_size)
2915 .flex_none()
2916 .justify_between()
2917 .child(
2918 self.render_generate_commit_message_button(cx)
2919 .unwrap_or_else(|| div().into_any_element()),
2920 )
2921 .child(
2922 h_flex().gap_0p5().children(enable_coauthors).child(
2923 panel_filled_button(title)
2924 .tooltip(move |window, cx| {
2925 if can_commit {
2926 Tooltip::for_action_in(
2927 tooltip,
2928 &Commit,
2929 &commit_tooltip_focus_handle,
2930 window,
2931 cx,
2932 )
2933 } else {
2934 Tooltip::simple(tooltip, cx)
2935 }
2936 })
2937 .disabled(!can_commit || self.modal_open)
2938 .on_click({
2939 cx.listener(move |this, _: &ClickEvent, window, cx| {
2940 telemetry::event!(
2941 "Git Committed",
2942 source = "Git Panel"
2943 );
2944 this.commit_changes(window, cx)
2945 })
2946 }),
2947 ),
2948 ),
2949 )
2950 .child(
2951 div()
2952 .pr_2p5()
2953 .on_action(|&editor::actions::MoveUp, _, cx| {
2954 cx.stop_propagation();
2955 })
2956 .on_action(|&editor::actions::MoveDown, _, cx| {
2957 cx.stop_propagation();
2958 })
2959 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2960 )
2961 .child(
2962 h_flex()
2963 .absolute()
2964 .top_2()
2965 .right_2()
2966 .opacity(0.5)
2967 .hover(|this| this.opacity(1.0))
2968 .child(
2969 panel_icon_button("expand-commit-editor", IconName::Maximize)
2970 .icon_size(IconSize::Small)
2971 .size(ui::ButtonSize::Default)
2972 .tooltip(move |window, cx| {
2973 Tooltip::for_action_in(
2974 "Open Commit Modal",
2975 &git::ExpandCommitEditor,
2976 &expand_tooltip_focus_handle,
2977 window,
2978 cx,
2979 )
2980 })
2981 .on_click(cx.listener({
2982 move |_, _, window, cx| {
2983 window.dispatch_action(
2984 git::ExpandCommitEditor.boxed_clone(),
2985 cx,
2986 )
2987 }
2988 })),
2989 ),
2990 ),
2991 );
2992
2993 Some(footer)
2994 }
2995
2996 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2997 let active_repository = self.active_repository.as_ref()?;
2998 let branch = active_repository.read(cx).current_branch()?;
2999 let commit = branch.most_recent_commit.as_ref()?.clone();
3000
3001 let this = cx.entity();
3002 Some(
3003 h_flex()
3004 .items_center()
3005 .py_2()
3006 .px(px(8.))
3007 .border_color(cx.theme().colors().border)
3008 .gap_1p5()
3009 .child(
3010 div()
3011 .flex_grow()
3012 .overflow_hidden()
3013 .items_center()
3014 .max_w(relative(0.85))
3015 .h_full()
3016 .child(
3017 Label::new(commit.subject.clone())
3018 .size(LabelSize::Small)
3019 .truncate(),
3020 )
3021 .id("commit-msg-hover")
3022 .hoverable_tooltip(move |window, cx| {
3023 GitPanelMessageTooltip::new(
3024 this.clone(),
3025 commit.sha.clone(),
3026 window,
3027 cx,
3028 )
3029 .into()
3030 }),
3031 )
3032 .child(div().flex_1())
3033 .when(commit.has_parent, |this| {
3034 let has_unstaged = self.has_unstaged_changes();
3035 this.child(
3036 panel_icon_button("undo", IconName::Undo)
3037 .icon_size(IconSize::Small)
3038 .icon_color(Color::Muted)
3039 .tooltip(move |window, cx| {
3040 Tooltip::with_meta(
3041 "Uncommit",
3042 Some(&git::Uncommit),
3043 if has_unstaged {
3044 "git reset HEAD^ --soft"
3045 } else {
3046 "git reset HEAD^"
3047 },
3048 window,
3049 cx,
3050 )
3051 })
3052 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3053 )
3054 }),
3055 )
3056 }
3057
3058 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3059 h_flex()
3060 .h_full()
3061 .flex_grow()
3062 .justify_center()
3063 .items_center()
3064 .child(
3065 v_flex()
3066 .gap_2()
3067 .child(h_flex().w_full().justify_around().child(
3068 if self.active_repository.is_some() {
3069 "No changes to commit"
3070 } else {
3071 "No Git repositories"
3072 },
3073 ))
3074 .children({
3075 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3076 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3077 h_flex().w_full().justify_around().child(
3078 panel_filled_button("Initialize Repository")
3079 .tooltip(Tooltip::for_action_title_in(
3080 "git init",
3081 &git::Init,
3082 &self.focus_handle,
3083 ))
3084 .on_click(move |_, _, cx| {
3085 cx.defer(move |cx| {
3086 cx.dispatch_action(&git::Init);
3087 })
3088 }),
3089 )
3090 })
3091 })
3092 .text_ui_sm(cx)
3093 .mx_auto()
3094 .text_color(Color::Placeholder.color(cx)),
3095 )
3096 }
3097
3098 fn render_vertical_scrollbar(
3099 &self,
3100 show_horizontal_scrollbar_container: bool,
3101 cx: &mut Context<Self>,
3102 ) -> impl IntoElement {
3103 div()
3104 .id("git-panel-vertical-scroll")
3105 .occlude()
3106 .flex_none()
3107 .h_full()
3108 .cursor_default()
3109 .absolute()
3110 .right_0()
3111 .top_0()
3112 .bottom_0()
3113 .w(px(12.))
3114 .when(show_horizontal_scrollbar_container, |this| {
3115 this.pb_neg_3p5()
3116 })
3117 .on_mouse_move(cx.listener(|_, _, _, cx| {
3118 cx.notify();
3119 cx.stop_propagation()
3120 }))
3121 .on_hover(|_, _, cx| {
3122 cx.stop_propagation();
3123 })
3124 .on_any_mouse_down(|_, _, cx| {
3125 cx.stop_propagation();
3126 })
3127 .on_mouse_up(
3128 MouseButton::Left,
3129 cx.listener(|this, _, window, cx| {
3130 if !this.vertical_scrollbar.state.is_dragging()
3131 && !this.focus_handle.contains_focused(window, cx)
3132 {
3133 this.vertical_scrollbar.hide(window, cx);
3134 cx.notify();
3135 }
3136
3137 cx.stop_propagation();
3138 }),
3139 )
3140 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3141 cx.notify();
3142 }))
3143 .children(Scrollbar::vertical(
3144 // percentage as f32..end_offset as f32,
3145 self.vertical_scrollbar.state.clone(),
3146 ))
3147 }
3148
3149 /// Renders the horizontal scrollbar.
3150 ///
3151 /// The right offset is used to determine how far to the right the
3152 /// scrollbar should extend to, useful for ensuring it doesn't collide
3153 /// with the vertical scrollbar when visible.
3154 fn render_horizontal_scrollbar(
3155 &self,
3156 right_offset: Pixels,
3157 cx: &mut Context<Self>,
3158 ) -> impl IntoElement {
3159 div()
3160 .id("git-panel-horizontal-scroll")
3161 .occlude()
3162 .flex_none()
3163 .w_full()
3164 .cursor_default()
3165 .absolute()
3166 .bottom_neg_px()
3167 .left_0()
3168 .right_0()
3169 .pr(right_offset)
3170 .on_mouse_move(cx.listener(|_, _, _, cx| {
3171 cx.notify();
3172 cx.stop_propagation()
3173 }))
3174 .on_hover(|_, _, cx| {
3175 cx.stop_propagation();
3176 })
3177 .on_any_mouse_down(|_, _, cx| {
3178 cx.stop_propagation();
3179 })
3180 .on_mouse_up(
3181 MouseButton::Left,
3182 cx.listener(|this, _, window, cx| {
3183 if !this.horizontal_scrollbar.state.is_dragging()
3184 && !this.focus_handle.contains_focused(window, cx)
3185 {
3186 this.horizontal_scrollbar.hide(window, cx);
3187 cx.notify();
3188 }
3189
3190 cx.stop_propagation();
3191 }),
3192 )
3193 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3194 cx.notify();
3195 }))
3196 .children(Scrollbar::horizontal(
3197 // percentage as f32..end_offset as f32,
3198 self.horizontal_scrollbar.state.clone(),
3199 ))
3200 }
3201
3202 fn render_buffer_header_controls(
3203 &self,
3204 entity: &Entity<Self>,
3205 file: &Arc<dyn File>,
3206 _: &Window,
3207 cx: &App,
3208 ) -> Option<AnyElement> {
3209 let repo = self.active_repository.as_ref()?.read(cx);
3210 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
3211 let ix = self.entry_by_path(&repo_path)?;
3212 let entry = self.entries.get(ix)?;
3213
3214 let entry_staging = self.entry_staging(entry.status_entry()?);
3215
3216 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3217 .disabled(!self.has_write_access(cx))
3218 .fill()
3219 .elevation(ElevationIndex::Surface)
3220 .on_click({
3221 let entry = entry.clone();
3222 let git_panel = entity.downgrade();
3223 move |_, window, cx| {
3224 git_panel
3225 .update(cx, |this, cx| {
3226 this.toggle_staged_for_entry(&entry, window, cx);
3227 cx.stop_propagation();
3228 })
3229 .ok();
3230 }
3231 });
3232 Some(
3233 h_flex()
3234 .id("start-slot")
3235 .text_lg()
3236 .child(checkbox)
3237 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3238 // prevent the list item active state triggering when toggling checkbox
3239 cx.stop_propagation();
3240 })
3241 .into_any_element(),
3242 )
3243 }
3244
3245 fn render_entries(
3246 &self,
3247 has_write_access: bool,
3248 _: &Window,
3249 cx: &mut Context<Self>,
3250 ) -> impl IntoElement {
3251 let entry_count = self.entries.len();
3252
3253 let scroll_track_size = px(16.);
3254
3255 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3256 // magic number
3257 px(3.)
3258 } else {
3259 px(0.)
3260 };
3261
3262 v_flex()
3263 .flex_1()
3264 .size_full()
3265 .overflow_hidden()
3266 .relative()
3267 // Show a border on the top and bottom of the container when
3268 // the vertical scrollbar container is visible so we don't have a
3269 // floating left border in the panel.
3270 .when(self.vertical_scrollbar.show_track, |this| {
3271 this.border_t_1()
3272 .border_b_1()
3273 .border_color(cx.theme().colors().border)
3274 })
3275 .child(
3276 h_flex()
3277 .flex_1()
3278 .size_full()
3279 .relative()
3280 .overflow_hidden()
3281 .child(
3282 uniform_list(cx.entity().clone(), "entries", entry_count, {
3283 move |this, range, window, cx| {
3284 let mut items = Vec::with_capacity(range.end - range.start);
3285
3286 for ix in range {
3287 match &this.entries.get(ix) {
3288 Some(GitListEntry::GitStatusEntry(entry)) => {
3289 items.push(this.render_entry(
3290 ix,
3291 entry,
3292 has_write_access,
3293 window,
3294 cx,
3295 ));
3296 }
3297 Some(GitListEntry::Header(header)) => {
3298 items.push(this.render_list_header(
3299 ix,
3300 header,
3301 has_write_access,
3302 window,
3303 cx,
3304 ));
3305 }
3306 None => {}
3307 }
3308 }
3309
3310 items
3311 }
3312 })
3313 .size_full()
3314 .flex_grow()
3315 .with_sizing_behavior(ListSizingBehavior::Auto)
3316 .with_horizontal_sizing_behavior(
3317 ListHorizontalSizingBehavior::Unconstrained,
3318 )
3319 .with_width_from_item(self.max_width_item_index)
3320 .track_scroll(self.scroll_handle.clone()),
3321 )
3322 .on_mouse_down(
3323 MouseButton::Right,
3324 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3325 this.deploy_panel_context_menu(event.position, window, cx)
3326 }),
3327 )
3328 .when(self.vertical_scrollbar.show_track, |this| {
3329 this.child(
3330 v_flex()
3331 .h_full()
3332 .flex_none()
3333 .w(scroll_track_size)
3334 .bg(cx.theme().colors().panel_background)
3335 .child(
3336 div()
3337 .size_full()
3338 .flex_1()
3339 .border_l_1()
3340 .border_color(cx.theme().colors().border),
3341 ),
3342 )
3343 })
3344 .when(self.vertical_scrollbar.show_scrollbar, |this| {
3345 this.child(
3346 self.render_vertical_scrollbar(
3347 self.horizontal_scrollbar.show_track,
3348 cx,
3349 ),
3350 )
3351 }),
3352 )
3353 .when(self.horizontal_scrollbar.show_track, |this| {
3354 this.child(
3355 h_flex()
3356 .w_full()
3357 .h(scroll_track_size)
3358 .flex_none()
3359 .relative()
3360 .child(
3361 div()
3362 .w_full()
3363 .flex_1()
3364 // for some reason the horizontal scrollbar is 1px
3365 // taller than the vertical scrollbar??
3366 .h(scroll_track_size - px(1.))
3367 .bg(cx.theme().colors().panel_background)
3368 .border_t_1()
3369 .border_color(cx.theme().colors().border),
3370 )
3371 .when(self.vertical_scrollbar.show_track, |this| {
3372 this.child(
3373 div()
3374 .flex_none()
3375 // -1px prevents a missing pixel between the two container borders
3376 .w(scroll_track_size - px(1.))
3377 .h_full(),
3378 )
3379 .child(
3380 // HACK: Fill the missing 1px 🥲
3381 div()
3382 .absolute()
3383 .right(scroll_track_size - px(1.))
3384 .bottom(scroll_track_size - px(1.))
3385 .size_px()
3386 .bg(cx.theme().colors().border),
3387 )
3388 }),
3389 )
3390 })
3391 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3392 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3393 })
3394 }
3395
3396 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3397 Label::new(label.into()).color(color).single_line()
3398 }
3399
3400 fn list_item_height(&self) -> Rems {
3401 rems(1.75)
3402 }
3403
3404 fn render_list_header(
3405 &self,
3406 ix: usize,
3407 header: &GitHeaderEntry,
3408 _: bool,
3409 _: &Window,
3410 _: &Context<Self>,
3411 ) -> AnyElement {
3412 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3413
3414 h_flex()
3415 .id(id)
3416 .h(self.list_item_height())
3417 .w_full()
3418 .items_end()
3419 .px(rems(0.75)) // ~12px
3420 .pb(rems(0.3125)) // ~ 5px
3421 .child(
3422 Label::new(header.title())
3423 .color(Color::Muted)
3424 .size(LabelSize::Small)
3425 .line_height_style(LineHeightStyle::UiLabel)
3426 .single_line(),
3427 )
3428 .into_any_element()
3429 }
3430
3431 fn load_commit_details(
3432 &self,
3433 sha: String,
3434 cx: &mut Context<Self>,
3435 ) -> Task<anyhow::Result<CommitDetails>> {
3436 let Some(repo) = self.active_repository.clone() else {
3437 return Task::ready(Err(anyhow::anyhow!("no active repo")));
3438 };
3439 repo.update(cx, |repo, cx| {
3440 let show = repo.show(sha);
3441 cx.spawn(async move |_, _| show.await?)
3442 })
3443 }
3444
3445 fn deploy_entry_context_menu(
3446 &mut self,
3447 position: Point<Pixels>,
3448 ix: usize,
3449 window: &mut Window,
3450 cx: &mut Context<Self>,
3451 ) {
3452 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3453 return;
3454 };
3455 let stage_title = if entry.status.staging().is_fully_staged() {
3456 "Unstage File"
3457 } else {
3458 "Stage File"
3459 };
3460 let restore_title = if entry.status.is_created() {
3461 "Trash File"
3462 } else {
3463 "Restore File"
3464 };
3465 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3466 context_menu
3467 .context(self.focus_handle.clone())
3468 .action(stage_title, ToggleStaged.boxed_clone())
3469 .action(restore_title, git::RestoreFile.boxed_clone())
3470 .separator()
3471 .action("Open Diff", Confirm.boxed_clone())
3472 .action("Open File", SecondaryConfirm.boxed_clone())
3473 });
3474 self.selected_entry = Some(ix);
3475 self.set_context_menu(context_menu, position, window, cx);
3476 }
3477
3478 fn deploy_panel_context_menu(
3479 &mut self,
3480 position: Point<Pixels>,
3481 window: &mut Window,
3482 cx: &mut Context<Self>,
3483 ) {
3484 let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3485 self.set_context_menu(context_menu, position, window, cx);
3486 }
3487
3488 fn set_context_menu(
3489 &mut self,
3490 context_menu: Entity<ContextMenu>,
3491 position: Point<Pixels>,
3492 window: &Window,
3493 cx: &mut Context<Self>,
3494 ) {
3495 let subscription = cx.subscribe_in(
3496 &context_menu,
3497 window,
3498 |this, _, _: &DismissEvent, window, cx| {
3499 if this.context_menu.as_ref().is_some_and(|context_menu| {
3500 context_menu.0.focus_handle(cx).contains_focused(window, cx)
3501 }) {
3502 cx.focus_self(window);
3503 }
3504 this.context_menu.take();
3505 cx.notify();
3506 },
3507 );
3508 self.context_menu = Some((context_menu, position, subscription));
3509 cx.notify();
3510 }
3511
3512 fn render_entry(
3513 &self,
3514 ix: usize,
3515 entry: &GitStatusEntry,
3516 has_write_access: bool,
3517 window: &Window,
3518 cx: &Context<Self>,
3519 ) -> AnyElement {
3520 let display_name = entry.display_name();
3521
3522 let selected = self.selected_entry == Some(ix);
3523 let marked = self.marked_entries.contains(&ix);
3524 let status_style = GitPanelSettings::get_global(cx).status_style;
3525 let status = entry.status;
3526 let modifiers = self.current_modifiers;
3527 let shift_held = modifiers.shift;
3528
3529 let has_conflict = status.is_conflicted();
3530 let is_modified = status.is_modified();
3531 let is_deleted = status.is_deleted();
3532
3533 let label_color = if status_style == StatusStyle::LabelColor {
3534 if has_conflict {
3535 Color::VersionControlConflict
3536 } else if is_modified {
3537 Color::VersionControlModified
3538 } else if is_deleted {
3539 // We don't want a bunch of red labels in the list
3540 Color::Disabled
3541 } else {
3542 Color::VersionControlAdded
3543 }
3544 } else {
3545 Color::Default
3546 };
3547
3548 let path_color = if status.is_deleted() {
3549 Color::Disabled
3550 } else {
3551 Color::Muted
3552 };
3553
3554 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3555 let checkbox_wrapper_id: ElementId =
3556 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3557 let checkbox_id: ElementId =
3558 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3559
3560 let entry_staging = self.entry_staging(entry);
3561 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3562
3563 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3564 is_staged = ToggleState::Selected;
3565 }
3566
3567 let handle = cx.weak_entity();
3568
3569 let selected_bg_alpha = 0.08;
3570 let marked_bg_alpha = 0.12;
3571 let state_opacity_step = 0.04;
3572
3573 let base_bg = match (selected, marked) {
3574 (true, true) => cx
3575 .theme()
3576 .status()
3577 .info
3578 .alpha(selected_bg_alpha + marked_bg_alpha),
3579 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3580 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3581 _ => cx.theme().colors().ghost_element_background,
3582 };
3583
3584 let hover_bg = if selected {
3585 cx.theme()
3586 .status()
3587 .info
3588 .alpha(selected_bg_alpha + state_opacity_step)
3589 } else {
3590 cx.theme().colors().ghost_element_hover
3591 };
3592
3593 let active_bg = if selected {
3594 cx.theme()
3595 .status()
3596 .info
3597 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3598 } else {
3599 cx.theme().colors().ghost_element_active
3600 };
3601
3602 h_flex()
3603 .id(id)
3604 .h(self.list_item_height())
3605 .w_full()
3606 .items_center()
3607 .border_1()
3608 .when(selected && self.focus_handle.is_focused(window), |el| {
3609 el.border_color(cx.theme().colors().border_focused)
3610 })
3611 .px(rems(0.75)) // ~12px
3612 .overflow_hidden()
3613 .flex_none()
3614 .gap_1p5()
3615 .bg(base_bg)
3616 .hover(|this| this.bg(hover_bg))
3617 .active(|this| this.bg(active_bg))
3618 .on_click({
3619 cx.listener(move |this, event: &ClickEvent, window, cx| {
3620 this.selected_entry = Some(ix);
3621 cx.notify();
3622 if event.modifiers().secondary() {
3623 this.open_file(&Default::default(), window, cx)
3624 } else {
3625 this.open_diff(&Default::default(), window, cx);
3626 this.focus_handle.focus(window);
3627 }
3628 })
3629 })
3630 .on_mouse_down(
3631 MouseButton::Right,
3632 move |event: &MouseDownEvent, window, cx| {
3633 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3634 if event.button != MouseButton::Right {
3635 return;
3636 }
3637
3638 let Some(this) = handle.upgrade() else {
3639 return;
3640 };
3641 this.update(cx, |this, cx| {
3642 this.deploy_entry_context_menu(event.position, ix, window, cx);
3643 });
3644 cx.stop_propagation();
3645 },
3646 )
3647 // .on_secondary_mouse_down(cx.listener(
3648 // move |this, event: &MouseDownEvent, window, cx| {
3649 // this.deploy_entry_context_menu(event.position, ix, window, cx);
3650 // cx.stop_propagation();
3651 // },
3652 // ))
3653 .child(
3654 div()
3655 .id(checkbox_wrapper_id)
3656 .flex_none()
3657 .occlude()
3658 .cursor_pointer()
3659 .child(
3660 Checkbox::new(checkbox_id, is_staged)
3661 .disabled(!has_write_access)
3662 .fill()
3663 .placeholder(
3664 !self.has_staged_changes()
3665 && !self.has_conflicts()
3666 && !entry.status.is_created(),
3667 )
3668 .elevation(ElevationIndex::Surface)
3669 .on_click({
3670 let entry = entry.clone();
3671 cx.listener(move |this, _, window, cx| {
3672 if !has_write_access {
3673 return;
3674 }
3675 this.toggle_staged_for_entry(
3676 &GitListEntry::GitStatusEntry(entry.clone()),
3677 window,
3678 cx,
3679 );
3680 cx.stop_propagation();
3681 })
3682 })
3683 .tooltip(move |window, cx| {
3684 let is_staged = entry_staging.is_fully_staged();
3685
3686 let action = if is_staged { "Unstage" } else { "Stage" };
3687 let tooltip_name = if shift_held {
3688 format!("{} section", action)
3689 } else {
3690 action.to_string()
3691 };
3692
3693 let meta = if shift_held {
3694 format!(
3695 "Release shift to {} single entry",
3696 action.to_lowercase()
3697 )
3698 } else {
3699 format!("Shift click to {} section", action.to_lowercase())
3700 };
3701
3702 Tooltip::with_meta(
3703 tooltip_name,
3704 Some(&ToggleStaged),
3705 meta,
3706 window,
3707 cx,
3708 )
3709 }),
3710 ),
3711 )
3712 .child(git_status_icon(status))
3713 .child(
3714 h_flex()
3715 .items_center()
3716 .flex_1()
3717 // .overflow_hidden()
3718 .when_some(entry.parent_dir(), |this, parent| {
3719 if !parent.is_empty() {
3720 this.child(
3721 self.entry_label(format!("{}/", parent), path_color)
3722 .when(status.is_deleted(), |this| this.strikethrough()),
3723 )
3724 } else {
3725 this
3726 }
3727 })
3728 .child(
3729 self.entry_label(display_name.clone(), label_color)
3730 .when(status.is_deleted(), |this| this.strikethrough()),
3731 ),
3732 )
3733 .into_any_element()
3734 }
3735
3736 fn has_write_access(&self, cx: &App) -> bool {
3737 !self.project.read(cx).is_read_only(cx)
3738 }
3739}
3740
3741fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3742 assistant_settings::AssistantSettings::get_global(cx)
3743 .enabled
3744 .then(|| {
3745 let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3746 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3747 provider.is_authenticated(cx).then(|| model)
3748 })
3749 .flatten()
3750}
3751
3752impl Render for GitPanel {
3753 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3754 let project = self.project.read(cx);
3755 let has_entries = self.entries.len() > 0;
3756 let room = self
3757 .workspace
3758 .upgrade()
3759 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3760
3761 let has_write_access = self.has_write_access(cx);
3762
3763 let has_co_authors = room.map_or(false, |room| {
3764 room.read(cx)
3765 .remote_participants()
3766 .values()
3767 .any(|remote_participant| remote_participant.can_write())
3768 });
3769
3770 v_flex()
3771 .id("git_panel")
3772 .key_context(self.dispatch_context(window, cx))
3773 .track_focus(&self.focus_handle)
3774 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3775 .when(has_write_access && !project.is_read_only(cx), |this| {
3776 this.on_action(cx.listener(Self::toggle_staged_for_selected))
3777 .on_action(cx.listener(GitPanel::commit))
3778 .on_action(cx.listener(Self::stage_all))
3779 .on_action(cx.listener(Self::unstage_all))
3780 .on_action(cx.listener(Self::stage_selected))
3781 .on_action(cx.listener(Self::unstage_selected))
3782 .on_action(cx.listener(Self::restore_tracked_files))
3783 .on_action(cx.listener(Self::revert_selected))
3784 .on_action(cx.listener(Self::clean_all))
3785 .on_action(cx.listener(Self::generate_commit_message_action))
3786 })
3787 .on_action(cx.listener(Self::select_first))
3788 .on_action(cx.listener(Self::select_next))
3789 .on_action(cx.listener(Self::select_previous))
3790 .on_action(cx.listener(Self::select_last))
3791 .on_action(cx.listener(Self::close_panel))
3792 .on_action(cx.listener(Self::open_diff))
3793 .on_action(cx.listener(Self::open_file))
3794 .on_action(cx.listener(Self::focus_changes_list))
3795 .on_action(cx.listener(Self::focus_editor))
3796 .on_action(cx.listener(Self::expand_commit_editor))
3797 .when(has_write_access && has_co_authors, |git_panel| {
3798 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3799 })
3800 .on_hover(cx.listener(move |this, hovered, window, cx| {
3801 if *hovered {
3802 this.horizontal_scrollbar.show(cx);
3803 this.vertical_scrollbar.show(cx);
3804 cx.notify();
3805 } else if !this.focus_handle.contains_focused(window, cx) {
3806 this.hide_scrollbars(window, cx);
3807 }
3808 }))
3809 .size_full()
3810 .overflow_hidden()
3811 .bg(cx.theme().colors().panel_background)
3812 .child(
3813 v_flex()
3814 .size_full()
3815 .children(self.render_panel_header(window, cx))
3816 .map(|this| {
3817 if has_entries {
3818 this.child(self.render_entries(has_write_access, window, cx))
3819 } else {
3820 this.child(self.render_empty_state(cx).into_any_element())
3821 }
3822 })
3823 .children(self.render_footer(window, cx))
3824 .children(self.render_previous_commit(cx))
3825 .into_any_element(),
3826 )
3827 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3828 deferred(
3829 anchored()
3830 .position(*position)
3831 .anchor(Corner::TopLeft)
3832 .child(menu.clone()),
3833 )
3834 .with_priority(1)
3835 }))
3836 }
3837}
3838
3839impl Focusable for GitPanel {
3840 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3841 if self.entries.is_empty() {
3842 self.commit_editor.focus_handle(cx)
3843 } else {
3844 self.focus_handle.clone()
3845 }
3846 }
3847}
3848
3849impl EventEmitter<Event> for GitPanel {}
3850
3851impl EventEmitter<PanelEvent> for GitPanel {}
3852
3853pub(crate) struct GitPanelAddon {
3854 pub(crate) workspace: WeakEntity<Workspace>,
3855}
3856
3857impl editor::Addon for GitPanelAddon {
3858 fn to_any(&self) -> &dyn std::any::Any {
3859 self
3860 }
3861
3862 fn render_buffer_header_controls(
3863 &self,
3864 excerpt_info: &ExcerptInfo,
3865 window: &Window,
3866 cx: &App,
3867 ) -> Option<AnyElement> {
3868 let file = excerpt_info.buffer.file()?;
3869 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3870
3871 git_panel
3872 .read(cx)
3873 .render_buffer_header_controls(&git_panel, &file, window, cx)
3874 }
3875}
3876
3877impl Panel for GitPanel {
3878 fn persistent_name() -> &'static str {
3879 "GitPanel"
3880 }
3881
3882 fn position(&self, _: &Window, cx: &App) -> DockPosition {
3883 GitPanelSettings::get_global(cx).dock
3884 }
3885
3886 fn position_is_valid(&self, position: DockPosition) -> bool {
3887 matches!(position, DockPosition::Left | DockPosition::Right)
3888 }
3889
3890 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3891 settings::update_settings_file::<GitPanelSettings>(
3892 self.fs.clone(),
3893 cx,
3894 move |settings, _| settings.dock = Some(position),
3895 );
3896 }
3897
3898 fn size(&self, _: &Window, cx: &App) -> Pixels {
3899 self.width
3900 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3901 }
3902
3903 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3904 self.width = size;
3905 self.serialize(cx);
3906 cx.notify();
3907 }
3908
3909 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3910 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3911 }
3912
3913 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3914 Some("Git Panel")
3915 }
3916
3917 fn toggle_action(&self) -> Box<dyn Action> {
3918 Box::new(ToggleFocus)
3919 }
3920
3921 fn activation_priority(&self) -> u32 {
3922 2
3923 }
3924}
3925
3926impl PanelHeader for GitPanel {}
3927
3928struct GitPanelMessageTooltip {
3929 commit_tooltip: Option<Entity<CommitTooltip>>,
3930}
3931
3932impl GitPanelMessageTooltip {
3933 fn new(
3934 git_panel: Entity<GitPanel>,
3935 sha: SharedString,
3936 window: &mut Window,
3937 cx: &mut App,
3938 ) -> Entity<Self> {
3939 cx.new(|cx| {
3940 cx.spawn_in(window, async move |this, cx| {
3941 let details = git_panel
3942 .update(cx, |git_panel, cx| {
3943 git_panel.load_commit_details(sha.to_string(), cx)
3944 })?
3945 .await?;
3946
3947 let commit_details = editor::commit_tooltip::CommitDetails {
3948 sha: details.sha.clone(),
3949 committer_name: details.committer_name.clone(),
3950 committer_email: details.committer_email.clone(),
3951 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3952 message: Some(editor::commit_tooltip::ParsedCommitMessage {
3953 message: details.message.clone(),
3954 ..Default::default()
3955 }),
3956 };
3957
3958 this.update_in(cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3959 this.commit_tooltip =
3960 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3961 cx.notify();
3962 })
3963 })
3964 .detach();
3965
3966 Self {
3967 commit_tooltip: None,
3968 }
3969 })
3970 }
3971}
3972
3973impl Render for GitPanelMessageTooltip {
3974 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3975 if let Some(commit_tooltip) = &self.commit_tooltip {
3976 commit_tooltip.clone().into_any_element()
3977 } else {
3978 gpui::Empty.into_any_element()
3979 }
3980 }
3981}
3982
3983#[derive(IntoElement, IntoComponent)]
3984#[component(scope = "Version Control")]
3985pub struct PanelRepoFooter {
3986 active_repository: SharedString,
3987 branch: Option<Branch>,
3988 // Getting a GitPanel in previews will be difficult.
3989 //
3990 // For now just take an option here, and we won't bind handlers to buttons in previews.
3991 git_panel: Option<Entity<GitPanel>>,
3992}
3993
3994impl PanelRepoFooter {
3995 pub fn new(
3996 active_repository: SharedString,
3997 branch: Option<Branch>,
3998 git_panel: Option<Entity<GitPanel>>,
3999 ) -> Self {
4000 Self {
4001 active_repository,
4002 branch,
4003 git_panel,
4004 }
4005 }
4006
4007 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4008 Self {
4009 active_repository,
4010 branch,
4011 git_panel: None,
4012 }
4013 }
4014}
4015
4016impl RenderOnce for PanelRepoFooter {
4017 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4018 let project = self
4019 .git_panel
4020 .as_ref()
4021 .map(|panel| panel.read(cx).project.clone());
4022
4023 let repo = self
4024 .git_panel
4025 .as_ref()
4026 .and_then(|panel| panel.read(cx).active_repository.clone());
4027
4028 let single_repo = project
4029 .as_ref()
4030 .map(|project| {
4031 filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
4032 })
4033 .unwrap_or(true);
4034
4035 const MAX_BRANCH_LEN: usize = 16;
4036 const MAX_REPO_LEN: usize = 16;
4037 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4038
4039 let branch = self.branch.clone();
4040 let branch_name = branch
4041 .as_ref()
4042 .map_or(" (no branch)".into(), |branch| branch.name.clone());
4043 let active_repo_name = self.active_repository.clone();
4044
4045 let branch_actual_len = branch_name.len();
4046 let repo_actual_len = active_repo_name.len();
4047
4048 // ideally, show the whole branch and repo names but
4049 // when we can't, use a budget to allocate space between the two
4050 let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4051 <= LABEL_CHARACTER_BUDGET
4052 {
4053 (repo_actual_len, branch_actual_len)
4054 } else {
4055 if branch_actual_len <= MAX_BRANCH_LEN {
4056 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4057 (repo_space, branch_actual_len)
4058 } else if repo_actual_len <= MAX_REPO_LEN {
4059 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4060 (repo_actual_len, branch_space)
4061 } else {
4062 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4063 }
4064 };
4065
4066 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4067 active_repo_name.to_string()
4068 } else {
4069 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4070 };
4071
4072 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4073 branch_name.to_string()
4074 } else {
4075 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4076 };
4077
4078 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4079 .style(ButtonStyle::Transparent)
4080 .size(ButtonSize::None)
4081 .label_size(LabelSize::Small)
4082 .color(Color::Muted);
4083
4084 let repo_selector = PopoverMenu::new("repository-switcher")
4085 .menu({
4086 let project = project.clone();
4087 move |window, cx| {
4088 let project = project.clone()?;
4089 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4090 }
4091 })
4092 .trigger_with_tooltip(
4093 repo_selector_trigger.disabled(single_repo).truncate(true),
4094 Tooltip::text("Switch active repository"),
4095 )
4096 .anchor(Corner::BottomLeft)
4097 .into_any_element();
4098
4099 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4100 .style(ButtonStyle::Transparent)
4101 .size(ButtonSize::None)
4102 .label_size(LabelSize::Small)
4103 .truncate(true)
4104 .tooltip(Tooltip::for_action_title(
4105 "Switch Branch",
4106 &zed_actions::git::Branch,
4107 ))
4108 .on_click(|_, window, cx| {
4109 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
4110 });
4111
4112 let branch_selector = PopoverMenu::new("popover-button")
4113 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4114 .trigger_with_tooltip(
4115 branch_selector_button,
4116 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
4117 )
4118 .anchor(Corner::BottomLeft)
4119 .offset(gpui::Point {
4120 x: px(0.0),
4121 y: px(-2.0),
4122 });
4123
4124 h_flex()
4125 .w_full()
4126 .px_2()
4127 .h(px(36.))
4128 .items_center()
4129 .justify_between()
4130 .gap_1()
4131 .child(
4132 h_flex()
4133 .flex_1()
4134 .overflow_hidden()
4135 .items_center()
4136 .child(
4137 div().child(
4138 Icon::new(IconName::GitBranchSmall)
4139 .size(IconSize::Small)
4140 .color(if single_repo {
4141 Color::Disabled
4142 } else {
4143 Color::Muted
4144 }),
4145 ),
4146 )
4147 .child(repo_selector)
4148 .when_some(branch.clone(), |this, _| {
4149 this.child(
4150 div()
4151 .text_color(cx.theme().colors().text_muted)
4152 .text_sm()
4153 .child("/"),
4154 )
4155 })
4156 .child(branch_selector),
4157 )
4158 .children(if let Some(git_panel) = self.git_panel {
4159 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4160 } else {
4161 None
4162 })
4163 }
4164}
4165
4166impl ComponentPreview for PanelRepoFooter {
4167 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
4168 let unknown_upstream = None;
4169 let no_remote_upstream = Some(UpstreamTracking::Gone);
4170 let ahead_of_upstream = Some(
4171 UpstreamTrackingStatus {
4172 ahead: 2,
4173 behind: 0,
4174 }
4175 .into(),
4176 );
4177 let behind_upstream = Some(
4178 UpstreamTrackingStatus {
4179 ahead: 0,
4180 behind: 2,
4181 }
4182 .into(),
4183 );
4184 let ahead_and_behind_upstream = Some(
4185 UpstreamTrackingStatus {
4186 ahead: 3,
4187 behind: 1,
4188 }
4189 .into(),
4190 );
4191
4192 let not_ahead_or_behind_upstream = Some(
4193 UpstreamTrackingStatus {
4194 ahead: 0,
4195 behind: 0,
4196 }
4197 .into(),
4198 );
4199
4200 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4201 Branch {
4202 is_head: true,
4203 name: "some-branch".into(),
4204 upstream: upstream.map(|tracking| Upstream {
4205 ref_name: "origin/some-branch".into(),
4206 tracking,
4207 }),
4208 most_recent_commit: Some(CommitSummary {
4209 sha: "abc123".into(),
4210 subject: "Modify stuff".into(),
4211 commit_timestamp: 1710932954,
4212 has_parent: true,
4213 }),
4214 }
4215 }
4216
4217 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4218 Branch {
4219 is_head: true,
4220 name: branch_name.to_string().into(),
4221 upstream: upstream.map(|tracking| Upstream {
4222 ref_name: format!("zed/{}", branch_name).into(),
4223 tracking,
4224 }),
4225 most_recent_commit: Some(CommitSummary {
4226 sha: "abc123".into(),
4227 subject: "Modify stuff".into(),
4228 commit_timestamp: 1710932954,
4229 has_parent: true,
4230 }),
4231 }
4232 }
4233
4234 fn active_repository(id: usize) -> SharedString {
4235 format!("repo-{}", id).into()
4236 }
4237
4238 let example_width = px(340.);
4239
4240 v_flex()
4241 .gap_6()
4242 .w_full()
4243 .flex_none()
4244 .children(vec![example_group_with_title(
4245 "Action Button States",
4246 vec![
4247 single_example(
4248 "No Branch",
4249 div()
4250 .w(example_width)
4251 .overflow_hidden()
4252 .child(PanelRepoFooter::new_preview(
4253 active_repository(1).clone(),
4254 None,
4255 ))
4256 .into_any_element(),
4257 )
4258 .grow(),
4259 single_example(
4260 "Remote status unknown",
4261 div()
4262 .w(example_width)
4263 .overflow_hidden()
4264 .child(PanelRepoFooter::new_preview(
4265 active_repository(2).clone(),
4266 Some(branch(unknown_upstream)),
4267 ))
4268 .into_any_element(),
4269 )
4270 .grow(),
4271 single_example(
4272 "No Remote Upstream",
4273 div()
4274 .w(example_width)
4275 .overflow_hidden()
4276 .child(PanelRepoFooter::new_preview(
4277 active_repository(3).clone(),
4278 Some(branch(no_remote_upstream)),
4279 ))
4280 .into_any_element(),
4281 )
4282 .grow(),
4283 single_example(
4284 "Not Ahead or Behind",
4285 div()
4286 .w(example_width)
4287 .overflow_hidden()
4288 .child(PanelRepoFooter::new_preview(
4289 active_repository(4).clone(),
4290 Some(branch(not_ahead_or_behind_upstream)),
4291 ))
4292 .into_any_element(),
4293 )
4294 .grow(),
4295 single_example(
4296 "Behind remote",
4297 div()
4298 .w(example_width)
4299 .overflow_hidden()
4300 .child(PanelRepoFooter::new_preview(
4301 active_repository(5).clone(),
4302 Some(branch(behind_upstream)),
4303 ))
4304 .into_any_element(),
4305 )
4306 .grow(),
4307 single_example(
4308 "Ahead of remote",
4309 div()
4310 .w(example_width)
4311 .overflow_hidden()
4312 .child(PanelRepoFooter::new_preview(
4313 active_repository(6).clone(),
4314 Some(branch(ahead_of_upstream)),
4315 ))
4316 .into_any_element(),
4317 )
4318 .grow(),
4319 single_example(
4320 "Ahead and behind remote",
4321 div()
4322 .w(example_width)
4323 .overflow_hidden()
4324 .child(PanelRepoFooter::new_preview(
4325 active_repository(7).clone(),
4326 Some(branch(ahead_and_behind_upstream)),
4327 ))
4328 .into_any_element(),
4329 )
4330 .grow(),
4331 ],
4332 )
4333 .grow()
4334 .vertical()])
4335 .children(vec![example_group_with_title(
4336 "Labels",
4337 vec![
4338 single_example(
4339 "Short Branch & Repo",
4340 div()
4341 .w(example_width)
4342 .overflow_hidden()
4343 .child(PanelRepoFooter::new_preview(
4344 SharedString::from("zed"),
4345 Some(custom("main", behind_upstream)),
4346 ))
4347 .into_any_element(),
4348 )
4349 .grow(),
4350 single_example(
4351 "Long Branch",
4352 div()
4353 .w(example_width)
4354 .overflow_hidden()
4355 .child(PanelRepoFooter::new_preview(
4356 SharedString::from("zed"),
4357 Some(custom(
4358 "redesign-and-update-git-ui-list-entry-style",
4359 behind_upstream,
4360 )),
4361 ))
4362 .into_any_element(),
4363 )
4364 .grow(),
4365 single_example(
4366 "Long Repo",
4367 div()
4368 .w(example_width)
4369 .overflow_hidden()
4370 .child(PanelRepoFooter::new_preview(
4371 SharedString::from("zed-industries-community-examples"),
4372 Some(custom("gpui", ahead_of_upstream)),
4373 ))
4374 .into_any_element(),
4375 )
4376 .grow(),
4377 single_example(
4378 "Long Repo & Branch",
4379 div()
4380 .w(example_width)
4381 .overflow_hidden()
4382 .child(PanelRepoFooter::new_preview(
4383 SharedString::from("zed-industries-community-examples"),
4384 Some(custom(
4385 "redesign-and-update-git-ui-list-entry-style",
4386 behind_upstream,
4387 )),
4388 ))
4389 .into_any_element(),
4390 )
4391 .grow(),
4392 single_example(
4393 "Uppercase Repo",
4394 div()
4395 .w(example_width)
4396 .overflow_hidden()
4397 .child(PanelRepoFooter::new_preview(
4398 SharedString::from("LICENSES"),
4399 Some(custom("main", ahead_of_upstream)),
4400 ))
4401 .into_any_element(),
4402 )
4403 .grow(),
4404 single_example(
4405 "Uppercase Branch",
4406 div()
4407 .w(example_width)
4408 .overflow_hidden()
4409 .child(PanelRepoFooter::new_preview(
4410 SharedString::from("zed"),
4411 Some(custom("update-README", behind_upstream)),
4412 ))
4413 .into_any_element(),
4414 )
4415 .grow(),
4416 ],
4417 )
4418 .grow()
4419 .vertical()])
4420 .into_any_element()
4421 }
4422}
4423
4424#[cfg(test)]
4425mod tests {
4426 use git::status::StatusCode;
4427 use gpui::TestAppContext;
4428 use project::{FakeFs, WorktreeSettings};
4429 use serde_json::json;
4430 use settings::SettingsStore;
4431 use theme::LoadThemes;
4432 use util::path;
4433
4434 use super::*;
4435
4436 fn init_test(cx: &mut gpui::TestAppContext) {
4437 if std::env::var("RUST_LOG").is_ok() {
4438 env_logger::try_init().ok();
4439 }
4440
4441 cx.update(|cx| {
4442 let settings_store = SettingsStore::test(cx);
4443 cx.set_global(settings_store);
4444 AssistantSettings::register(cx);
4445 WorktreeSettings::register(cx);
4446 workspace::init_settings(cx);
4447 theme::init(LoadThemes::JustBase, cx);
4448 language::init(cx);
4449 editor::init(cx);
4450 Project::init_settings(cx);
4451 crate::init(cx);
4452 });
4453 }
4454
4455 #[gpui::test]
4456 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4457 init_test(cx);
4458 let fs = FakeFs::new(cx.background_executor.clone());
4459 fs.insert_tree(
4460 "/root",
4461 json!({
4462 "zed": {
4463 ".git": {},
4464 "crates": {
4465 "gpui": {
4466 "gpui.rs": "fn main() {}"
4467 },
4468 "util": {
4469 "util.rs": "fn do_it() {}"
4470 }
4471 }
4472 },
4473 }),
4474 )
4475 .await;
4476
4477 fs.set_status_for_repo(
4478 Path::new(path!("/root/zed/.git")),
4479 &[
4480 (
4481 Path::new("crates/gpui/gpui.rs"),
4482 StatusCode::Modified.worktree(),
4483 ),
4484 (
4485 Path::new("crates/util/util.rs"),
4486 StatusCode::Modified.worktree(),
4487 ),
4488 ],
4489 );
4490
4491 let project =
4492 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4493 let (workspace, cx) =
4494 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4495
4496 cx.read(|cx| {
4497 project
4498 .read(cx)
4499 .worktrees(cx)
4500 .nth(0)
4501 .unwrap()
4502 .read(cx)
4503 .as_local()
4504 .unwrap()
4505 .scan_complete()
4506 })
4507 .await;
4508
4509 cx.executor().run_until_parked();
4510
4511 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4512 let panel = cx.new_window_entity(|window, cx| {
4513 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4514 });
4515
4516 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4517 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4518 });
4519 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4520 handle.await;
4521
4522 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4523 pretty_assertions::assert_eq!(
4524 entries,
4525 [
4526 GitListEntry::Header(GitHeaderEntry {
4527 header: Section::Tracked
4528 }),
4529 GitListEntry::GitStatusEntry(GitStatusEntry {
4530 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4531 repo_path: "crates/gpui/gpui.rs".into(),
4532 worktree_path: Path::new("gpui.rs").into(),
4533 status: StatusCode::Modified.worktree(),
4534 staging: StageStatus::Unstaged,
4535 }),
4536 GitListEntry::GitStatusEntry(GitStatusEntry {
4537 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4538 repo_path: "crates/util/util.rs".into(),
4539 worktree_path: Path::new("../util/util.rs").into(),
4540 status: StatusCode::Modified.worktree(),
4541 staging: StageStatus::Unstaged,
4542 },),
4543 ],
4544 );
4545
4546 cx.update_window_entity(&panel, |panel, window, cx| {
4547 panel.select_last(&Default::default(), window, cx);
4548 assert_eq!(panel.selected_entry, Some(2));
4549 panel.open_diff(&Default::default(), window, cx);
4550 });
4551 cx.run_until_parked();
4552
4553 let worktree_roots = workspace.update(cx, |workspace, cx| {
4554 workspace
4555 .worktrees(cx)
4556 .map(|worktree| worktree.read(cx).abs_path())
4557 .collect::<Vec<_>>()
4558 });
4559 pretty_assertions::assert_eq!(
4560 worktree_roots,
4561 vec![
4562 Path::new(path!("/root/zed/crates/gpui")).into(),
4563 Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4564 ]
4565 );
4566
4567 project.update(cx, |project, cx| {
4568 let git_store = project.git_store().read(cx);
4569 // The repo that comes from the single-file worktree can't be selected through the UI.
4570 let filtered_entries = filtered_repository_entries(git_store, cx)
4571 .iter()
4572 .map(|repo| repo.read(cx).worktree_abs_path.clone())
4573 .collect::<Vec<_>>();
4574 assert_eq!(
4575 filtered_entries,
4576 [Path::new(path!("/root/zed/crates/gpui")).into()]
4577 );
4578 // But we can select it artificially here.
4579 let repo_from_single_file_worktree = git_store
4580 .repositories()
4581 .values()
4582 .find(|repo| {
4583 repo.read(cx).worktree_abs_path.as_ref()
4584 == Path::new(path!("/root/zed/crates/util/util.rs"))
4585 })
4586 .unwrap()
4587 .clone();
4588
4589 // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4590 repo_from_single_file_worktree.update(cx, |repo, cx| repo.set_as_active_repository(cx));
4591 });
4592
4593 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4594 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4595 });
4596 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4597 handle.await;
4598 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4599 pretty_assertions::assert_eq!(
4600 entries,
4601 [
4602 GitListEntry::Header(GitHeaderEntry {
4603 header: Section::Tracked
4604 }),
4605 GitListEntry::GitStatusEntry(GitStatusEntry {
4606 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4607 repo_path: "crates/gpui/gpui.rs".into(),
4608 worktree_path: Path::new("../../gpui/gpui.rs").into(),
4609 status: StatusCode::Modified.worktree(),
4610 staging: StageStatus::Unstaged,
4611 }),
4612 GitListEntry::GitStatusEntry(GitStatusEntry {
4613 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4614 repo_path: "crates/util/util.rs".into(),
4615 worktree_path: Path::new("util.rs").into(),
4616 status: StatusCode::Modified.worktree(),
4617 staging: StageStatus::Unstaged,
4618 },),
4619 ],
4620 );
4621 }
4622}