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