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