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 window,
362 cx,
363 );
364 commit_editor.set_collaboration_hub(Box::new(project));
365 commit_editor.set_use_autoclose(false);
366 commit_editor.set_show_gutter(false, cx);
367 commit_editor.set_show_wrap_guides(false, cx);
368 commit_editor.set_show_indent_guides(false, cx);
369 commit_editor.set_hard_wrap(Some(72), 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".to_string(), 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| {
1512 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1513 })?
1514 .await??;
1515
1516 Ok(Some(prior_head))
1517 } else {
1518 Ok(None)
1519 }
1520 })
1521 .await;
1522
1523 this.update_in(&mut cx, |this, window, cx| {
1524 this.pending_commit.take();
1525 match result {
1526 Ok(None) => {}
1527 Ok(Some(prior_commit)) => {
1528 this.commit_editor.update(cx, |editor, cx| {
1529 editor.set_text(prior_commit.message, window, cx)
1530 });
1531 }
1532 Err(e) => this.show_error_toast("reset", e, cx),
1533 }
1534 })
1535 .ok();
1536 });
1537
1538 self.pending_commit = Some(task);
1539 }
1540
1541 fn check_for_pushed_commits(
1542 &mut self,
1543 window: &mut Window,
1544 cx: &mut Context<Self>,
1545 ) -> impl Future<Output = Result<bool, anyhow::Error>> {
1546 let repo = self.active_repository.clone();
1547 let mut cx = window.to_async(cx);
1548
1549 async move {
1550 let Some(repo) = repo else {
1551 return Err(anyhow::anyhow!("No active repository"));
1552 };
1553
1554 let pushed_to: Vec<SharedString> = repo
1555 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1556 .await??;
1557
1558 if pushed_to.is_empty() {
1559 Ok(true)
1560 } else {
1561 #[derive(strum::EnumIter, strum::VariantNames)]
1562 #[strum(serialize_all = "title_case")]
1563 enum CancelUncommit {
1564 Uncommit,
1565 Cancel,
1566 }
1567 let detail = format!(
1568 "This commit was already pushed to {}.",
1569 pushed_to.into_iter().join(", ")
1570 );
1571 let result = cx
1572 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1573 .await?;
1574
1575 match result {
1576 CancelUncommit::Cancel => Ok(false),
1577 CancelUncommit::Uncommit => Ok(true),
1578 }
1579 }
1580 }
1581 }
1582
1583 /// Suggests a commit message based on the changed files and their statuses
1584 pub fn suggest_commit_message(&self) -> Option<String> {
1585 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1586 Some(staged_entry)
1587 } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1588 Some(single_tracked_entry)
1589 } else {
1590 None
1591 }?;
1592
1593 let action_text = if git_status_entry.status.is_deleted() {
1594 Some("Delete")
1595 } else if git_status_entry.status.is_created() {
1596 Some("Create")
1597 } else if git_status_entry.status.is_modified() {
1598 Some("Update")
1599 } else {
1600 None
1601 }?;
1602
1603 let file_name = git_status_entry
1604 .repo_path
1605 .file_name()
1606 .unwrap_or_default()
1607 .to_string_lossy();
1608
1609 Some(format!("{} {}", action_text, file_name))
1610 }
1611
1612 fn generate_commit_message_action(
1613 &mut self,
1614 _: &git::GenerateCommitMessage,
1615 _window: &mut Window,
1616 cx: &mut Context<Self>,
1617 ) {
1618 self.generate_commit_message(cx);
1619 }
1620
1621 /// Generates a commit message using an LLM.
1622 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1623 if !self.can_commit() {
1624 return;
1625 }
1626
1627 let model = match current_language_model(cx) {
1628 Some(value) => value,
1629 None => return,
1630 };
1631
1632 let Some(repo) = self.active_repository.as_ref() else {
1633 return;
1634 };
1635
1636 telemetry::event!("Git Commit Message Generated");
1637
1638 let diff = repo.update(cx, |repo, cx| {
1639 if self.has_staged_changes() {
1640 repo.diff(DiffType::HeadToIndex, cx)
1641 } else {
1642 repo.diff(DiffType::HeadToWorktree, cx)
1643 }
1644 });
1645
1646 self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1647 async move {
1648 let _defer = util::defer({
1649 let mut cx = cx.clone();
1650 let this = this.clone();
1651 move || {
1652 this.update(&mut cx, |this, _cx| {
1653 this.generate_commit_message_task.take();
1654 })
1655 .ok();
1656 }
1657 });
1658
1659 let mut diff_text = diff.await??;
1660
1661 const ONE_MB: usize = 1_000_000;
1662 if diff_text.len() > ONE_MB {
1663 diff_text = diff_text.chars().take(ONE_MB).collect()
1664 }
1665
1666 let subject = this.update(&mut cx, |this, cx| {
1667 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1668 })?;
1669
1670 let text_empty = subject.trim().is_empty();
1671
1672 let content = if text_empty {
1673 format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1674 } else {
1675 format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1676 };
1677
1678 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1679
1680 let request = LanguageModelRequest {
1681 messages: vec![LanguageModelRequestMessage {
1682 role: Role::User,
1683 content: vec![content.into()],
1684 cache: false,
1685 }],
1686 tools: Vec::new(),
1687 stop: Vec::new(),
1688 temperature: None,
1689 };
1690
1691 let stream = model.stream_completion_text(request, &cx);
1692 let mut messages = stream.await?;
1693
1694 if !text_empty {
1695 this.update(&mut cx, |this, cx| {
1696 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1697 let insert_position = buffer.anchor_before(buffer.len());
1698 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1699 });
1700 })?;
1701 }
1702
1703 while let Some(message) = messages.stream.next().await {
1704 let text = message?;
1705
1706 this.update(&mut cx, |this, cx| {
1707 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1708 let insert_position = buffer.anchor_before(buffer.len());
1709 buffer.edit([(insert_position..insert_position, text)], None, cx);
1710 });
1711 })?;
1712 }
1713
1714 anyhow::Ok(())
1715 }
1716 .log_err()
1717 }));
1718 }
1719
1720 fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1721 let suggested_commit_message = self.suggest_commit_message();
1722 let placeholder_text = suggested_commit_message
1723 .as_deref()
1724 .unwrap_or("Enter commit message");
1725
1726 self.commit_editor.update(cx, |editor, cx| {
1727 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1728 });
1729
1730 cx.notify();
1731 }
1732
1733 pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1734 if !self.can_push_and_pull(cx) {
1735 return;
1736 }
1737
1738 let Some(repo) = self.active_repository.clone() else {
1739 return;
1740 };
1741 telemetry::event!("Git Fetched");
1742 let guard = self.start_remote_operation();
1743 let askpass = self.askpass_delegate("git fetch", window, cx);
1744 let this = cx.weak_entity();
1745 window
1746 .spawn(cx, |mut cx| async move {
1747 let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1748
1749 let remote_message = fetch.await?;
1750 drop(guard);
1751 this.update(&mut cx, |this, cx| {
1752 let action = RemoteAction::Fetch;
1753 match remote_message {
1754 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1755 Err(e) => {
1756 log::error!("Error while fetching {:?}", e);
1757 this.show_error_toast(action.name(), e, cx)
1758 }
1759 }
1760
1761 anyhow::Ok(())
1762 })
1763 .ok();
1764 anyhow::Ok(())
1765 })
1766 .detach_and_log_err(cx);
1767 }
1768
1769 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1770 let worktrees = self
1771 .project
1772 .read(cx)
1773 .visible_worktrees(cx)
1774 .collect::<Vec<_>>();
1775
1776 let worktree = if worktrees.len() == 1 {
1777 Task::ready(Some(worktrees.first().unwrap().clone()))
1778 } else if worktrees.len() == 0 {
1779 let result = window.prompt(
1780 PromptLevel::Warning,
1781 "Unable to initialize a git repository",
1782 Some("Open a directory first"),
1783 &["Ok"],
1784 cx,
1785 );
1786 cx.background_executor()
1787 .spawn(async move {
1788 result.await.ok();
1789 })
1790 .detach();
1791 return;
1792 } else {
1793 let worktree_directories = worktrees
1794 .iter()
1795 .map(|worktree| worktree.read(cx).abs_path())
1796 .map(|worktree_abs_path| {
1797 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1798 Path::new("~")
1799 .join(path)
1800 .to_string_lossy()
1801 .to_string()
1802 .into()
1803 } else {
1804 worktree_abs_path.to_string_lossy().to_string().into()
1805 }
1806 })
1807 .collect_vec();
1808 let prompt = picker_prompt::prompt(
1809 "Where would you like to initialize this git repository?",
1810 worktree_directories,
1811 self.workspace.clone(),
1812 window,
1813 cx,
1814 );
1815
1816 cx.spawn(|_, _| async move { prompt.await.map(|ix| worktrees[ix].clone()) })
1817 };
1818
1819 cx.spawn_in(window, |this, mut cx| async move {
1820 let worktree = match worktree.await {
1821 Some(worktree) => worktree,
1822 None => {
1823 return;
1824 }
1825 };
1826
1827 let Ok(result) = this.update(&mut cx, |this, cx| {
1828 let fallback_branch_name = GitPanelSettings::get_global(cx)
1829 .fallback_branch_name
1830 .clone();
1831 this.project.read(cx).git_init(
1832 worktree.read(cx).abs_path(),
1833 fallback_branch_name,
1834 cx,
1835 )
1836 }) else {
1837 return;
1838 };
1839
1840 let result = result.await;
1841
1842 this.update_in(&mut cx, |this, _, cx| match result {
1843 Ok(()) => {}
1844 Err(e) => this.show_error_toast("init", e, cx),
1845 })
1846 .ok();
1847 })
1848 .detach();
1849 }
1850
1851 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1852 if !self.can_push_and_pull(cx) {
1853 return;
1854 }
1855 let Some(repo) = self.active_repository.clone() else {
1856 return;
1857 };
1858 let Some(branch) = repo.read(cx).current_branch() else {
1859 return;
1860 };
1861 telemetry::event!("Git Pulled");
1862 let branch = branch.clone();
1863 let remote = self.get_current_remote(window, cx);
1864 cx.spawn_in(window, move |this, mut cx| async move {
1865 let remote = match remote.await {
1866 Ok(Some(remote)) => remote,
1867 Ok(None) => {
1868 return Ok(());
1869 }
1870 Err(e) => {
1871 log::error!("Failed to get current remote: {}", e);
1872 this.update(&mut cx, |this, cx| this.show_error_toast("pull", e, cx))
1873 .ok();
1874 return Ok(());
1875 }
1876 };
1877
1878 let askpass = this.update_in(&mut cx, |this, window, cx| {
1879 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1880 })?;
1881
1882 let guard = this
1883 .update(&mut cx, |this, _| this.start_remote_operation())
1884 .ok();
1885
1886 let pull = repo.update(&mut cx, |repo, cx| {
1887 repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1888 })?;
1889
1890 let remote_message = pull.await?;
1891 drop(guard);
1892
1893 let action = RemoteAction::Pull(remote);
1894 this.update(&mut cx, |this, cx| match remote_message {
1895 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1896 Err(e) => {
1897 log::error!("Error while pulling {:?}", e);
1898 this.show_error_toast(action.name(), e, cx)
1899 }
1900 })
1901 .ok();
1902
1903 anyhow::Ok(())
1904 })
1905 .detach_and_log_err(cx);
1906 }
1907
1908 pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1909 if !self.can_push_and_pull(cx) {
1910 return;
1911 }
1912 let Some(repo) = self.active_repository.clone() else {
1913 return;
1914 };
1915 let Some(branch) = repo.read(cx).current_branch() else {
1916 return;
1917 };
1918 telemetry::event!("Git Pushed");
1919 let branch = branch.clone();
1920
1921 let options = if force_push {
1922 Some(PushOptions::Force)
1923 } else {
1924 match branch.upstream {
1925 Some(Upstream {
1926 tracking: UpstreamTracking::Gone,
1927 ..
1928 })
1929 | None => Some(PushOptions::SetUpstream),
1930 _ => None,
1931 }
1932 };
1933 let remote = self.get_current_remote(window, cx);
1934
1935 cx.spawn_in(window, move |this, mut cx| async move {
1936 let remote = match remote.await {
1937 Ok(Some(remote)) => remote,
1938 Ok(None) => {
1939 return Ok(());
1940 }
1941 Err(e) => {
1942 log::error!("Failed to get current remote: {}", e);
1943 this.update(&mut cx, |this, cx| this.show_error_toast("push", e, cx))
1944 .ok();
1945 return Ok(());
1946 }
1947 };
1948
1949 let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1950 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1951 })?;
1952
1953 let guard = this
1954 .update(&mut cx, |this, _| this.start_remote_operation())
1955 .ok();
1956
1957 let push = repo.update(&mut cx, |repo, cx| {
1958 repo.push(
1959 branch.name.clone(),
1960 remote.name.clone(),
1961 options,
1962 askpass_delegate,
1963 cx,
1964 )
1965 })?;
1966
1967 let remote_output = push.await?;
1968 drop(guard);
1969
1970 let action = RemoteAction::Push(branch.name, remote);
1971 this.update(&mut cx, |this, cx| match remote_output {
1972 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1973 Err(e) => {
1974 log::error!("Error while pushing {:?}", e);
1975 this.show_error_toast(action.name(), e, cx)
1976 }
1977 })?;
1978
1979 anyhow::Ok(())
1980 })
1981 .detach_and_log_err(cx);
1982 }
1983
1984 fn askpass_delegate(
1985 &self,
1986 operation: impl Into<SharedString>,
1987 window: &mut Window,
1988 cx: &mut Context<Self>,
1989 ) -> AskPassDelegate {
1990 let this = cx.weak_entity();
1991 let operation = operation.into();
1992 let window = window.window_handle();
1993 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1994 window
1995 .update(cx, |_, window, cx| {
1996 this.update(cx, |this, cx| {
1997 this.workspace.update(cx, |workspace, cx| {
1998 workspace.toggle_modal(window, cx, |window, cx| {
1999 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2000 });
2001 })
2002 })
2003 })
2004 .ok();
2005 })
2006 }
2007
2008 fn can_push_and_pull(&self, cx: &App) -> bool {
2009 !self.project.read(cx).is_via_collab()
2010 }
2011
2012 fn get_current_remote(
2013 &mut self,
2014 window: &mut Window,
2015 cx: &mut Context<Self>,
2016 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
2017 let repo = self.active_repository.clone();
2018 let workspace = self.workspace.clone();
2019 let mut cx = window.to_async(cx);
2020
2021 async move {
2022 let Some(repo) = repo else {
2023 return Err(anyhow::anyhow!("No active repository"));
2024 };
2025
2026 let mut current_remotes: Vec<Remote> = repo
2027 .update(&mut cx, |repo, _| {
2028 let Some(current_branch) = repo.current_branch() else {
2029 return Err(anyhow::anyhow!("No active branch"));
2030 };
2031
2032 Ok(repo.get_remotes(Some(current_branch.name.to_string())))
2033 })??
2034 .await??;
2035
2036 if current_remotes.len() == 0 {
2037 return Err(anyhow::anyhow!("No active remote"));
2038 } else if current_remotes.len() == 1 {
2039 return Ok(Some(current_remotes.pop().unwrap()));
2040 } else {
2041 let current_remotes: Vec<_> = current_remotes
2042 .into_iter()
2043 .map(|remotes| remotes.name)
2044 .collect();
2045 let selection = cx
2046 .update(|window, cx| {
2047 picker_prompt::prompt(
2048 "Pick which remote to push to",
2049 current_remotes.clone(),
2050 workspace,
2051 window,
2052 cx,
2053 )
2054 })?
2055 .await;
2056
2057 Ok(selection.map(|selection| Remote {
2058 name: current_remotes[selection].clone(),
2059 }))
2060 }
2061 }
2062 }
2063
2064 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2065 let mut new_co_authors = Vec::new();
2066 let project = self.project.read(cx);
2067
2068 let Some(room) = self
2069 .workspace
2070 .upgrade()
2071 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2072 else {
2073 return Vec::default();
2074 };
2075
2076 let room = room.read(cx);
2077
2078 for (peer_id, collaborator) in project.collaborators() {
2079 if collaborator.is_host {
2080 continue;
2081 }
2082
2083 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2084 continue;
2085 };
2086 if participant.can_write() && participant.user.email.is_some() {
2087 let email = participant.user.email.clone().unwrap();
2088
2089 new_co_authors.push((
2090 participant
2091 .user
2092 .name
2093 .clone()
2094 .unwrap_or_else(|| participant.user.github_login.clone()),
2095 email,
2096 ))
2097 }
2098 }
2099 if !project.is_local() && !project.is_read_only(cx) {
2100 if let Some(user) = room.local_participant_user(cx) {
2101 if let Some(email) = user.email.clone() {
2102 new_co_authors.push((
2103 user.name
2104 .clone()
2105 .unwrap_or_else(|| user.github_login.clone()),
2106 email.clone(),
2107 ))
2108 }
2109 }
2110 }
2111 new_co_authors
2112 }
2113
2114 fn toggle_fill_co_authors(
2115 &mut self,
2116 _: &ToggleFillCoAuthors,
2117 _: &mut Window,
2118 cx: &mut Context<Self>,
2119 ) {
2120 self.add_coauthors = !self.add_coauthors;
2121 cx.notify();
2122 }
2123
2124 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2125 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2126
2127 let existing_text = message.to_ascii_lowercase();
2128 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2129 let mut ends_with_co_authors = false;
2130 let existing_co_authors = existing_text
2131 .lines()
2132 .filter_map(|line| {
2133 let line = line.trim();
2134 if line.starts_with(&lowercase_co_author_prefix) {
2135 ends_with_co_authors = true;
2136 Some(line)
2137 } else {
2138 ends_with_co_authors = false;
2139 None
2140 }
2141 })
2142 .collect::<HashSet<_>>();
2143
2144 let new_co_authors = self
2145 .potential_co_authors(cx)
2146 .into_iter()
2147 .filter(|(_, email)| {
2148 !existing_co_authors
2149 .iter()
2150 .any(|existing| existing.contains(email.as_str()))
2151 })
2152 .collect::<Vec<_>>();
2153
2154 if new_co_authors.is_empty() {
2155 return;
2156 }
2157
2158 if !ends_with_co_authors {
2159 message.push('\n');
2160 }
2161 for (name, email) in new_co_authors {
2162 message.push('\n');
2163 message.push_str(CO_AUTHOR_PREFIX);
2164 message.push_str(&name);
2165 message.push_str(" <");
2166 message.push_str(&email);
2167 message.push('>');
2168 }
2169 message.push('\n');
2170 }
2171
2172 fn schedule_update(
2173 &mut self,
2174 clear_pending: bool,
2175 window: &mut Window,
2176 cx: &mut Context<Self>,
2177 ) {
2178 let handle = cx.entity().downgrade();
2179 self.reopen_commit_buffer(window, cx);
2180 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
2181 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2182 if let Some(git_panel) = handle.upgrade() {
2183 git_panel
2184 .update_in(&mut cx, |git_panel, window, cx| {
2185 if clear_pending {
2186 git_panel.clear_pending();
2187 }
2188 git_panel.update_visible_entries(cx);
2189 git_panel.update_editor_placeholder(cx);
2190 git_panel.update_scrollbar_properties(window, cx);
2191 })
2192 .ok();
2193 }
2194 });
2195 }
2196
2197 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2198 let Some(active_repo) = self.active_repository.as_ref() else {
2199 return;
2200 };
2201 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2202 let project = self.project.read(cx);
2203 active_repo.open_commit_buffer(
2204 Some(project.languages().clone()),
2205 project.buffer_store().clone(),
2206 cx,
2207 )
2208 });
2209
2210 cx.spawn_in(window, |git_panel, mut cx| async move {
2211 let buffer = load_buffer.await?;
2212 git_panel.update_in(&mut cx, |git_panel, window, cx| {
2213 if git_panel
2214 .commit_editor
2215 .read(cx)
2216 .buffer()
2217 .read(cx)
2218 .as_singleton()
2219 .as_ref()
2220 != Some(&buffer)
2221 {
2222 git_panel.commit_editor = cx.new(|cx| {
2223 commit_message_editor(
2224 buffer,
2225 git_panel.suggest_commit_message().as_deref(),
2226 git_panel.project.clone(),
2227 true,
2228 window,
2229 cx,
2230 )
2231 });
2232 }
2233 })
2234 })
2235 .detach_and_log_err(cx);
2236 }
2237
2238 fn clear_pending(&mut self) {
2239 self.pending.retain(|v| !v.finished)
2240 }
2241
2242 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2243 self.entries.clear();
2244 self.single_staged_entry.take();
2245 self.single_staged_entry.take();
2246 let mut changed_entries = Vec::new();
2247 let mut new_entries = Vec::new();
2248 let mut conflict_entries = Vec::new();
2249 let mut last_staged = None;
2250 let mut staged_count = 0;
2251 let mut max_width_item: Option<(RepoPath, usize)> = None;
2252
2253 let Some(repo) = self.active_repository.as_ref() else {
2254 // Just clear entries if no repository is active.
2255 cx.notify();
2256 return;
2257 };
2258
2259 let repo = repo.read(cx);
2260
2261 for entry in repo.status() {
2262 let is_conflict = repo.has_conflict(&entry.repo_path);
2263 let is_new = entry.status.is_created();
2264 let staging = entry.status.staging();
2265
2266 if self.pending.iter().any(|pending| {
2267 pending.target_status == TargetStatus::Reverted
2268 && !pending.finished
2269 && pending
2270 .entries
2271 .iter()
2272 .any(|pending| pending.repo_path == entry.repo_path)
2273 }) {
2274 continue;
2275 }
2276
2277 // dot_git_abs path always has at least one component, namely .git.
2278 let abs_path = repo
2279 .dot_git_abs_path
2280 .parent()
2281 .unwrap()
2282 .join(&entry.repo_path);
2283 let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2284 let entry = GitStatusEntry {
2285 repo_path: entry.repo_path.clone(),
2286 worktree_path,
2287 abs_path,
2288 status: entry.status,
2289 staging,
2290 };
2291
2292 if staging.has_staged() {
2293 staged_count += 1;
2294 last_staged = Some(entry.clone());
2295 }
2296
2297 let width_estimate = Self::item_width_estimate(
2298 entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2299 entry.display_name().len(),
2300 );
2301
2302 match max_width_item.as_mut() {
2303 Some((repo_path, estimate)) => {
2304 if width_estimate > *estimate {
2305 *repo_path = entry.repo_path.clone();
2306 *estimate = width_estimate;
2307 }
2308 }
2309 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2310 }
2311
2312 if is_conflict {
2313 conflict_entries.push(entry);
2314 } else if is_new {
2315 new_entries.push(entry);
2316 } else {
2317 changed_entries.push(entry);
2318 }
2319 }
2320
2321 let mut pending_staged_count = 0;
2322 let mut last_pending_staged = None;
2323 let mut pending_status_for_last_staged = None;
2324 for pending in self.pending.iter() {
2325 if pending.target_status == TargetStatus::Staged {
2326 pending_staged_count += pending.entries.len();
2327 last_pending_staged = pending.entries.iter().next().cloned();
2328 }
2329 if let Some(last_staged) = &last_staged {
2330 if pending
2331 .entries
2332 .iter()
2333 .any(|entry| entry.repo_path == last_staged.repo_path)
2334 {
2335 pending_status_for_last_staged = Some(pending.target_status);
2336 }
2337 }
2338 }
2339
2340 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2341 match pending_status_for_last_staged {
2342 Some(TargetStatus::Staged) | None => {
2343 self.single_staged_entry = last_staged;
2344 }
2345 _ => {}
2346 }
2347 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2348 self.single_staged_entry = last_pending_staged;
2349 }
2350
2351 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2352 self.single_tracked_entry = changed_entries.first().cloned();
2353 }
2354
2355 if conflict_entries.len() > 0 {
2356 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2357 header: Section::Conflict,
2358 }));
2359 self.entries.extend(
2360 conflict_entries
2361 .into_iter()
2362 .map(GitListEntry::GitStatusEntry),
2363 );
2364 }
2365
2366 if changed_entries.len() > 0 {
2367 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2368 header: Section::Tracked,
2369 }));
2370 self.entries.extend(
2371 changed_entries
2372 .into_iter()
2373 .map(GitListEntry::GitStatusEntry),
2374 );
2375 }
2376 if new_entries.len() > 0 {
2377 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2378 header: Section::New,
2379 }));
2380 self.entries
2381 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2382 }
2383
2384 if let Some((repo_path, _)) = max_width_item {
2385 self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2386 GitListEntry::GitStatusEntry(git_status_entry) => {
2387 git_status_entry.repo_path == repo_path
2388 }
2389 GitListEntry::Header(_) => false,
2390 });
2391 }
2392
2393 self.update_counts(repo);
2394
2395 self.select_first_entry_if_none(cx);
2396
2397 cx.notify();
2398 }
2399
2400 fn header_state(&self, header_type: Section) -> ToggleState {
2401 let (staged_count, count) = match header_type {
2402 Section::New => (self.new_staged_count, self.new_count),
2403 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2404 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2405 };
2406 if staged_count == 0 {
2407 ToggleState::Unselected
2408 } else if count == staged_count {
2409 ToggleState::Selected
2410 } else {
2411 ToggleState::Indeterminate
2412 }
2413 }
2414
2415 fn update_counts(&mut self, repo: &Repository) {
2416 self.conflicted_count = 0;
2417 self.conflicted_staged_count = 0;
2418 self.new_count = 0;
2419 self.tracked_count = 0;
2420 self.new_staged_count = 0;
2421 self.tracked_staged_count = 0;
2422 self.entry_count = 0;
2423 for entry in &self.entries {
2424 let Some(status_entry) = entry.status_entry() else {
2425 continue;
2426 };
2427 self.entry_count += 1;
2428 if repo.has_conflict(&status_entry.repo_path) {
2429 self.conflicted_count += 1;
2430 if self.entry_staging(status_entry).has_staged() {
2431 self.conflicted_staged_count += 1;
2432 }
2433 } else if status_entry.status.is_created() {
2434 self.new_count += 1;
2435 if self.entry_staging(status_entry).has_staged() {
2436 self.new_staged_count += 1;
2437 }
2438 } else {
2439 self.tracked_count += 1;
2440 if self.entry_staging(status_entry).has_staged() {
2441 self.tracked_staged_count += 1;
2442 }
2443 }
2444 }
2445 }
2446
2447 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2448 for pending in self.pending.iter().rev() {
2449 if pending
2450 .entries
2451 .iter()
2452 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2453 {
2454 match pending.target_status {
2455 TargetStatus::Staged => return StageStatus::Staged,
2456 TargetStatus::Unstaged => return StageStatus::Unstaged,
2457 TargetStatus::Reverted => continue,
2458 TargetStatus::Unchanged => continue,
2459 }
2460 }
2461 }
2462 entry.staging
2463 }
2464
2465 pub(crate) fn has_staged_changes(&self) -> bool {
2466 self.tracked_staged_count > 0
2467 || self.new_staged_count > 0
2468 || self.conflicted_staged_count > 0
2469 }
2470
2471 pub(crate) fn has_unstaged_changes(&self) -> bool {
2472 self.tracked_count > self.tracked_staged_count
2473 || self.new_count > self.new_staged_count
2474 || self.conflicted_count > self.conflicted_staged_count
2475 }
2476
2477 fn has_conflicts(&self) -> bool {
2478 self.conflicted_count > 0
2479 }
2480
2481 fn has_tracked_changes(&self) -> bool {
2482 self.tracked_count > 0
2483 }
2484
2485 pub fn has_unstaged_conflicts(&self) -> bool {
2486 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2487 }
2488
2489 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2490 let action = action.into();
2491 let Some(workspace) = self.workspace.upgrade() else {
2492 return;
2493 };
2494
2495 let message = e.to_string().trim().to_string();
2496 if message
2497 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2498 .next()
2499 .is_some()
2500 {
2501 return; // Hide the cancelled by user message
2502 } else {
2503 let project = self.project.clone();
2504 workspace.update(cx, |workspace, cx| {
2505 let workspace_weak = cx.weak_entity();
2506 let toast =
2507 StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2508 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2509 .action("View Log", move |window, cx| {
2510 let message = message.clone();
2511 let project = project.clone();
2512 let action = action.clone();
2513 workspace_weak
2514 .update(cx, move |workspace, cx| {
2515 Self::open_output(
2516 project, action, workspace, &message, window, cx,
2517 )
2518 })
2519 .ok();
2520 })
2521 });
2522 workspace.toggle_status_toast(toast, cx)
2523 });
2524 }
2525 }
2526
2527 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2528 let Some(workspace) = self.workspace.upgrade() else {
2529 return;
2530 };
2531
2532 workspace.update(cx, |workspace, cx| {
2533 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2534 let workspace_weak = cx.weak_entity();
2535 let operation = action.name();
2536
2537 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2538 use remote_output::SuccessStyle::*;
2539 let project = self.project.clone();
2540 match style {
2541 Toast { .. } => this,
2542 ToastWithLog { output } => this
2543 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2544 .action("View Log", move |window, cx| {
2545 let output = output.clone();
2546 let project = project.clone();
2547 let output =
2548 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2549 workspace_weak
2550 .update(cx, move |workspace, cx| {
2551 Self::open_output(
2552 project, operation, workspace, &output, window, cx,
2553 )
2554 })
2555 .ok();
2556 }),
2557 PushPrLink { link } => this
2558 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2559 .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2560 }
2561 });
2562 workspace.toggle_status_toast(status_toast, cx)
2563 });
2564 }
2565
2566 fn open_output(
2567 project: Entity<Project>,
2568 operation: impl Into<SharedString>,
2569 workspace: &mut Workspace,
2570 output: &str,
2571 window: &mut Window,
2572 cx: &mut Context<Workspace>,
2573 ) {
2574 let operation = operation.into();
2575 let buffer = cx.new(|cx| Buffer::local(output, cx));
2576 let editor = cx.new(|cx| {
2577 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2578 editor.buffer().update(cx, |buffer, cx| {
2579 buffer.set_title(format!("Output from git {operation}"), cx);
2580 });
2581 editor.set_read_only(true);
2582 editor
2583 });
2584
2585 workspace.add_item_to_center(Box::new(editor), window, cx);
2586 }
2587
2588 pub fn render_spinner(&self) -> Option<impl IntoElement> {
2589 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2590 Icon::new(IconName::ArrowCircle)
2591 .size(IconSize::XSmall)
2592 .color(Color::Info)
2593 .with_animation(
2594 "arrow-circle",
2595 Animation::new(Duration::from_secs(2)).repeat(),
2596 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2597 )
2598 .into_any_element()
2599 })
2600 }
2601
2602 pub fn can_commit(&self) -> bool {
2603 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2604 }
2605
2606 pub fn can_stage_all(&self) -> bool {
2607 self.has_unstaged_changes()
2608 }
2609
2610 pub fn can_unstage_all(&self) -> bool {
2611 self.has_staged_changes()
2612 }
2613
2614 // eventually we'll need to take depth into account here
2615 // if we add a tree view
2616 fn item_width_estimate(path: usize, file_name: usize) -> usize {
2617 path + file_name
2618 }
2619
2620 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2621 let focus_handle = self.focus_handle.clone();
2622 PopoverMenu::new(id.into())
2623 .trigger(
2624 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2625 .icon_size(IconSize::Small)
2626 .icon_color(Color::Muted),
2627 )
2628 .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
2629 .anchor(Corner::TopRight)
2630 }
2631
2632 pub(crate) fn render_generate_commit_message_button(
2633 &self,
2634 cx: &Context<Self>,
2635 ) -> Option<AnyElement> {
2636 current_language_model(cx).is_some().then(|| {
2637 if self.generate_commit_message_task.is_some() {
2638 return h_flex()
2639 .gap_1()
2640 .child(
2641 Icon::new(IconName::ArrowCircle)
2642 .size(IconSize::XSmall)
2643 .color(Color::Info)
2644 .with_animation(
2645 "arrow-circle",
2646 Animation::new(Duration::from_secs(2)).repeat(),
2647 |icon, delta| {
2648 icon.transform(Transformation::rotate(percentage(delta)))
2649 },
2650 ),
2651 )
2652 .child(
2653 Label::new("Generating Commit...")
2654 .size(LabelSize::Small)
2655 .color(Color::Muted),
2656 )
2657 .into_any_element();
2658 }
2659
2660 let can_commit = self.can_commit();
2661 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2662 IconButton::new("generate-commit-message", IconName::AiEdit)
2663 .shape(ui::IconButtonShape::Square)
2664 .icon_color(Color::Muted)
2665 .tooltip(move |window, cx| {
2666 if can_commit {
2667 Tooltip::for_action_in(
2668 "Generate Commit Message",
2669 &git::GenerateCommitMessage,
2670 &editor_focus_handle,
2671 window,
2672 cx,
2673 )
2674 } else {
2675 Tooltip::simple("No changes to commit", cx)
2676 }
2677 })
2678 .disabled(!can_commit)
2679 .on_click(cx.listener(move |this, _event, _window, cx| {
2680 this.generate_commit_message(cx);
2681 }))
2682 .into_any_element()
2683 })
2684 }
2685
2686 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2687 let potential_co_authors = self.potential_co_authors(cx);
2688 if potential_co_authors.is_empty() {
2689 None
2690 } else {
2691 Some(
2692 IconButton::new("co-authors", IconName::Person)
2693 .shape(ui::IconButtonShape::Square)
2694 .icon_color(Color::Disabled)
2695 .selected_icon_color(Color::Selected)
2696 .toggle_state(self.add_coauthors)
2697 .tooltip(move |_, cx| {
2698 let title = format!(
2699 "Add co-authored-by:{}{}",
2700 if potential_co_authors.len() == 1 {
2701 ""
2702 } else {
2703 "\n"
2704 },
2705 potential_co_authors
2706 .iter()
2707 .map(|(name, email)| format!(" {} <{}>", name, email))
2708 .join("\n")
2709 );
2710 Tooltip::simple(title, cx)
2711 })
2712 .on_click(cx.listener(|this, _, _, cx| {
2713 this.add_coauthors = !this.add_coauthors;
2714 cx.notify();
2715 }))
2716 .into_any_element(),
2717 )
2718 }
2719 }
2720
2721 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2722 if self.has_unstaged_conflicts() {
2723 (false, "You must resolve conflicts before committing")
2724 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2725 (false, "No changes to commit")
2726 } else if self.pending_commit.is_some() {
2727 (false, "Commit in progress")
2728 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2729 (false, "No commit message")
2730 } else if !self.has_write_access(cx) {
2731 (false, "You do not have write access to this project")
2732 } else {
2733 (true, self.commit_button_title())
2734 }
2735 }
2736
2737 pub fn commit_button_title(&self) -> &'static str {
2738 if self.has_staged_changes() {
2739 "Commit"
2740 } else {
2741 "Commit Tracked"
2742 }
2743 }
2744
2745 fn expand_commit_editor(
2746 &mut self,
2747 _: &git::ExpandCommitEditor,
2748 window: &mut Window,
2749 cx: &mut Context<Self>,
2750 ) {
2751 let workspace = self.workspace.clone();
2752 window.defer(cx, move |window, cx| {
2753 workspace
2754 .update(cx, |workspace, cx| {
2755 CommitModal::toggle(workspace, window, cx)
2756 })
2757 .ok();
2758 })
2759 }
2760
2761 fn render_panel_header(
2762 &self,
2763 window: &mut Window,
2764 cx: &mut Context<Self>,
2765 ) -> Option<impl IntoElement> {
2766 self.active_repository.as_ref()?;
2767
2768 let text;
2769 let action;
2770 let tooltip;
2771 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2772 text = "Unstage All";
2773 action = git::UnstageAll.boxed_clone();
2774 tooltip = "git reset";
2775 } else {
2776 text = "Stage All";
2777 action = git::StageAll.boxed_clone();
2778 tooltip = "git add --all ."
2779 }
2780
2781 let change_string = match self.entry_count {
2782 0 => "No Changes".to_string(),
2783 1 => "1 Change".to_string(),
2784 _ => format!("{} Changes", self.entry_count),
2785 };
2786
2787 Some(
2788 self.panel_header_container(window, cx)
2789 .px_2()
2790 .child(
2791 panel_button(change_string)
2792 .color(Color::Muted)
2793 .tooltip(Tooltip::for_action_title_in(
2794 "Open diff",
2795 &Diff,
2796 &self.focus_handle,
2797 ))
2798 .on_click(|_, _, cx| {
2799 cx.defer(|cx| {
2800 cx.dispatch_action(&Diff);
2801 })
2802 }),
2803 )
2804 .child(div().flex_grow()) // spacer
2805 .child(self.render_overflow_menu("overflow_menu"))
2806 .child(div().w_2()) // another spacer
2807 .child(
2808 panel_filled_button(text)
2809 .tooltip(Tooltip::for_action_title_in(
2810 tooltip,
2811 action.as_ref(),
2812 &self.focus_handle,
2813 ))
2814 .disabled(self.entry_count == 0)
2815 .on_click(move |_, _, cx| {
2816 let action = action.boxed_clone();
2817 cx.defer(move |cx| {
2818 cx.dispatch_action(action.as_ref());
2819 })
2820 }),
2821 ),
2822 )
2823 }
2824
2825 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2826 let branch = self
2827 .active_repository
2828 .as_ref()?
2829 .read(cx)
2830 .current_branch()
2831 .cloned();
2832 if !self.can_push_and_pull(cx) {
2833 return None;
2834 }
2835 let spinner = self.render_spinner();
2836 Some(
2837 h_flex()
2838 .gap_1()
2839 .flex_shrink_0()
2840 .children(spinner)
2841 .when_some(branch, |this, branch| {
2842 let focus_handle = Some(self.focus_handle(cx));
2843
2844 this.children(render_remote_button(
2845 "remote-button",
2846 &branch,
2847 focus_handle,
2848 true,
2849 ))
2850 })
2851 .into_any_element(),
2852 )
2853 }
2854
2855 pub fn render_footer(
2856 &self,
2857 window: &mut Window,
2858 cx: &mut Context<Self>,
2859 ) -> Option<impl IntoElement> {
2860 let active_repository = self.active_repository.clone()?;
2861 let (can_commit, tooltip) = self.configure_commit_button(cx);
2862 let project = self.project.clone().read(cx);
2863 let panel_editor_style = panel_editor_style(true, window, cx);
2864
2865 let enable_coauthors = self.render_co_authors(cx);
2866 let title = self.commit_button_title();
2867
2868 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2869 let commit_tooltip_focus_handle = editor_focus_handle.clone();
2870 let expand_tooltip_focus_handle = editor_focus_handle.clone();
2871
2872 let branch = active_repository.read(cx).current_branch().cloned();
2873
2874 let footer_size = px(32.);
2875 let gap = px(9.0);
2876 let max_height = panel_editor_style
2877 .text
2878 .line_height_in_pixels(window.rem_size())
2879 * MAX_PANEL_EDITOR_LINES
2880 + gap;
2881
2882 let git_panel = cx.entity().clone();
2883 let display_name = SharedString::from(Arc::from(
2884 active_repository
2885 .read(cx)
2886 .display_name(project, cx)
2887 .trim_end_matches("/"),
2888 ));
2889 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2890 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
2891 });
2892
2893 let footer = v_flex()
2894 .child(PanelRepoFooter::new(display_name, branch, Some(git_panel)))
2895 .child(
2896 panel_editor_container(window, cx)
2897 .id("commit-editor-container")
2898 .relative()
2899 .w_full()
2900 .h(max_height + footer_size)
2901 .border_t_1()
2902 .border_color(cx.theme().colors().border_variant)
2903 .cursor_text()
2904 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2905 window.focus(&this.commit_editor.focus_handle(cx));
2906 }))
2907 .child(
2908 h_flex()
2909 .id("commit-footer")
2910 .border_t_1()
2911 .when(editor_is_long, |el| {
2912 el.border_color(cx.theme().colors().border_variant)
2913 })
2914 .absolute()
2915 .bottom_0()
2916 .left_0()
2917 .w_full()
2918 .px_2()
2919 .h(footer_size)
2920 .flex_none()
2921 .justify_between()
2922 .child(
2923 self.render_generate_commit_message_button(cx)
2924 .unwrap_or_else(|| div().into_any_element()),
2925 )
2926 .child(
2927 h_flex().gap_0p5().children(enable_coauthors).child(
2928 panel_filled_button(title)
2929 .tooltip(move |window, cx| {
2930 if can_commit {
2931 Tooltip::for_action_in(
2932 tooltip,
2933 &Commit,
2934 &commit_tooltip_focus_handle,
2935 window,
2936 cx,
2937 )
2938 } else {
2939 Tooltip::simple(tooltip, cx)
2940 }
2941 })
2942 .disabled(!can_commit || self.modal_open)
2943 .on_click({
2944 cx.listener(move |this, _: &ClickEvent, window, cx| {
2945 this.commit_changes(window, cx)
2946 })
2947 }),
2948 ),
2949 ),
2950 )
2951 .child(
2952 div()
2953 .pr_2p5()
2954 .on_action(|&editor::actions::MoveUp, _, cx| {
2955 cx.stop_propagation();
2956 })
2957 .on_action(|&editor::actions::MoveDown, _, cx| {
2958 cx.stop_propagation();
2959 })
2960 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2961 )
2962 .child(
2963 h_flex()
2964 .absolute()
2965 .top_2()
2966 .right_2()
2967 .opacity(0.5)
2968 .hover(|this| this.opacity(1.0))
2969 .child(
2970 panel_icon_button("expand-commit-editor", IconName::Maximize)
2971 .icon_size(IconSize::Small)
2972 .size(ui::ButtonSize::Default)
2973 .tooltip(move |window, cx| {
2974 Tooltip::for_action_in(
2975 "Open Commit Modal",
2976 &git::ExpandCommitEditor,
2977 &expand_tooltip_focus_handle,
2978 window,
2979 cx,
2980 )
2981 })
2982 .on_click(cx.listener({
2983 move |_, _, window, cx| {
2984 window.dispatch_action(
2985 git::ExpandCommitEditor.boxed_clone(),
2986 cx,
2987 )
2988 }
2989 })),
2990 ),
2991 ),
2992 );
2993
2994 Some(footer)
2995 }
2996
2997 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2998 let active_repository = self.active_repository.as_ref()?;
2999 let branch = active_repository.read(cx).current_branch()?;
3000 let commit = branch.most_recent_commit.as_ref()?.clone();
3001
3002 let this = cx.entity();
3003 Some(
3004 h_flex()
3005 .items_center()
3006 .py_2()
3007 .px(px(8.))
3008 .border_color(cx.theme().colors().border)
3009 .gap_1p5()
3010 .child(
3011 div()
3012 .flex_grow()
3013 .overflow_hidden()
3014 .items_center()
3015 .max_w(relative(0.85))
3016 .h_full()
3017 .child(
3018 Label::new(commit.subject.clone())
3019 .size(LabelSize::Small)
3020 .truncate(),
3021 )
3022 .id("commit-msg-hover")
3023 .hoverable_tooltip(move |window, cx| {
3024 GitPanelMessageTooltip::new(
3025 this.clone(),
3026 commit.sha.clone(),
3027 window,
3028 cx,
3029 )
3030 .into()
3031 }),
3032 )
3033 .child(div().flex_1())
3034 .when(commit.has_parent, |this| {
3035 let has_unstaged = self.has_unstaged_changes();
3036 this.child(
3037 panel_icon_button("undo", IconName::Undo)
3038 .icon_size(IconSize::Small)
3039 .icon_color(Color::Muted)
3040 .tooltip(move |window, cx| {
3041 Tooltip::with_meta(
3042 "Uncommit",
3043 Some(&git::Uncommit),
3044 if has_unstaged {
3045 "git reset HEAD^ --soft"
3046 } else {
3047 "git reset HEAD^"
3048 },
3049 window,
3050 cx,
3051 )
3052 })
3053 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3054 )
3055 }),
3056 )
3057 }
3058
3059 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3060 h_flex()
3061 .h_full()
3062 .flex_grow()
3063 .justify_center()
3064 .items_center()
3065 .child(
3066 v_flex()
3067 .gap_2()
3068 .child(h_flex().w_full().justify_around().child(
3069 if self.active_repository.is_some() {
3070 "No changes to commit"
3071 } else {
3072 "No Git repositories"
3073 },
3074 ))
3075 .children({
3076 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3077 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3078 h_flex().w_full().justify_around().child(
3079 panel_filled_button("Initialize Repository")
3080 .tooltip(Tooltip::for_action_title_in(
3081 "git init",
3082 &git::Init,
3083 &self.focus_handle,
3084 ))
3085 .on_click(move |_, _, cx| {
3086 cx.defer(move |cx| {
3087 cx.dispatch_action(&git::Init);
3088 })
3089 }),
3090 )
3091 })
3092 })
3093 .text_ui_sm(cx)
3094 .mx_auto()
3095 .text_color(Color::Placeholder.color(cx)),
3096 )
3097 }
3098
3099 fn render_vertical_scrollbar(
3100 &self,
3101 show_horizontal_scrollbar_container: bool,
3102 cx: &mut Context<Self>,
3103 ) -> impl IntoElement {
3104 div()
3105 .id("git-panel-vertical-scroll")
3106 .occlude()
3107 .flex_none()
3108 .h_full()
3109 .cursor_default()
3110 .absolute()
3111 .right_0()
3112 .top_0()
3113 .bottom_0()
3114 .w(px(12.))
3115 .when(show_horizontal_scrollbar_container, |this| {
3116 this.pb_neg_3p5()
3117 })
3118 .on_mouse_move(cx.listener(|_, _, _, cx| {
3119 cx.notify();
3120 cx.stop_propagation()
3121 }))
3122 .on_hover(|_, _, cx| {
3123 cx.stop_propagation();
3124 })
3125 .on_any_mouse_down(|_, _, cx| {
3126 cx.stop_propagation();
3127 })
3128 .on_mouse_up(
3129 MouseButton::Left,
3130 cx.listener(|this, _, window, cx| {
3131 if !this.vertical_scrollbar.state.is_dragging()
3132 && !this.focus_handle.contains_focused(window, cx)
3133 {
3134 this.vertical_scrollbar.hide(window, cx);
3135 cx.notify();
3136 }
3137
3138 cx.stop_propagation();
3139 }),
3140 )
3141 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3142 cx.notify();
3143 }))
3144 .children(Scrollbar::vertical(
3145 // percentage as f32..end_offset as f32,
3146 self.vertical_scrollbar.state.clone(),
3147 ))
3148 }
3149
3150 /// Renders the horizontal scrollbar.
3151 ///
3152 /// The right offset is used to determine how far to the right the
3153 /// scrollbar should extend to, useful for ensuring it doesn't collide
3154 /// with the vertical scrollbar when visible.
3155 fn render_horizontal_scrollbar(
3156 &self,
3157 right_offset: Pixels,
3158 cx: &mut Context<Self>,
3159 ) -> impl IntoElement {
3160 div()
3161 .id("git-panel-horizontal-scroll")
3162 .occlude()
3163 .flex_none()
3164 .w_full()
3165 .cursor_default()
3166 .absolute()
3167 .bottom_neg_px()
3168 .left_0()
3169 .right_0()
3170 .pr(right_offset)
3171 .on_mouse_move(cx.listener(|_, _, _, cx| {
3172 cx.notify();
3173 cx.stop_propagation()
3174 }))
3175 .on_hover(|_, _, cx| {
3176 cx.stop_propagation();
3177 })
3178 .on_any_mouse_down(|_, _, cx| {
3179 cx.stop_propagation();
3180 })
3181 .on_mouse_up(
3182 MouseButton::Left,
3183 cx.listener(|this, _, window, cx| {
3184 if !this.horizontal_scrollbar.state.is_dragging()
3185 && !this.focus_handle.contains_focused(window, cx)
3186 {
3187 this.horizontal_scrollbar.hide(window, cx);
3188 cx.notify();
3189 }
3190
3191 cx.stop_propagation();
3192 }),
3193 )
3194 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3195 cx.notify();
3196 }))
3197 .children(Scrollbar::horizontal(
3198 // percentage as f32..end_offset as f32,
3199 self.horizontal_scrollbar.state.clone(),
3200 ))
3201 }
3202
3203 fn render_buffer_header_controls(
3204 &self,
3205 entity: &Entity<Self>,
3206 file: &Arc<dyn File>,
3207 _: &Window,
3208 cx: &App,
3209 ) -> Option<AnyElement> {
3210 let repo = self.active_repository.as_ref()?.read(cx);
3211 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
3212 let ix = self.entry_by_path(&repo_path)?;
3213 let entry = self.entries.get(ix)?;
3214
3215 let entry_staging = self.entry_staging(entry.status_entry()?);
3216
3217 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3218 .disabled(!self.has_write_access(cx))
3219 .fill()
3220 .elevation(ElevationIndex::Surface)
3221 .on_click({
3222 let entry = entry.clone();
3223 let git_panel = entity.downgrade();
3224 move |_, window, cx| {
3225 git_panel
3226 .update(cx, |this, cx| {
3227 this.toggle_staged_for_entry(&entry, window, cx);
3228 cx.stop_propagation();
3229 })
3230 .ok();
3231 }
3232 });
3233 Some(
3234 h_flex()
3235 .id("start-slot")
3236 .text_lg()
3237 .child(checkbox)
3238 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3239 // prevent the list item active state triggering when toggling checkbox
3240 cx.stop_propagation();
3241 })
3242 .into_any_element(),
3243 )
3244 }
3245
3246 fn render_entries(
3247 &self,
3248 has_write_access: bool,
3249 _: &Window,
3250 cx: &mut Context<Self>,
3251 ) -> impl IntoElement {
3252 let entry_count = self.entries.len();
3253
3254 let scroll_track_size = px(16.);
3255
3256 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3257 // magic number
3258 px(3.)
3259 } else {
3260 px(0.)
3261 };
3262
3263 v_flex()
3264 .flex_1()
3265 .size_full()
3266 .overflow_hidden()
3267 .relative()
3268 // Show a border on the top and bottom of the container when
3269 // the vertical scrollbar container is visible so we don't have a
3270 // floating left border in the panel.
3271 .when(self.vertical_scrollbar.show_track, |this| {
3272 this.border_t_1()
3273 .border_b_1()
3274 .border_color(cx.theme().colors().border)
3275 })
3276 .child(
3277 h_flex()
3278 .flex_1()
3279 .size_full()
3280 .relative()
3281 .overflow_hidden()
3282 .child(
3283 uniform_list(cx.entity().clone(), "entries", entry_count, {
3284 move |this, range, window, cx| {
3285 let mut items = Vec::with_capacity(range.end - range.start);
3286
3287 for ix in range {
3288 match &this.entries.get(ix) {
3289 Some(GitListEntry::GitStatusEntry(entry)) => {
3290 items.push(this.render_entry(
3291 ix,
3292 entry,
3293 has_write_access,
3294 window,
3295 cx,
3296 ));
3297 }
3298 Some(GitListEntry::Header(header)) => {
3299 items.push(this.render_list_header(
3300 ix,
3301 header,
3302 has_write_access,
3303 window,
3304 cx,
3305 ));
3306 }
3307 None => {}
3308 }
3309 }
3310
3311 items
3312 }
3313 })
3314 .size_full()
3315 .flex_grow()
3316 .with_sizing_behavior(ListSizingBehavior::Auto)
3317 .with_horizontal_sizing_behavior(
3318 ListHorizontalSizingBehavior::Unconstrained,
3319 )
3320 .with_width_from_item(self.max_width_item_index)
3321 .track_scroll(self.scroll_handle.clone()),
3322 )
3323 .on_mouse_down(
3324 MouseButton::Right,
3325 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3326 this.deploy_panel_context_menu(event.position, window, cx)
3327 }),
3328 )
3329 .when(self.vertical_scrollbar.show_track, |this| {
3330 this.child(
3331 v_flex()
3332 .h_full()
3333 .flex_none()
3334 .w(scroll_track_size)
3335 .bg(cx.theme().colors().panel_background)
3336 .child(
3337 div()
3338 .size_full()
3339 .flex_1()
3340 .border_l_1()
3341 .border_color(cx.theme().colors().border),
3342 ),
3343 )
3344 })
3345 .when(self.vertical_scrollbar.show_scrollbar, |this| {
3346 this.child(
3347 self.render_vertical_scrollbar(
3348 self.horizontal_scrollbar.show_track,
3349 cx,
3350 ),
3351 )
3352 }),
3353 )
3354 .when(self.horizontal_scrollbar.show_track, |this| {
3355 this.child(
3356 h_flex()
3357 .w_full()
3358 .h(scroll_track_size)
3359 .flex_none()
3360 .relative()
3361 .child(
3362 div()
3363 .w_full()
3364 .flex_1()
3365 // for some reason the horizontal scrollbar is 1px
3366 // taller than the vertical scrollbar??
3367 .h(scroll_track_size - px(1.))
3368 .bg(cx.theme().colors().panel_background)
3369 .border_t_1()
3370 .border_color(cx.theme().colors().border),
3371 )
3372 .when(self.vertical_scrollbar.show_track, |this| {
3373 this.child(
3374 div()
3375 .flex_none()
3376 // -1px prevents a missing pixel between the two container borders
3377 .w(scroll_track_size - px(1.))
3378 .h_full(),
3379 )
3380 .child(
3381 // HACK: Fill the missing 1px 🥲
3382 div()
3383 .absolute()
3384 .right(scroll_track_size - px(1.))
3385 .bottom(scroll_track_size - px(1.))
3386 .size_px()
3387 .bg(cx.theme().colors().border),
3388 )
3389 }),
3390 )
3391 })
3392 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3393 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3394 })
3395 }
3396
3397 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3398 Label::new(label.into()).color(color).single_line()
3399 }
3400
3401 fn list_item_height(&self) -> Rems {
3402 rems(1.75)
3403 }
3404
3405 fn render_list_header(
3406 &self,
3407 ix: usize,
3408 header: &GitHeaderEntry,
3409 _: bool,
3410 _: &Window,
3411 _: &Context<Self>,
3412 ) -> AnyElement {
3413 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3414
3415 h_flex()
3416 .id(id)
3417 .h(self.list_item_height())
3418 .w_full()
3419 .items_end()
3420 .px(rems(0.75)) // ~12px
3421 .pb(rems(0.3125)) // ~ 5px
3422 .child(
3423 Label::new(header.title())
3424 .color(Color::Muted)
3425 .size(LabelSize::Small)
3426 .line_height_style(LineHeightStyle::UiLabel)
3427 .single_line(),
3428 )
3429 .into_any_element()
3430 }
3431
3432 fn load_commit_details(
3433 &self,
3434 sha: String,
3435 cx: &mut Context<Self>,
3436 ) -> Task<anyhow::Result<CommitDetails>> {
3437 let Some(repo) = self.active_repository.clone() else {
3438 return Task::ready(Err(anyhow::anyhow!("no active repo")));
3439 };
3440 repo.update(cx, |repo, cx| {
3441 let show = repo.show(sha);
3442 cx.spawn(|_, _| async move { show.await? })
3443 })
3444 }
3445
3446 fn deploy_entry_context_menu(
3447 &mut self,
3448 position: Point<Pixels>,
3449 ix: usize,
3450 window: &mut Window,
3451 cx: &mut Context<Self>,
3452 ) {
3453 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3454 return;
3455 };
3456 let stage_title = if entry.status.staging().is_fully_staged() {
3457 "Unstage File"
3458 } else {
3459 "Stage File"
3460 };
3461 let restore_title = if entry.status.is_created() {
3462 "Trash File"
3463 } else {
3464 "Restore File"
3465 };
3466 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3467 context_menu
3468 .context(self.focus_handle.clone())
3469 .action(stage_title, ToggleStaged.boxed_clone())
3470 .action(restore_title, git::RestoreFile.boxed_clone())
3471 .separator()
3472 .action("Open Diff", Confirm.boxed_clone())
3473 .action("Open File", SecondaryConfirm.boxed_clone())
3474 });
3475 self.selected_entry = Some(ix);
3476 self.set_context_menu(context_menu, position, window, cx);
3477 }
3478
3479 fn deploy_panel_context_menu(
3480 &mut self,
3481 position: Point<Pixels>,
3482 window: &mut Window,
3483 cx: &mut Context<Self>,
3484 ) {
3485 let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3486 self.set_context_menu(context_menu, position, window, cx);
3487 }
3488
3489 fn set_context_menu(
3490 &mut self,
3491 context_menu: Entity<ContextMenu>,
3492 position: Point<Pixels>,
3493 window: &Window,
3494 cx: &mut Context<Self>,
3495 ) {
3496 let subscription = cx.subscribe_in(
3497 &context_menu,
3498 window,
3499 |this, _, _: &DismissEvent, window, cx| {
3500 if this.context_menu.as_ref().is_some_and(|context_menu| {
3501 context_menu.0.focus_handle(cx).contains_focused(window, cx)
3502 }) {
3503 cx.focus_self(window);
3504 }
3505 this.context_menu.take();
3506 cx.notify();
3507 },
3508 );
3509 self.context_menu = Some((context_menu, position, subscription));
3510 cx.notify();
3511 }
3512
3513 fn render_entry(
3514 &self,
3515 ix: usize,
3516 entry: &GitStatusEntry,
3517 has_write_access: bool,
3518 window: &Window,
3519 cx: &Context<Self>,
3520 ) -> AnyElement {
3521 let display_name = entry.display_name();
3522
3523 let selected = self.selected_entry == Some(ix);
3524 let marked = self.marked_entries.contains(&ix);
3525 let status_style = GitPanelSettings::get_global(cx).status_style;
3526 let status = entry.status;
3527 let modifiers = self.current_modifiers;
3528 let shift_held = modifiers.shift;
3529
3530 let has_conflict = status.is_conflicted();
3531 let is_modified = status.is_modified();
3532 let is_deleted = status.is_deleted();
3533
3534 let label_color = if status_style == StatusStyle::LabelColor {
3535 if has_conflict {
3536 Color::Conflict
3537 } else if is_modified {
3538 Color::Modified
3539 } else if is_deleted {
3540 // We don't want a bunch of red labels in the list
3541 Color::Disabled
3542 } else {
3543 Color::Created
3544 }
3545 } else {
3546 Color::Default
3547 };
3548
3549 let path_color = if status.is_deleted() {
3550 Color::Disabled
3551 } else {
3552 Color::Muted
3553 };
3554
3555 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3556 let checkbox_wrapper_id: ElementId =
3557 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3558 let checkbox_id: ElementId =
3559 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3560
3561 let entry_staging = self.entry_staging(entry);
3562 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3563
3564 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3565 is_staged = ToggleState::Selected;
3566 }
3567
3568 let handle = cx.weak_entity();
3569
3570 let selected_bg_alpha = 0.08;
3571 let marked_bg_alpha = 0.12;
3572 let state_opacity_step = 0.04;
3573
3574 let base_bg = match (selected, marked) {
3575 (true, true) => cx
3576 .theme()
3577 .status()
3578 .info
3579 .alpha(selected_bg_alpha + marked_bg_alpha),
3580 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3581 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3582 _ => cx.theme().colors().ghost_element_background,
3583 };
3584
3585 let hover_bg = if selected {
3586 cx.theme()
3587 .status()
3588 .info
3589 .alpha(selected_bg_alpha + state_opacity_step)
3590 } else {
3591 cx.theme().colors().ghost_element_hover
3592 };
3593
3594 let active_bg = if selected {
3595 cx.theme()
3596 .status()
3597 .info
3598 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3599 } else {
3600 cx.theme().colors().ghost_element_active
3601 };
3602
3603 h_flex()
3604 .id(id)
3605 .h(self.list_item_height())
3606 .w_full()
3607 .items_center()
3608 .border_1()
3609 .when(selected && self.focus_handle.is_focused(window), |el| {
3610 el.border_color(cx.theme().colors().border_focused)
3611 })
3612 .px(rems(0.75)) // ~12px
3613 .overflow_hidden()
3614 .flex_none()
3615 .gap_1p5()
3616 .bg(base_bg)
3617 .hover(|this| this.bg(hover_bg))
3618 .active(|this| this.bg(active_bg))
3619 .on_click({
3620 cx.listener(move |this, event: &ClickEvent, window, cx| {
3621 this.selected_entry = Some(ix);
3622 cx.notify();
3623 if event.modifiers().secondary() {
3624 this.open_file(&Default::default(), window, cx)
3625 } else {
3626 this.open_diff(&Default::default(), window, cx);
3627 this.focus_handle.focus(window);
3628 }
3629 })
3630 })
3631 .on_mouse_down(
3632 MouseButton::Right,
3633 move |event: &MouseDownEvent, window, cx| {
3634 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3635 if event.button != MouseButton::Right {
3636 return;
3637 }
3638
3639 let Some(this) = handle.upgrade() else {
3640 return;
3641 };
3642 this.update(cx, |this, cx| {
3643 this.deploy_entry_context_menu(event.position, ix, window, cx);
3644 });
3645 cx.stop_propagation();
3646 },
3647 )
3648 // .on_secondary_mouse_down(cx.listener(
3649 // move |this, event: &MouseDownEvent, window, cx| {
3650 // this.deploy_entry_context_menu(event.position, ix, window, cx);
3651 // cx.stop_propagation();
3652 // },
3653 // ))
3654 .child(
3655 div()
3656 .id(checkbox_wrapper_id)
3657 .flex_none()
3658 .occlude()
3659 .cursor_pointer()
3660 .child(
3661 Checkbox::new(checkbox_id, is_staged)
3662 .disabled(!has_write_access)
3663 .fill()
3664 .placeholder(
3665 !self.has_staged_changes()
3666 && !self.has_conflicts()
3667 && !entry.status.is_created(),
3668 )
3669 .elevation(ElevationIndex::Surface)
3670 .on_click({
3671 let entry = entry.clone();
3672 cx.listener(move |this, _, window, cx| {
3673 if !has_write_access {
3674 return;
3675 }
3676 this.toggle_staged_for_entry(
3677 &GitListEntry::GitStatusEntry(entry.clone()),
3678 window,
3679 cx,
3680 );
3681 cx.stop_propagation();
3682 })
3683 })
3684 .tooltip(move |window, cx| {
3685 let is_staged = entry_staging.is_fully_staged();
3686
3687 let action = if is_staged { "Unstage" } else { "Stage" };
3688 let tooltip_name = if shift_held {
3689 format!("{} section", action)
3690 } else {
3691 action.to_string()
3692 };
3693
3694 let meta = if shift_held {
3695 format!(
3696 "Release shift to {} single entry",
3697 action.to_lowercase()
3698 )
3699 } else {
3700 format!("Shift click to {} section", action.to_lowercase())
3701 };
3702
3703 Tooltip::with_meta(
3704 tooltip_name,
3705 Some(&ToggleStaged),
3706 meta,
3707 window,
3708 cx,
3709 )
3710 }),
3711 ),
3712 )
3713 .child(git_status_icon(status))
3714 .child(
3715 h_flex()
3716 .items_center()
3717 .flex_1()
3718 // .overflow_hidden()
3719 .when_some(entry.parent_dir(), |this, parent| {
3720 if !parent.is_empty() {
3721 this.child(
3722 self.entry_label(format!("{}/", parent), path_color)
3723 .when(status.is_deleted(), |this| this.strikethrough()),
3724 )
3725 } else {
3726 this
3727 }
3728 })
3729 .child(
3730 self.entry_label(display_name.clone(), label_color)
3731 .when(status.is_deleted(), |this| this.strikethrough()),
3732 ),
3733 )
3734 .into_any_element()
3735 }
3736
3737 fn has_write_access(&self, cx: &App) -> bool {
3738 !self.project.read(cx).is_read_only(cx)
3739 }
3740}
3741
3742fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3743 assistant_settings::AssistantSettings::get_global(cx)
3744 .enabled
3745 .then(|| {
3746 let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3747 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3748 provider.is_authenticated(cx).then(|| model)
3749 })
3750 .flatten()
3751}
3752
3753impl Render for GitPanel {
3754 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3755 let project = self.project.read(cx);
3756 let has_entries = self.entries.len() > 0;
3757 let room = self
3758 .workspace
3759 .upgrade()
3760 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3761
3762 let has_write_access = self.has_write_access(cx);
3763
3764 let has_co_authors = room.map_or(false, |room| {
3765 room.read(cx)
3766 .remote_participants()
3767 .values()
3768 .any(|remote_participant| remote_participant.can_write())
3769 });
3770
3771 v_flex()
3772 .id("git_panel")
3773 .key_context(self.dispatch_context(window, cx))
3774 .track_focus(&self.focus_handle)
3775 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3776 .when(has_write_access && !project.is_read_only(cx), |this| {
3777 this.on_action(cx.listener(Self::toggle_staged_for_selected))
3778 .on_action(cx.listener(GitPanel::commit))
3779 .on_action(cx.listener(Self::stage_all))
3780 .on_action(cx.listener(Self::unstage_all))
3781 .on_action(cx.listener(Self::stage_selected))
3782 .on_action(cx.listener(Self::unstage_selected))
3783 .on_action(cx.listener(Self::restore_tracked_files))
3784 .on_action(cx.listener(Self::revert_selected))
3785 .on_action(cx.listener(Self::clean_all))
3786 .on_action(cx.listener(Self::generate_commit_message_action))
3787 })
3788 .on_action(cx.listener(Self::select_first))
3789 .on_action(cx.listener(Self::select_next))
3790 .on_action(cx.listener(Self::select_previous))
3791 .on_action(cx.listener(Self::select_last))
3792 .on_action(cx.listener(Self::close_panel))
3793 .on_action(cx.listener(Self::open_diff))
3794 .on_action(cx.listener(Self::open_file))
3795 .on_action(cx.listener(Self::focus_changes_list))
3796 .on_action(cx.listener(Self::focus_editor))
3797 .on_action(cx.listener(Self::expand_commit_editor))
3798 .when(has_write_access && has_co_authors, |git_panel| {
3799 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3800 })
3801 .on_hover(cx.listener(move |this, hovered, window, cx| {
3802 if *hovered {
3803 this.horizontal_scrollbar.show(cx);
3804 this.vertical_scrollbar.show(cx);
3805 cx.notify();
3806 } else if !this.focus_handle.contains_focused(window, cx) {
3807 this.hide_scrollbars(window, cx);
3808 }
3809 }))
3810 .size_full()
3811 .overflow_hidden()
3812 .bg(ElevationIndex::Surface.bg(cx))
3813 .child(
3814 v_flex()
3815 .size_full()
3816 .children(self.render_panel_header(window, cx))
3817 .map(|this| {
3818 if has_entries {
3819 this.child(self.render_entries(has_write_access, window, cx))
3820 } else {
3821 this.child(self.render_empty_state(cx).into_any_element())
3822 }
3823 })
3824 .children(self.render_footer(window, cx))
3825 .children(self.render_previous_commit(cx))
3826 .into_any_element(),
3827 )
3828 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3829 deferred(
3830 anchored()
3831 .position(*position)
3832 .anchor(gpui::Corner::TopLeft)
3833 .child(menu.clone()),
3834 )
3835 .with_priority(1)
3836 }))
3837 }
3838}
3839
3840impl Focusable for GitPanel {
3841 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3842 if self.entries.is_empty() {
3843 self.commit_editor.focus_handle(cx)
3844 } else {
3845 self.focus_handle.clone()
3846 }
3847 }
3848}
3849
3850impl EventEmitter<Event> for GitPanel {}
3851
3852impl EventEmitter<PanelEvent> for GitPanel {}
3853
3854pub(crate) struct GitPanelAddon {
3855 pub(crate) workspace: WeakEntity<Workspace>,
3856}
3857
3858impl editor::Addon for GitPanelAddon {
3859 fn to_any(&self) -> &dyn std::any::Any {
3860 self
3861 }
3862
3863 fn render_buffer_header_controls(
3864 &self,
3865 excerpt_info: &ExcerptInfo,
3866 window: &Window,
3867 cx: &App,
3868 ) -> Option<AnyElement> {
3869 let file = excerpt_info.buffer.file()?;
3870 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3871
3872 git_panel
3873 .read(cx)
3874 .render_buffer_header_controls(&git_panel, &file, window, cx)
3875 }
3876}
3877
3878impl Panel for GitPanel {
3879 fn persistent_name() -> &'static str {
3880 "GitPanel"
3881 }
3882
3883 fn position(&self, _: &Window, cx: &App) -> DockPosition {
3884 GitPanelSettings::get_global(cx).dock
3885 }
3886
3887 fn position_is_valid(&self, position: DockPosition) -> bool {
3888 matches!(position, DockPosition::Left | DockPosition::Right)
3889 }
3890
3891 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3892 settings::update_settings_file::<GitPanelSettings>(
3893 self.fs.clone(),
3894 cx,
3895 move |settings, _| settings.dock = Some(position),
3896 );
3897 }
3898
3899 fn size(&self, _: &Window, cx: &App) -> Pixels {
3900 self.width
3901 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3902 }
3903
3904 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3905 self.width = size;
3906 self.serialize(cx);
3907 cx.notify();
3908 }
3909
3910 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3911 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3912 }
3913
3914 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3915 Some("Git Panel")
3916 }
3917
3918 fn toggle_action(&self) -> Box<dyn Action> {
3919 Box::new(ToggleFocus)
3920 }
3921
3922 fn activation_priority(&self) -> u32 {
3923 2
3924 }
3925}
3926
3927impl PanelHeader for GitPanel {}
3928
3929struct GitPanelMessageTooltip {
3930 commit_tooltip: Option<Entity<CommitTooltip>>,
3931}
3932
3933impl GitPanelMessageTooltip {
3934 fn new(
3935 git_panel: Entity<GitPanel>,
3936 sha: SharedString,
3937 window: &mut Window,
3938 cx: &mut App,
3939 ) -> Entity<Self> {
3940 cx.new(|cx| {
3941 cx.spawn_in(window, |this, mut cx| async move {
3942 let details = git_panel
3943 .update(&mut cx, |git_panel, cx| {
3944 git_panel.load_commit_details(sha.to_string(), cx)
3945 })?
3946 .await?;
3947
3948 let commit_details = editor::commit_tooltip::CommitDetails {
3949 sha: details.sha.clone(),
3950 committer_name: details.committer_name.clone(),
3951 committer_email: details.committer_email.clone(),
3952 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3953 message: Some(editor::commit_tooltip::ParsedCommitMessage {
3954 message: details.message.clone(),
3955 ..Default::default()
3956 }),
3957 };
3958
3959 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3960 this.commit_tooltip =
3961 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3962 cx.notify();
3963 })
3964 })
3965 .detach();
3966
3967 Self {
3968 commit_tooltip: None,
3969 }
3970 })
3971 }
3972}
3973
3974impl Render for GitPanelMessageTooltip {
3975 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3976 if let Some(commit_tooltip) = &self.commit_tooltip {
3977 commit_tooltip.clone().into_any_element()
3978 } else {
3979 gpui::Empty.into_any_element()
3980 }
3981 }
3982}
3983
3984#[derive(IntoElement, IntoComponent)]
3985#[component(scope = "Version Control")]
3986pub struct PanelRepoFooter {
3987 active_repository: SharedString,
3988 branch: Option<Branch>,
3989 // Getting a GitPanel in previews will be difficult.
3990 //
3991 // For now just take an option here, and we won't bind handlers to buttons in previews.
3992 git_panel: Option<Entity<GitPanel>>,
3993}
3994
3995impl PanelRepoFooter {
3996 pub fn new(
3997 active_repository: SharedString,
3998 branch: Option<Branch>,
3999 git_panel: Option<Entity<GitPanel>>,
4000 ) -> Self {
4001 Self {
4002 active_repository,
4003 branch,
4004 git_panel,
4005 }
4006 }
4007
4008 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4009 Self {
4010 active_repository,
4011 branch,
4012 git_panel: None,
4013 }
4014 }
4015}
4016
4017impl RenderOnce for PanelRepoFooter {
4018 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4019 let project = self
4020 .git_panel
4021 .as_ref()
4022 .map(|panel| panel.read(cx).project.clone());
4023
4024 let repo = self
4025 .git_panel
4026 .as_ref()
4027 .and_then(|panel| panel.read(cx).active_repository.clone());
4028
4029 let single_repo = project
4030 .as_ref()
4031 .map(|project| {
4032 filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
4033 })
4034 .unwrap_or(true);
4035
4036 const MAX_BRANCH_LEN: usize = 16;
4037 const MAX_REPO_LEN: usize = 16;
4038 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4039
4040 let branch = self.branch.clone();
4041 let branch_name = branch
4042 .as_ref()
4043 .map_or(" (no branch)".into(), |branch| branch.name.clone());
4044 let active_repo_name = self.active_repository.clone();
4045
4046 let branch_actual_len = branch_name.len();
4047 let repo_actual_len = active_repo_name.len();
4048
4049 // ideally, show the whole branch and repo names but
4050 // when we can't, use a budget to allocate space between the two
4051 let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4052 <= LABEL_CHARACTER_BUDGET
4053 {
4054 (repo_actual_len, branch_actual_len)
4055 } else {
4056 if branch_actual_len <= MAX_BRANCH_LEN {
4057 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4058 (repo_space, branch_actual_len)
4059 } else if repo_actual_len <= MAX_REPO_LEN {
4060 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4061 (repo_actual_len, branch_space)
4062 } else {
4063 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4064 }
4065 };
4066
4067 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4068 active_repo_name.to_string()
4069 } else {
4070 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4071 };
4072
4073 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4074 branch_name.to_string()
4075 } else {
4076 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4077 };
4078
4079 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4080 .style(ButtonStyle::Transparent)
4081 .size(ButtonSize::None)
4082 .label_size(LabelSize::Small)
4083 .color(Color::Muted);
4084
4085 let repo_selector = PopoverMenu::new("repository-switcher")
4086 .menu({
4087 let project = project.clone();
4088 move |window, cx| {
4089 let project = project.clone()?;
4090 Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
4091 }
4092 })
4093 .trigger_with_tooltip(
4094 repo_selector_trigger.disabled(single_repo).truncate(true),
4095 Tooltip::text("Switch active repository"),
4096 )
4097 .attach(gpui::Corner::BottomLeft)
4098 .into_any_element();
4099
4100 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4101 .style(ButtonStyle::Transparent)
4102 .size(ButtonSize::None)
4103 .label_size(LabelSize::Small)
4104 .truncate(true)
4105 .tooltip(Tooltip::for_action_title(
4106 "Switch Branch",
4107 &zed_actions::git::Branch,
4108 ))
4109 .on_click(|_, window, cx| {
4110 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
4111 });
4112
4113 let branch_selector = PopoverMenu::new("popover-button")
4114 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4115 .trigger_with_tooltip(
4116 branch_selector_button,
4117 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
4118 )
4119 .anchor(Corner::TopLeft)
4120 .offset(gpui::Point {
4121 x: px(0.0),
4122 y: px(-2.0),
4123 });
4124
4125 h_flex()
4126 .w_full()
4127 .px_2()
4128 .h(px(36.))
4129 .items_center()
4130 .justify_between()
4131 .gap_1()
4132 .child(
4133 h_flex()
4134 .flex_1()
4135 .overflow_hidden()
4136 .items_center()
4137 .child(
4138 div().child(
4139 Icon::new(IconName::GitBranchSmall)
4140 .size(IconSize::Small)
4141 .color(if single_repo {
4142 Color::Disabled
4143 } else {
4144 Color::Muted
4145 }),
4146 ),
4147 )
4148 .child(repo_selector)
4149 .when_some(branch.clone(), |this, _| {
4150 this.child(
4151 div()
4152 .text_color(cx.theme().colors().text_muted)
4153 .text_sm()
4154 .child("/"),
4155 )
4156 })
4157 .child(branch_selector),
4158 )
4159 .children(if let Some(git_panel) = self.git_panel {
4160 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4161 } else {
4162 None
4163 })
4164 }
4165}
4166
4167impl ComponentPreview for PanelRepoFooter {
4168 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
4169 let unknown_upstream = None;
4170 let no_remote_upstream = Some(UpstreamTracking::Gone);
4171 let ahead_of_upstream = Some(
4172 UpstreamTrackingStatus {
4173 ahead: 2,
4174 behind: 0,
4175 }
4176 .into(),
4177 );
4178 let behind_upstream = Some(
4179 UpstreamTrackingStatus {
4180 ahead: 0,
4181 behind: 2,
4182 }
4183 .into(),
4184 );
4185 let ahead_and_behind_upstream = Some(
4186 UpstreamTrackingStatus {
4187 ahead: 3,
4188 behind: 1,
4189 }
4190 .into(),
4191 );
4192
4193 let not_ahead_or_behind_upstream = Some(
4194 UpstreamTrackingStatus {
4195 ahead: 0,
4196 behind: 0,
4197 }
4198 .into(),
4199 );
4200
4201 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4202 Branch {
4203 is_head: true,
4204 name: "some-branch".into(),
4205 upstream: upstream.map(|tracking| Upstream {
4206 ref_name: "origin/some-branch".into(),
4207 tracking,
4208 }),
4209 most_recent_commit: Some(CommitSummary {
4210 sha: "abc123".into(),
4211 subject: "Modify stuff".into(),
4212 commit_timestamp: 1710932954,
4213 has_parent: true,
4214 }),
4215 }
4216 }
4217
4218 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4219 Branch {
4220 is_head: true,
4221 name: branch_name.to_string().into(),
4222 upstream: upstream.map(|tracking| Upstream {
4223 ref_name: format!("zed/{}", branch_name).into(),
4224 tracking,
4225 }),
4226 most_recent_commit: Some(CommitSummary {
4227 sha: "abc123".into(),
4228 subject: "Modify stuff".into(),
4229 commit_timestamp: 1710932954,
4230 has_parent: true,
4231 }),
4232 }
4233 }
4234
4235 fn active_repository(id: usize) -> SharedString {
4236 format!("repo-{}", id).into()
4237 }
4238
4239 let example_width = px(340.);
4240
4241 v_flex()
4242 .gap_6()
4243 .w_full()
4244 .flex_none()
4245 .children(vec![example_group_with_title(
4246 "Action Button States",
4247 vec![
4248 single_example(
4249 "No Branch",
4250 div()
4251 .w(example_width)
4252 .overflow_hidden()
4253 .child(PanelRepoFooter::new_preview(
4254 active_repository(1).clone(),
4255 None,
4256 ))
4257 .into_any_element(),
4258 )
4259 .grow(),
4260 single_example(
4261 "Remote status unknown",
4262 div()
4263 .w(example_width)
4264 .overflow_hidden()
4265 .child(PanelRepoFooter::new_preview(
4266 active_repository(2).clone(),
4267 Some(branch(unknown_upstream)),
4268 ))
4269 .into_any_element(),
4270 )
4271 .grow(),
4272 single_example(
4273 "No Remote Upstream",
4274 div()
4275 .w(example_width)
4276 .overflow_hidden()
4277 .child(PanelRepoFooter::new_preview(
4278 active_repository(3).clone(),
4279 Some(branch(no_remote_upstream)),
4280 ))
4281 .into_any_element(),
4282 )
4283 .grow(),
4284 single_example(
4285 "Not Ahead or Behind",
4286 div()
4287 .w(example_width)
4288 .overflow_hidden()
4289 .child(PanelRepoFooter::new_preview(
4290 active_repository(4).clone(),
4291 Some(branch(not_ahead_or_behind_upstream)),
4292 ))
4293 .into_any_element(),
4294 )
4295 .grow(),
4296 single_example(
4297 "Behind remote",
4298 div()
4299 .w(example_width)
4300 .overflow_hidden()
4301 .child(PanelRepoFooter::new_preview(
4302 active_repository(5).clone(),
4303 Some(branch(behind_upstream)),
4304 ))
4305 .into_any_element(),
4306 )
4307 .grow(),
4308 single_example(
4309 "Ahead of remote",
4310 div()
4311 .w(example_width)
4312 .overflow_hidden()
4313 .child(PanelRepoFooter::new_preview(
4314 active_repository(6).clone(),
4315 Some(branch(ahead_of_upstream)),
4316 ))
4317 .into_any_element(),
4318 )
4319 .grow(),
4320 single_example(
4321 "Ahead and behind remote",
4322 div()
4323 .w(example_width)
4324 .overflow_hidden()
4325 .child(PanelRepoFooter::new_preview(
4326 active_repository(7).clone(),
4327 Some(branch(ahead_and_behind_upstream)),
4328 ))
4329 .into_any_element(),
4330 )
4331 .grow(),
4332 ],
4333 )
4334 .grow()
4335 .vertical()])
4336 .children(vec![example_group_with_title(
4337 "Labels",
4338 vec![
4339 single_example(
4340 "Short Branch & Repo",
4341 div()
4342 .w(example_width)
4343 .overflow_hidden()
4344 .child(PanelRepoFooter::new_preview(
4345 SharedString::from("zed"),
4346 Some(custom("main", behind_upstream)),
4347 ))
4348 .into_any_element(),
4349 )
4350 .grow(),
4351 single_example(
4352 "Long Branch",
4353 div()
4354 .w(example_width)
4355 .overflow_hidden()
4356 .child(PanelRepoFooter::new_preview(
4357 SharedString::from("zed"),
4358 Some(custom(
4359 "redesign-and-update-git-ui-list-entry-style",
4360 behind_upstream,
4361 )),
4362 ))
4363 .into_any_element(),
4364 )
4365 .grow(),
4366 single_example(
4367 "Long Repo",
4368 div()
4369 .w(example_width)
4370 .overflow_hidden()
4371 .child(PanelRepoFooter::new_preview(
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 SharedString::from("zed-industries-community-examples"),
4385 Some(custom(
4386 "redesign-and-update-git-ui-list-entry-style",
4387 behind_upstream,
4388 )),
4389 ))
4390 .into_any_element(),
4391 )
4392 .grow(),
4393 single_example(
4394 "Uppercase Repo",
4395 div()
4396 .w(example_width)
4397 .overflow_hidden()
4398 .child(PanelRepoFooter::new_preview(
4399 SharedString::from("LICENSES"),
4400 Some(custom("main", ahead_of_upstream)),
4401 ))
4402 .into_any_element(),
4403 )
4404 .grow(),
4405 single_example(
4406 "Uppercase Branch",
4407 div()
4408 .w(example_width)
4409 .overflow_hidden()
4410 .child(PanelRepoFooter::new_preview(
4411 SharedString::from("zed"),
4412 Some(custom("update-README", behind_upstream)),
4413 ))
4414 .into_any_element(),
4415 )
4416 .grow(),
4417 ],
4418 )
4419 .grow()
4420 .vertical()])
4421 .into_any_element()
4422 }
4423}
4424
4425#[cfg(test)]
4426mod tests {
4427 use git::status::StatusCode;
4428 use gpui::TestAppContext;
4429 use project::{FakeFs, WorktreeSettings};
4430 use serde_json::json;
4431 use settings::SettingsStore;
4432 use theme::LoadThemes;
4433 use util::path;
4434
4435 use super::*;
4436
4437 fn init_test(cx: &mut gpui::TestAppContext) {
4438 if std::env::var("RUST_LOG").is_ok() {
4439 env_logger::try_init().ok();
4440 }
4441
4442 cx.update(|cx| {
4443 let settings_store = SettingsStore::test(cx);
4444 cx.set_global(settings_store);
4445 AssistantSettings::register(cx);
4446 WorktreeSettings::register(cx);
4447 workspace::init_settings(cx);
4448 theme::init(LoadThemes::JustBase, cx);
4449 language::init(cx);
4450 editor::init(cx);
4451 Project::init_settings(cx);
4452 crate::init(cx);
4453 });
4454 }
4455
4456 #[gpui::test]
4457 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4458 init_test(cx);
4459 let fs = FakeFs::new(cx.background_executor.clone());
4460 fs.insert_tree(
4461 "/root",
4462 json!({
4463 "zed": {
4464 ".git": {},
4465 "crates": {
4466 "gpui": {
4467 "gpui.rs": "fn main() {}"
4468 },
4469 "util": {
4470 "util.rs": "fn do_it() {}"
4471 }
4472 }
4473 },
4474 }),
4475 )
4476 .await;
4477
4478 fs.set_status_for_repo_via_git_operation(
4479 Path::new(path!("/root/zed/.git")),
4480 &[
4481 (
4482 Path::new("crates/gpui/gpui.rs"),
4483 StatusCode::Modified.worktree(),
4484 ),
4485 (
4486 Path::new("crates/util/util.rs"),
4487 StatusCode::Modified.worktree(),
4488 ),
4489 ],
4490 );
4491
4492 let project =
4493 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4494 let (workspace, cx) =
4495 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4496
4497 cx.read(|cx| {
4498 project
4499 .read(cx)
4500 .worktrees(cx)
4501 .nth(0)
4502 .unwrap()
4503 .read(cx)
4504 .as_local()
4505 .unwrap()
4506 .scan_complete()
4507 })
4508 .await;
4509
4510 cx.executor().run_until_parked();
4511
4512 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4513 let panel = cx.new_window_entity(|window, cx| {
4514 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4515 });
4516
4517 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4518 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4519 });
4520 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4521 handle.await;
4522
4523 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4524 pretty_assertions::assert_eq!(
4525 entries,
4526 [
4527 GitListEntry::Header(GitHeaderEntry {
4528 header: Section::Tracked
4529 }),
4530 GitListEntry::GitStatusEntry(GitStatusEntry {
4531 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4532 repo_path: "crates/gpui/gpui.rs".into(),
4533 worktree_path: Path::new("gpui.rs").into(),
4534 status: StatusCode::Modified.worktree(),
4535 staging: StageStatus::Unstaged,
4536 }),
4537 GitListEntry::GitStatusEntry(GitStatusEntry {
4538 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4539 repo_path: "crates/util/util.rs".into(),
4540 worktree_path: Path::new("../util/util.rs").into(),
4541 status: StatusCode::Modified.worktree(),
4542 staging: StageStatus::Unstaged,
4543 },),
4544 ],
4545 );
4546
4547 cx.update_window_entity(&panel, |panel, window, cx| {
4548 panel.select_last(&Default::default(), window, cx);
4549 assert_eq!(panel.selected_entry, Some(2));
4550 panel.open_diff(&Default::default(), window, cx);
4551 });
4552 cx.run_until_parked();
4553
4554 let worktree_roots = workspace.update(cx, |workspace, cx| {
4555 workspace
4556 .worktrees(cx)
4557 .map(|worktree| worktree.read(cx).abs_path())
4558 .collect::<Vec<_>>()
4559 });
4560 pretty_assertions::assert_eq!(
4561 worktree_roots,
4562 vec![
4563 Path::new(path!("/root/zed/crates/gpui")).into(),
4564 Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4565 ]
4566 );
4567
4568 let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4569 let git_store = project.git_store().read(cx);
4570 // The repo that comes from the single-file worktree can't be selected through the UI.
4571 let filtered_entries = filtered_repository_entries(git_store, cx)
4572 .iter()
4573 .map(|repo| repo.read(cx).worktree_abs_path.clone())
4574 .collect::<Vec<_>>();
4575 assert_eq!(
4576 filtered_entries,
4577 [Path::new(path!("/root/zed/crates/gpui")).into()]
4578 );
4579 // But we can select it artificially here.
4580 git_store
4581 .all_repositories()
4582 .into_iter()
4583 .find(|repo| {
4584 &*repo.read(cx).worktree_abs_path
4585 == Path::new(path!("/root/zed/crates/util/util.rs"))
4586 })
4587 .unwrap()
4588 });
4589
4590 // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4591 repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4592 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4593 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4594 });
4595 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4596 handle.await;
4597 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4598 pretty_assertions::assert_eq!(
4599 entries,
4600 [
4601 GitListEntry::Header(GitHeaderEntry {
4602 header: Section::Tracked
4603 }),
4604 GitListEntry::GitStatusEntry(GitStatusEntry {
4605 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4606 repo_path: "crates/gpui/gpui.rs".into(),
4607 worktree_path: Path::new("../../gpui/gpui.rs").into(),
4608 status: StatusCode::Modified.worktree(),
4609 staging: StageStatus::Unstaged,
4610 }),
4611 GitListEntry::GitStatusEntry(GitStatusEntry {
4612 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4613 repo_path: "crates/util/util.rs".into(),
4614 worktree_path: Path::new("util.rs").into(),
4615 status: StatusCode::Modified.worktree(),
4616 staging: StageStatus::Unstaged,
4617 },),
4618 ],
4619 );
4620 }
4621}