git_panel.rs

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