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