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