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