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                    .cloned()
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.is_empty() {
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.is_empty() && 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.is_empty() && pending_staged_count == 1 {
2769            self.single_staged_entry = last_pending_staged;
2770        }
2771
2772        if conflict_entries.is_empty() && changed_entries.len() == 1 {
2773            self.single_tracked_entry = changed_entries.first().cloned();
2774        }
2775
2776        if !conflict_entries.is_empty() {
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.is_empty() {
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.is_empty() {
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 => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
2987                    ToastWithLog { output } => this
2988                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2989                        .action("View Log", move |window, cx| {
2990                            let output = output.clone();
2991                            let output =
2992                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2993                            workspace_weak
2994                                .update(cx, move |workspace, cx| {
2995                                    Self::open_output(operation, workspace, &output, window, cx)
2996                                })
2997                                .ok();
2998                        }),
2999                    PushPrLink { text, link } => this
3000                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3001                        .action(text, move |_, cx| cx.open_url(&link)),
3002                }
3003            });
3004            workspace.toggle_status_toast(status_toast, cx)
3005        });
3006    }
3007
3008    fn open_output(
3009        operation: impl Into<SharedString>,
3010        workspace: &mut Workspace,
3011        output: &str,
3012        window: &mut Window,
3013        cx: &mut Context<Workspace>,
3014    ) {
3015        let operation = operation.into();
3016        let buffer = cx.new(|cx| Buffer::local(output, cx));
3017        buffer.update(cx, |buffer, cx| {
3018            buffer.set_capability(language::Capability::ReadOnly, cx);
3019        });
3020        let editor = cx.new(|cx| {
3021            let mut editor = Editor::for_buffer(buffer, None, window, cx);
3022            editor.buffer().update(cx, |buffer, cx| {
3023                buffer.set_title(format!("Output from git {operation}"), cx);
3024            });
3025            editor.set_read_only(true);
3026            editor
3027        });
3028
3029        workspace.add_item_to_center(Box::new(editor), window, cx);
3030    }
3031
3032    pub fn can_commit(&self) -> bool {
3033        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3034    }
3035
3036    pub fn can_stage_all(&self) -> bool {
3037        self.has_unstaged_changes()
3038    }
3039
3040    pub fn can_unstage_all(&self) -> bool {
3041        self.has_staged_changes()
3042    }
3043
3044    // eventually we'll need to take depth into account here
3045    // if we add a tree view
3046    fn item_width_estimate(path: usize, file_name: usize) -> usize {
3047        path + file_name
3048    }
3049
3050    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3051        let focus_handle = self.focus_handle.clone();
3052        let has_tracked_changes = self.has_tracked_changes();
3053        let has_staged_changes = self.has_staged_changes();
3054        let has_unstaged_changes = self.has_unstaged_changes();
3055        let has_new_changes = self.new_count > 0;
3056
3057        PopoverMenu::new(id.into())
3058            .trigger(
3059                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3060                    .icon_size(IconSize::Small)
3061                    .icon_color(Color::Muted),
3062            )
3063            .menu(move |window, cx| {
3064                Some(git_panel_context_menu(
3065                    focus_handle.clone(),
3066                    GitMenuState {
3067                        has_tracked_changes,
3068                        has_staged_changes,
3069                        has_unstaged_changes,
3070                        has_new_changes,
3071                    },
3072                    window,
3073                    cx,
3074                ))
3075            })
3076            .anchor(Corner::TopRight)
3077    }
3078
3079    pub(crate) fn render_generate_commit_message_button(
3080        &self,
3081        cx: &Context<Self>,
3082    ) -> Option<AnyElement> {
3083        current_language_model(cx).is_some().then(|| {
3084            if self.generate_commit_message_task.is_some() {
3085                return h_flex()
3086                    .gap_1()
3087                    .child(
3088                        Icon::new(IconName::ArrowCircle)
3089                            .size(IconSize::XSmall)
3090                            .color(Color::Info)
3091                            .with_animation(
3092                                "arrow-circle",
3093                                Animation::new(Duration::from_secs(2)).repeat(),
3094                                |icon, delta| {
3095                                    icon.transform(Transformation::rotate(percentage(delta)))
3096                                },
3097                            ),
3098                    )
3099                    .child(
3100                        Label::new("Generating Commit...")
3101                            .size(LabelSize::Small)
3102                            .color(Color::Muted),
3103                    )
3104                    .into_any_element();
3105            }
3106
3107            let can_commit = self.can_commit();
3108            let editor_focus_handle = self.commit_editor.focus_handle(cx);
3109            IconButton::new("generate-commit-message", IconName::AiEdit)
3110                .shape(ui::IconButtonShape::Square)
3111                .icon_color(Color::Muted)
3112                .tooltip(move |window, cx| {
3113                    if can_commit {
3114                        Tooltip::for_action_in(
3115                            "Generate Commit Message",
3116                            &git::GenerateCommitMessage,
3117                            &editor_focus_handle,
3118                            window,
3119                            cx,
3120                        )
3121                    } else {
3122                        Tooltip::simple("No changes to commit", cx)
3123                    }
3124                })
3125                .disabled(!can_commit)
3126                .on_click(cx.listener(move |this, _event, _window, cx| {
3127                    this.generate_commit_message(cx);
3128                }))
3129                .into_any_element()
3130        })
3131    }
3132
3133    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3134        let potential_co_authors = self.potential_co_authors(cx);
3135
3136        let (tooltip_label, icon) = if self.add_coauthors {
3137            ("Remove co-authored-by", IconName::Person)
3138        } else {
3139            ("Add co-authored-by", IconName::UserCheck)
3140        };
3141
3142        if potential_co_authors.is_empty() {
3143            None
3144        } else {
3145            Some(
3146                IconButton::new("co-authors", icon)
3147                    .shape(ui::IconButtonShape::Square)
3148                    .icon_color(Color::Disabled)
3149                    .selected_icon_color(Color::Selected)
3150                    .toggle_state(self.add_coauthors)
3151                    .tooltip(move |_, cx| {
3152                        let title = format!(
3153                            "{}:{}{}",
3154                            tooltip_label,
3155                            if potential_co_authors.len() == 1 {
3156                                ""
3157                            } else {
3158                                "\n"
3159                            },
3160                            potential_co_authors
3161                                .iter()
3162                                .map(|(name, email)| format!(" {} <{}>", name, email))
3163                                .join("\n")
3164                        );
3165                        Tooltip::simple(title, cx)
3166                    })
3167                    .on_click(cx.listener(|this, _, _, cx| {
3168                        this.add_coauthors = !this.add_coauthors;
3169                        cx.notify();
3170                    }))
3171                    .into_any_element(),
3172            )
3173        }
3174    }
3175
3176    fn render_git_commit_menu(
3177        &self,
3178        id: impl Into<ElementId>,
3179        keybinding_target: Option<FocusHandle>,
3180        cx: &mut Context<Self>,
3181    ) -> impl IntoElement {
3182        PopoverMenu::new(id.into())
3183            .trigger(
3184                ui::ButtonLike::new_rounded_right("commit-split-button-right")
3185                    .layer(ui::ElevationIndex::ModalSurface)
3186                    .size(ButtonSize::None)
3187                    .child(
3188                        h_flex()
3189                            .px_1()
3190                            .h_full()
3191                            .justify_center()
3192                            .border_l_1()
3193                            .border_color(cx.theme().colors().border)
3194                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3195                    ),
3196            )
3197            .menu({
3198                let git_panel = cx.entity();
3199                let has_previous_commit = self.head_commit(cx).is_some();
3200                let amend = self.amend_pending();
3201                let signoff = self.signoff_enabled;
3202
3203                move |window, cx| {
3204                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3205                        context_menu
3206                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
3207                                el.context(keybinding_target)
3208                            })
3209                            .when(has_previous_commit, |this| {
3210                                this.toggleable_entry(
3211                                    "Amend",
3212                                    amend,
3213                                    IconPosition::Start,
3214                                    Some(Box::new(Amend)),
3215                                    {
3216                                        let git_panel = git_panel.downgrade();
3217                                        move |_, cx| {
3218                                            git_panel
3219                                                .update(cx, |git_panel, cx| {
3220                                                    git_panel.toggle_amend_pending(cx);
3221                                                })
3222                                                .ok();
3223                                        }
3224                                    },
3225                                )
3226                            })
3227                            .toggleable_entry(
3228                                "Signoff",
3229                                signoff,
3230                                IconPosition::Start,
3231                                Some(Box::new(Signoff)),
3232                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3233                            )
3234                    }))
3235                }
3236            })
3237            .anchor(Corner::TopRight)
3238    }
3239
3240    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3241        if self.has_unstaged_conflicts() {
3242            (false, "You must resolve conflicts before committing")
3243        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
3244            (false, "No changes to commit")
3245        } else if self.pending_commit.is_some() {
3246            (false, "Commit in progress")
3247        } else if !self.has_commit_message(cx) {
3248            (false, "No commit message")
3249        } else if !self.has_write_access(cx) {
3250            (false, "You do not have write access to this project")
3251        } else {
3252            (true, self.commit_button_title())
3253        }
3254    }
3255
3256    pub fn commit_button_title(&self) -> &'static str {
3257        if self.amend_pending {
3258            if self.has_staged_changes() {
3259                "Amend"
3260            } else {
3261                "Amend Tracked"
3262            }
3263        } else if self.has_staged_changes() {
3264            "Commit"
3265        } else {
3266            "Commit Tracked"
3267        }
3268    }
3269
3270    fn expand_commit_editor(
3271        &mut self,
3272        _: &git::ExpandCommitEditor,
3273        window: &mut Window,
3274        cx: &mut Context<Self>,
3275    ) {
3276        let workspace = self.workspace.clone();
3277        window.defer(cx, move |window, cx| {
3278            workspace
3279                .update(cx, |workspace, cx| {
3280                    CommitModal::toggle(workspace, None, window, cx)
3281                })
3282                .ok();
3283        })
3284    }
3285
3286    fn render_panel_header(
3287        &self,
3288        window: &mut Window,
3289        cx: &mut Context<Self>,
3290    ) -> Option<impl IntoElement> {
3291        self.active_repository.as_ref()?;
3292
3293        let text;
3294        let action;
3295        let tooltip;
3296        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3297            text = "Unstage All";
3298            action = git::UnstageAll.boxed_clone();
3299            tooltip = "git reset";
3300        } else {
3301            text = "Stage All";
3302            action = git::StageAll.boxed_clone();
3303            tooltip = "git add --all ."
3304        }
3305
3306        let change_string = match self.entry_count {
3307            0 => "No Changes".to_string(),
3308            1 => "1 Change".to_string(),
3309            _ => format!("{} Changes", self.entry_count),
3310        };
3311
3312        Some(
3313            self.panel_header_container(window, cx)
3314                .px_2()
3315                .justify_between()
3316                .child(
3317                    panel_button(change_string)
3318                        .color(Color::Muted)
3319                        .tooltip(Tooltip::for_action_title_in(
3320                            "Open Diff",
3321                            &Diff,
3322                            &self.focus_handle,
3323                        ))
3324                        .on_click(|_, _, cx| {
3325                            cx.defer(|cx| {
3326                                cx.dispatch_action(&Diff);
3327                            })
3328                        }),
3329                )
3330                .child(
3331                    h_flex()
3332                        .gap_1()
3333                        .child(self.render_overflow_menu("overflow_menu"))
3334                        .child(
3335                            panel_filled_button(text)
3336                                .tooltip(Tooltip::for_action_title_in(
3337                                    tooltip,
3338                                    action.as_ref(),
3339                                    &self.focus_handle,
3340                                ))
3341                                .disabled(self.entry_count == 0)
3342                                .on_click(move |_, _, cx| {
3343                                    let action = action.boxed_clone();
3344                                    cx.defer(move |cx| {
3345                                        cx.dispatch_action(action.as_ref());
3346                                    })
3347                                }),
3348                        ),
3349                ),
3350        )
3351    }
3352
3353    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3354        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3355        if !self.can_push_and_pull(cx) {
3356            return None;
3357        }
3358        Some(
3359            h_flex()
3360                .gap_1()
3361                .flex_shrink_0()
3362                .when_some(branch, |this, branch| {
3363                    let focus_handle = Some(self.focus_handle(cx));
3364
3365                    this.children(render_remote_button(
3366                        "remote-button",
3367                        &branch,
3368                        focus_handle,
3369                        true,
3370                    ))
3371                })
3372                .into_any_element(),
3373        )
3374    }
3375
3376    pub fn render_footer(
3377        &self,
3378        window: &mut Window,
3379        cx: &mut Context<Self>,
3380    ) -> Option<impl IntoElement> {
3381        let active_repository = self.active_repository.clone()?;
3382        let panel_editor_style = panel_editor_style(true, window, cx);
3383
3384        let enable_coauthors = self.render_co_authors(cx);
3385
3386        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3387        let expand_tooltip_focus_handle = editor_focus_handle;
3388
3389        let branch = active_repository.read(cx).branch.clone();
3390        let head_commit = active_repository.read(cx).head_commit.clone();
3391
3392        let footer_size = px(32.);
3393        let gap = px(9.0);
3394        let max_height = panel_editor_style
3395            .text
3396            .line_height_in_pixels(window.rem_size())
3397            * MAX_PANEL_EDITOR_LINES
3398            + gap;
3399
3400        let git_panel = cx.entity();
3401        let display_name = SharedString::from(Arc::from(
3402            active_repository
3403                .read(cx)
3404                .display_name()
3405                .trim_end_matches("/"),
3406        ));
3407        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3408            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3409        });
3410
3411        let footer = v_flex()
3412            .child(PanelRepoFooter::new(
3413                display_name,
3414                branch,
3415                head_commit,
3416                Some(git_panel),
3417            ))
3418            .child(
3419                panel_editor_container(window, cx)
3420                    .id("commit-editor-container")
3421                    .relative()
3422                    .w_full()
3423                    .h(max_height + footer_size)
3424                    .border_t_1()
3425                    .border_color(cx.theme().colors().border)
3426                    .cursor_text()
3427                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3428                        window.focus(&this.commit_editor.focus_handle(cx));
3429                    }))
3430                    .child(
3431                        h_flex()
3432                            .id("commit-footer")
3433                            .border_t_1()
3434                            .when(editor_is_long, |el| {
3435                                el.border_color(cx.theme().colors().border_variant)
3436                            })
3437                            .absolute()
3438                            .bottom_0()
3439                            .left_0()
3440                            .w_full()
3441                            .px_2()
3442                            .h(footer_size)
3443                            .flex_none()
3444                            .justify_between()
3445                            .child(
3446                                self.render_generate_commit_message_button(cx)
3447                                    .unwrap_or_else(|| div().into_any_element()),
3448                            )
3449                            .child(
3450                                h_flex()
3451                                    .gap_0p5()
3452                                    .children(enable_coauthors)
3453                                    .child(self.render_commit_button(cx)),
3454                            ),
3455                    )
3456                    .child(
3457                        div()
3458                            .pr_2p5()
3459                            .on_action(|&editor::actions::MoveUp, _, cx| {
3460                                cx.stop_propagation();
3461                            })
3462                            .on_action(|&editor::actions::MoveDown, _, cx| {
3463                                cx.stop_propagation();
3464                            })
3465                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3466                    )
3467                    .child(
3468                        h_flex()
3469                            .absolute()
3470                            .top_2()
3471                            .right_2()
3472                            .opacity(0.5)
3473                            .hover(|this| this.opacity(1.0))
3474                            .child(
3475                                panel_icon_button("expand-commit-editor", IconName::Maximize)
3476                                    .icon_size(IconSize::Small)
3477                                    .size(ui::ButtonSize::Default)
3478                                    .tooltip(move |window, cx| {
3479                                        Tooltip::for_action_in(
3480                                            "Open Commit Modal",
3481                                            &git::ExpandCommitEditor,
3482                                            &expand_tooltip_focus_handle,
3483                                            window,
3484                                            cx,
3485                                        )
3486                                    })
3487                                    .on_click(cx.listener({
3488                                        move |_, _, window, cx| {
3489                                            window.dispatch_action(
3490                                                git::ExpandCommitEditor.boxed_clone(),
3491                                                cx,
3492                                            )
3493                                        }
3494                                    })),
3495                            ),
3496                    ),
3497            );
3498
3499        Some(footer)
3500    }
3501
3502    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3503        let (can_commit, tooltip) = self.configure_commit_button(cx);
3504        let title = self.commit_button_title();
3505        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3506        let amend = self.amend_pending();
3507        let signoff = self.signoff_enabled;
3508
3509        div()
3510            .id("commit-wrapper")
3511            .on_hover(cx.listener(move |this, hovered, _, cx| {
3512                this.show_placeholders =
3513                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3514                cx.notify()
3515            }))
3516            .child(SplitButton::new(
3517                ui::ButtonLike::new_rounded_left(ElementId::Name(
3518                    format!("split-button-left-{}", title).into(),
3519                ))
3520                .layer(ui::ElevationIndex::ModalSurface)
3521                .size(ui::ButtonSize::Compact)
3522                .child(
3523                    div()
3524                        .child(Label::new(title).size(LabelSize::Small))
3525                        .mr_0p5(),
3526                )
3527                .on_click({
3528                    let git_panel = cx.weak_entity();
3529                    move |_, window, cx| {
3530                        telemetry::event!("Git Committed", source = "Git Panel");
3531                        git_panel
3532                            .update(cx, |git_panel, cx| {
3533                                git_panel.set_amend_pending(false, cx);
3534                                git_panel.commit_changes(
3535                                    CommitOptions { amend, signoff },
3536                                    window,
3537                                    cx,
3538                                );
3539                            })
3540                            .ok();
3541                    }
3542                })
3543                .disabled(!can_commit || self.modal_open)
3544                .tooltip({
3545                    let handle = commit_tooltip_focus_handle.clone();
3546                    move |window, cx| {
3547                        if can_commit {
3548                            Tooltip::with_meta_in(
3549                                tooltip,
3550                                Some(&git::Commit),
3551                                format!(
3552                                    "git commit{}{}",
3553                                    if amend { " --amend" } else { "" },
3554                                    if signoff { " --signoff" } else { "" }
3555                                ),
3556                                &handle.clone(),
3557                                window,
3558                                cx,
3559                            )
3560                        } else {
3561                            Tooltip::simple(tooltip, cx)
3562                        }
3563                    }
3564                }),
3565                self.render_git_commit_menu(
3566                    ElementId::Name(format!("split-button-right-{}", title).into()),
3567                    Some(commit_tooltip_focus_handle),
3568                    cx,
3569                )
3570                .into_any_element(),
3571            ))
3572    }
3573
3574    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3575        h_flex()
3576            .py_1p5()
3577            .px_2()
3578            .gap_1p5()
3579            .justify_between()
3580            .border_t_1()
3581            .border_color(cx.theme().colors().border.opacity(0.8))
3582            .child(
3583                div()
3584                    .flex_grow()
3585                    .overflow_hidden()
3586                    .max_w(relative(0.85))
3587                    .child(
3588                        Label::new("This will update your most recent commit.")
3589                            .size(LabelSize::Small)
3590                            .truncate(),
3591                    ),
3592            )
3593            .child(
3594                panel_button("Cancel")
3595                    .size(ButtonSize::Default)
3596                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3597            )
3598    }
3599
3600    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3601        let active_repository = self.active_repository.as_ref()?;
3602        let branch = active_repository.read(cx).branch.as_ref()?;
3603        let commit = branch.most_recent_commit.as_ref()?.clone();
3604        let workspace = self.workspace.clone();
3605        let this = cx.entity();
3606
3607        Some(
3608            h_flex()
3609                .py_1p5()
3610                .px_2()
3611                .gap_1p5()
3612                .justify_between()
3613                .border_t_1()
3614                .border_color(cx.theme().colors().border.opacity(0.8))
3615                .child(
3616                    div()
3617                        .flex_grow()
3618                        .overflow_hidden()
3619                        .max_w(relative(0.85))
3620                        .child(
3621                            Label::new(commit.subject.clone())
3622                                .size(LabelSize::Small)
3623                                .truncate(),
3624                        )
3625                        .id("commit-msg-hover")
3626                        .on_click({
3627                            let commit = commit.clone();
3628                            let repo = active_repository.downgrade();
3629                            move |_, window, cx| {
3630                                CommitView::open(
3631                                    commit.clone(),
3632                                    repo.clone(),
3633                                    workspace.clone(),
3634                                    window,
3635                                    cx,
3636                                );
3637                            }
3638                        })
3639                        .hoverable_tooltip({
3640                            let repo = active_repository.clone();
3641                            move |window, cx| {
3642                                GitPanelMessageTooltip::new(
3643                                    this.clone(),
3644                                    commit.sha.clone(),
3645                                    repo.clone(),
3646                                    window,
3647                                    cx,
3648                                )
3649                                .into()
3650                            }
3651                        }),
3652                )
3653                .when(commit.has_parent, |this| {
3654                    let has_unstaged = self.has_unstaged_changes();
3655                    this.child(
3656                        panel_icon_button("undo", IconName::Undo)
3657                            .icon_size(IconSize::XSmall)
3658                            .icon_color(Color::Muted)
3659                            .tooltip(move |window, cx| {
3660                                Tooltip::with_meta(
3661                                    "Uncommit",
3662                                    Some(&git::Uncommit),
3663                                    if has_unstaged {
3664                                        "git reset HEAD^ --soft"
3665                                    } else {
3666                                        "git reset HEAD^"
3667                                    },
3668                                    window,
3669                                    cx,
3670                                )
3671                            })
3672                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3673                    )
3674                }),
3675        )
3676    }
3677
3678    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3679        h_flex().h_full().flex_grow().justify_center().child(
3680            v_flex()
3681                .gap_2()
3682                .child(h_flex().w_full().justify_around().child(
3683                    if self.active_repository.is_some() {
3684                        "No changes to commit"
3685                    } else {
3686                        "No Git repositories"
3687                    },
3688                ))
3689                .children({
3690                    let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3691                    (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3692                        h_flex().w_full().justify_around().child(
3693                            panel_filled_button("Initialize Repository")
3694                                .tooltip(Tooltip::for_action_title_in(
3695                                    "git init",
3696                                    &git::Init,
3697                                    &self.focus_handle,
3698                                ))
3699                                .on_click(move |_, _, cx| {
3700                                    cx.defer(move |cx| {
3701                                        cx.dispatch_action(&git::Init);
3702                                    })
3703                                }),
3704                        )
3705                    })
3706                })
3707                .text_ui_sm(cx)
3708                .mx_auto()
3709                .text_color(Color::Placeholder.color(cx)),
3710        )
3711    }
3712
3713    fn render_vertical_scrollbar(
3714        &self,
3715        show_horizontal_scrollbar_container: bool,
3716        cx: &mut Context<Self>,
3717    ) -> impl IntoElement {
3718        div()
3719            .id("git-panel-vertical-scroll")
3720            .occlude()
3721            .flex_none()
3722            .h_full()
3723            .cursor_default()
3724            .absolute()
3725            .right_0()
3726            .top_0()
3727            .bottom_0()
3728            .w(px(12.))
3729            .when(show_horizontal_scrollbar_container, |this| {
3730                this.pb_neg_3p5()
3731            })
3732            .on_mouse_move(cx.listener(|_, _, _, cx| {
3733                cx.notify();
3734                cx.stop_propagation()
3735            }))
3736            .on_hover(|_, _, cx| {
3737                cx.stop_propagation();
3738            })
3739            .on_any_mouse_down(|_, _, cx| {
3740                cx.stop_propagation();
3741            })
3742            .on_mouse_up(
3743                MouseButton::Left,
3744                cx.listener(|this, _, window, cx| {
3745                    if !this.vertical_scrollbar.state.is_dragging()
3746                        && !this.focus_handle.contains_focused(window, cx)
3747                    {
3748                        this.vertical_scrollbar.hide(window, cx);
3749                        cx.notify();
3750                    }
3751
3752                    cx.stop_propagation();
3753                }),
3754            )
3755            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3756                cx.notify();
3757            }))
3758            .children(Scrollbar::vertical(
3759                // percentage as f32..end_offset as f32,
3760                self.vertical_scrollbar.state.clone(),
3761            ))
3762    }
3763
3764    /// Renders the horizontal scrollbar.
3765    ///
3766    /// The right offset is used to determine how far to the right the
3767    /// scrollbar should extend to, useful for ensuring it doesn't collide
3768    /// with the vertical scrollbar when visible.
3769    fn render_horizontal_scrollbar(
3770        &self,
3771        right_offset: Pixels,
3772        cx: &mut Context<Self>,
3773    ) -> impl IntoElement {
3774        div()
3775            .id("git-panel-horizontal-scroll")
3776            .occlude()
3777            .flex_none()
3778            .w_full()
3779            .cursor_default()
3780            .absolute()
3781            .bottom_neg_px()
3782            .left_0()
3783            .right_0()
3784            .pr(right_offset)
3785            .on_mouse_move(cx.listener(|_, _, _, cx| {
3786                cx.notify();
3787                cx.stop_propagation()
3788            }))
3789            .on_hover(|_, _, cx| {
3790                cx.stop_propagation();
3791            })
3792            .on_any_mouse_down(|_, _, cx| {
3793                cx.stop_propagation();
3794            })
3795            .on_mouse_up(
3796                MouseButton::Left,
3797                cx.listener(|this, _, window, cx| {
3798                    if !this.horizontal_scrollbar.state.is_dragging()
3799                        && !this.focus_handle.contains_focused(window, cx)
3800                    {
3801                        this.horizontal_scrollbar.hide(window, cx);
3802                        cx.notify();
3803                    }
3804
3805                    cx.stop_propagation();
3806                }),
3807            )
3808            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3809                cx.notify();
3810            }))
3811            .children(Scrollbar::horizontal(
3812                // percentage as f32..end_offset as f32,
3813                self.horizontal_scrollbar.state.clone(),
3814            ))
3815    }
3816
3817    fn render_buffer_header_controls(
3818        &self,
3819        entity: &Entity<Self>,
3820        file: &Arc<dyn File>,
3821        _: &Window,
3822        cx: &App,
3823    ) -> Option<AnyElement> {
3824        let repo = self.active_repository.as_ref()?.read(cx);
3825        let project_path = (file.worktree_id(cx), file.path()).into();
3826        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3827        let ix = self.entry_by_path(&repo_path, cx)?;
3828        let entry = self.entries.get(ix)?;
3829
3830        let entry_staging = self.entry_staging(entry.status_entry()?);
3831
3832        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3833            .disabled(!self.has_write_access(cx))
3834            .fill()
3835            .elevation(ElevationIndex::Surface)
3836            .on_click({
3837                let entry = entry.clone();
3838                let git_panel = entity.downgrade();
3839                move |_, window, cx| {
3840                    git_panel
3841                        .update(cx, |this, cx| {
3842                            this.toggle_staged_for_entry(&entry, window, cx);
3843                            cx.stop_propagation();
3844                        })
3845                        .ok();
3846                }
3847            });
3848        Some(
3849            h_flex()
3850                .id("start-slot")
3851                .text_lg()
3852                .child(checkbox)
3853                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3854                    // prevent the list item active state triggering when toggling checkbox
3855                    cx.stop_propagation();
3856                })
3857                .into_any_element(),
3858        )
3859    }
3860
3861    fn render_entries(
3862        &self,
3863        has_write_access: bool,
3864        _: &Window,
3865        cx: &mut Context<Self>,
3866    ) -> impl IntoElement {
3867        let entry_count = self.entries.len();
3868
3869        let scroll_track_size = px(16.);
3870
3871        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3872            // magic number
3873            px(3.)
3874        } else {
3875            px(0.)
3876        };
3877
3878        v_flex()
3879            .flex_1()
3880            .size_full()
3881            .overflow_hidden()
3882            .relative()
3883            // Show a border on the top and bottom of the container when
3884            // the vertical scrollbar container is visible so we don't have a
3885            // floating left border in the panel.
3886            .when(self.vertical_scrollbar.show_track, |this| {
3887                this.border_t_1()
3888                    .border_b_1()
3889                    .border_color(cx.theme().colors().border)
3890            })
3891            .child(
3892                h_flex()
3893                    .flex_1()
3894                    .size_full()
3895                    .relative()
3896                    .overflow_hidden()
3897                    .child(
3898                        uniform_list(
3899                            "entries",
3900                            entry_count,
3901                            cx.processor(move |this, range: Range<usize>, window, cx| {
3902                                let mut items = Vec::with_capacity(range.end - range.start);
3903
3904                                for ix in range {
3905                                    match &this.entries.get(ix) {
3906                                        Some(GitListEntry::Status(entry)) => {
3907                                            items.push(this.render_entry(
3908                                                ix,
3909                                                entry,
3910                                                has_write_access,
3911                                                window,
3912                                                cx,
3913                                            ));
3914                                        }
3915                                        Some(GitListEntry::Header(header)) => {
3916                                            items.push(this.render_list_header(
3917                                                ix,
3918                                                header,
3919                                                has_write_access,
3920                                                window,
3921                                                cx,
3922                                            ));
3923                                        }
3924                                        None => {}
3925                                    }
3926                                }
3927
3928                                items
3929                            }),
3930                        )
3931                        .when(
3932                            !self.horizontal_scrollbar.show_track
3933                                && self.horizontal_scrollbar.show_scrollbar,
3934                            |this| {
3935                                // when not showing the horizontal scrollbar track, make sure we don't
3936                                // obscure the last entry
3937                                this.pb(scroll_track_size)
3938                            },
3939                        )
3940                        .size_full()
3941                        .flex_grow()
3942                        .with_sizing_behavior(ListSizingBehavior::Auto)
3943                        .with_horizontal_sizing_behavior(
3944                            ListHorizontalSizingBehavior::Unconstrained,
3945                        )
3946                        .with_width_from_item(self.max_width_item_index)
3947                        .track_scroll(self.scroll_handle.clone()),
3948                    )
3949                    .on_mouse_down(
3950                        MouseButton::Right,
3951                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3952                            this.deploy_panel_context_menu(event.position, window, cx)
3953                        }),
3954                    )
3955                    .when(self.vertical_scrollbar.show_track, |this| {
3956                        this.child(
3957                            v_flex()
3958                                .h_full()
3959                                .flex_none()
3960                                .w(scroll_track_size)
3961                                .bg(cx.theme().colors().panel_background)
3962                                .child(
3963                                    div()
3964                                        .size_full()
3965                                        .flex_1()
3966                                        .border_l_1()
3967                                        .border_color(cx.theme().colors().border),
3968                                ),
3969                        )
3970                    })
3971                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
3972                        this.child(
3973                            self.render_vertical_scrollbar(
3974                                self.horizontal_scrollbar.show_track,
3975                                cx,
3976                            ),
3977                        )
3978                    }),
3979            )
3980            .when(self.horizontal_scrollbar.show_track, |this| {
3981                this.child(
3982                    h_flex()
3983                        .w_full()
3984                        .h(scroll_track_size)
3985                        .flex_none()
3986                        .relative()
3987                        .child(
3988                            div()
3989                                .w_full()
3990                                .flex_1()
3991                                // for some reason the horizontal scrollbar is 1px
3992                                // taller than the vertical scrollbar??
3993                                .h(scroll_track_size - px(1.))
3994                                .bg(cx.theme().colors().panel_background)
3995                                .border_t_1()
3996                                .border_color(cx.theme().colors().border),
3997                        )
3998                        .when(self.vertical_scrollbar.show_track, |this| {
3999                            this.child(
4000                                div()
4001                                    .flex_none()
4002                                    // -1px prevents a missing pixel between the two container borders
4003                                    .w(scroll_track_size - px(1.))
4004                                    .h_full(),
4005                            )
4006                            .child(
4007                                // HACK: Fill the missing 1px 🥲
4008                                div()
4009                                    .absolute()
4010                                    .right(scroll_track_size - px(1.))
4011                                    .bottom(scroll_track_size - px(1.))
4012                                    .size_px()
4013                                    .bg(cx.theme().colors().border),
4014                            )
4015                        }),
4016                )
4017            })
4018            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
4019                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
4020            })
4021    }
4022
4023    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4024        Label::new(label.into()).color(color).single_line()
4025    }
4026
4027    fn list_item_height(&self) -> Rems {
4028        rems(1.75)
4029    }
4030
4031    fn render_list_header(
4032        &self,
4033        ix: usize,
4034        header: &GitHeaderEntry,
4035        _: bool,
4036        _: &Window,
4037        _: &Context<Self>,
4038    ) -> AnyElement {
4039        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4040
4041        h_flex()
4042            .id(id)
4043            .h(self.list_item_height())
4044            .w_full()
4045            .items_end()
4046            .px(rems(0.75)) // ~12px
4047            .pb(rems(0.3125)) // ~ 5px
4048            .child(
4049                Label::new(header.title())
4050                    .color(Color::Muted)
4051                    .size(LabelSize::Small)
4052                    .line_height_style(LineHeightStyle::UiLabel)
4053                    .single_line(),
4054            )
4055            .into_any_element()
4056    }
4057
4058    pub fn load_commit_details(
4059        &self,
4060        sha: String,
4061        cx: &mut Context<Self>,
4062    ) -> Task<anyhow::Result<CommitDetails>> {
4063        let Some(repo) = self.active_repository.clone() else {
4064            return Task::ready(Err(anyhow::anyhow!("no active repo")));
4065        };
4066        repo.update(cx, |repo, cx| {
4067            let show = repo.show(sha);
4068            cx.spawn(async move |_, _| show.await?)
4069        })
4070    }
4071
4072    fn deploy_entry_context_menu(
4073        &mut self,
4074        position: Point<Pixels>,
4075        ix: usize,
4076        window: &mut Window,
4077        cx: &mut Context<Self>,
4078    ) {
4079        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4080            return;
4081        };
4082        let stage_title = if entry.status.staging().is_fully_staged() {
4083            "Unstage File"
4084        } else {
4085            "Stage File"
4086        };
4087        let restore_title = if entry.status.is_created() {
4088            "Trash File"
4089        } else {
4090            "Restore File"
4091        };
4092        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4093            context_menu
4094                .context(self.focus_handle.clone())
4095                .action(stage_title, ToggleStaged.boxed_clone())
4096                .action(restore_title, git::RestoreFile::default().boxed_clone())
4097                .separator()
4098                .action("Open Diff", Confirm.boxed_clone())
4099                .action("Open File", SecondaryConfirm.boxed_clone())
4100        });
4101        self.selected_entry = Some(ix);
4102        self.set_context_menu(context_menu, position, window, cx);
4103    }
4104
4105    fn deploy_panel_context_menu(
4106        &mut self,
4107        position: Point<Pixels>,
4108        window: &mut Window,
4109        cx: &mut Context<Self>,
4110    ) {
4111        let context_menu = git_panel_context_menu(
4112            self.focus_handle.clone(),
4113            GitMenuState {
4114                has_tracked_changes: self.has_tracked_changes(),
4115                has_staged_changes: self.has_staged_changes(),
4116                has_unstaged_changes: self.has_unstaged_changes(),
4117                has_new_changes: self.new_count > 0,
4118            },
4119            window,
4120            cx,
4121        );
4122        self.set_context_menu(context_menu, position, window, cx);
4123    }
4124
4125    fn set_context_menu(
4126        &mut self,
4127        context_menu: Entity<ContextMenu>,
4128        position: Point<Pixels>,
4129        window: &Window,
4130        cx: &mut Context<Self>,
4131    ) {
4132        let subscription = cx.subscribe_in(
4133            &context_menu,
4134            window,
4135            |this, _, _: &DismissEvent, window, cx| {
4136                if this.context_menu.as_ref().is_some_and(|context_menu| {
4137                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
4138                }) {
4139                    cx.focus_self(window);
4140                }
4141                this.context_menu.take();
4142                cx.notify();
4143            },
4144        );
4145        self.context_menu = Some((context_menu, position, subscription));
4146        cx.notify();
4147    }
4148
4149    fn render_entry(
4150        &self,
4151        ix: usize,
4152        entry: &GitStatusEntry,
4153        has_write_access: bool,
4154        window: &Window,
4155        cx: &Context<Self>,
4156    ) -> AnyElement {
4157        let display_name = entry.display_name();
4158
4159        let selected = self.selected_entry == Some(ix);
4160        let marked = self.marked_entries.contains(&ix);
4161        let status_style = GitPanelSettings::get_global(cx).status_style;
4162        let status = entry.status;
4163
4164        let has_conflict = status.is_conflicted();
4165        let is_modified = status.is_modified();
4166        let is_deleted = status.is_deleted();
4167
4168        let label_color = if status_style == StatusStyle::LabelColor {
4169            if has_conflict {
4170                Color::VersionControlConflict
4171            } else if is_modified {
4172                Color::VersionControlModified
4173            } else if is_deleted {
4174                // We don't want a bunch of red labels in the list
4175                Color::Disabled
4176            } else {
4177                Color::VersionControlAdded
4178            }
4179        } else {
4180            Color::Default
4181        };
4182
4183        let path_color = if status.is_deleted() {
4184            Color::Disabled
4185        } else {
4186            Color::Muted
4187        };
4188
4189        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4190        let checkbox_wrapper_id: ElementId =
4191            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4192        let checkbox_id: ElementId =
4193            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4194
4195        let entry_staging = self.entry_staging(entry);
4196        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4197        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4198            is_staged = ToggleState::Selected;
4199        }
4200
4201        let handle = cx.weak_entity();
4202
4203        let selected_bg_alpha = 0.08;
4204        let marked_bg_alpha = 0.12;
4205        let state_opacity_step = 0.04;
4206
4207        let base_bg = match (selected, marked) {
4208            (true, true) => cx
4209                .theme()
4210                .status()
4211                .info
4212                .alpha(selected_bg_alpha + marked_bg_alpha),
4213            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4214            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4215            _ => cx.theme().colors().ghost_element_background,
4216        };
4217
4218        let hover_bg = if selected {
4219            cx.theme()
4220                .status()
4221                .info
4222                .alpha(selected_bg_alpha + state_opacity_step)
4223        } else {
4224            cx.theme().colors().ghost_element_hover
4225        };
4226
4227        let active_bg = if selected {
4228            cx.theme()
4229                .status()
4230                .info
4231                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4232        } else {
4233            cx.theme().colors().ghost_element_active
4234        };
4235
4236        h_flex()
4237            .id(id)
4238            .h(self.list_item_height())
4239            .w_full()
4240            .items_center()
4241            .border_1()
4242            .when(selected && self.focus_handle.is_focused(window), |el| {
4243                el.border_color(cx.theme().colors().border_focused)
4244            })
4245            .px(rems(0.75)) // ~12px
4246            .overflow_hidden()
4247            .flex_none()
4248            .gap_1p5()
4249            .bg(base_bg)
4250            .hover(|this| this.bg(hover_bg))
4251            .active(|this| this.bg(active_bg))
4252            .on_click({
4253                cx.listener(move |this, event: &ClickEvent, window, cx| {
4254                    this.selected_entry = Some(ix);
4255                    cx.notify();
4256                    if event.modifiers().secondary() {
4257                        this.open_file(&Default::default(), window, cx)
4258                    } else {
4259                        this.open_diff(&Default::default(), window, cx);
4260                        this.focus_handle.focus(window);
4261                    }
4262                })
4263            })
4264            .on_mouse_down(
4265                MouseButton::Right,
4266                move |event: &MouseDownEvent, window, cx| {
4267                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4268                    if event.button != MouseButton::Right {
4269                        return;
4270                    }
4271
4272                    let Some(this) = handle.upgrade() else {
4273                        return;
4274                    };
4275                    this.update(cx, |this, cx| {
4276                        this.deploy_entry_context_menu(event.position, ix, window, cx);
4277                    });
4278                    cx.stop_propagation();
4279                },
4280            )
4281            .child(
4282                div()
4283                    .id(checkbox_wrapper_id)
4284                    .flex_none()
4285                    .occlude()
4286                    .cursor_pointer()
4287                    .child(
4288                        Checkbox::new(checkbox_id, is_staged)
4289                            .disabled(!has_write_access)
4290                            .fill()
4291                            .elevation(ElevationIndex::Surface)
4292                            .on_click_ext({
4293                                let entry = entry.clone();
4294                                let this = cx.weak_entity();
4295                                move |_, click, window, cx| {
4296                                    this.update(cx, |this, cx| {
4297                                        if !has_write_access {
4298                                            return;
4299                                        }
4300                                        if click.modifiers().shift {
4301                                            this.stage_bulk(ix, cx);
4302                                        } else {
4303                                            this.toggle_staged_for_entry(
4304                                                &GitListEntry::Status(entry.clone()),
4305                                                window,
4306                                                cx,
4307                                            );
4308                                        }
4309                                        cx.stop_propagation();
4310                                    })
4311                                    .ok();
4312                                }
4313                            })
4314                            .tooltip(move |window, cx| {
4315                                let is_staged = entry_staging.is_fully_staged();
4316
4317                                let action = if is_staged { "Unstage" } else { "Stage" };
4318                                let tooltip_name = action.to_string();
4319
4320                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4321                            }),
4322                    ),
4323            )
4324            .child(git_status_icon(status))
4325            .child(
4326                h_flex()
4327                    .items_center()
4328                    .flex_1()
4329                    // .overflow_hidden()
4330                    .when_some(entry.parent_dir(), |this, parent| {
4331                        if !parent.is_empty() {
4332                            this.child(
4333                                self.entry_label(format!("{}/", parent), path_color)
4334                                    .when(status.is_deleted(), |this| this.strikethrough()),
4335                            )
4336                        } else {
4337                            this
4338                        }
4339                    })
4340                    .child(
4341                        self.entry_label(display_name, label_color)
4342                            .when(status.is_deleted(), |this| this.strikethrough()),
4343                    ),
4344            )
4345            .into_any_element()
4346    }
4347
4348    fn has_write_access(&self, cx: &App) -> bool {
4349        !self.project.read(cx).is_read_only(cx)
4350    }
4351
4352    pub fn amend_pending(&self) -> bool {
4353        self.amend_pending
4354    }
4355
4356    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4357        self.amend_pending = value;
4358        self.serialize(cx);
4359        cx.notify();
4360    }
4361
4362    pub fn signoff_enabled(&self) -> bool {
4363        self.signoff_enabled
4364    }
4365
4366    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4367        self.signoff_enabled = value;
4368        self.serialize(cx);
4369        cx.notify();
4370    }
4371
4372    pub fn toggle_signoff_enabled(
4373        &mut self,
4374        _: &Signoff,
4375        _window: &mut Window,
4376        cx: &mut Context<Self>,
4377    ) {
4378        self.set_signoff_enabled(!self.signoff_enabled, cx);
4379    }
4380
4381    pub async fn load(
4382        workspace: WeakEntity<Workspace>,
4383        mut cx: AsyncWindowContext,
4384    ) -> anyhow::Result<Entity<Self>> {
4385        let serialized_panel = match workspace
4386            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4387            .ok()
4388            .flatten()
4389        {
4390            Some(serialization_key) => cx
4391                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4392                .await
4393                .context("loading git panel")
4394                .log_err()
4395                .flatten()
4396                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4397                .transpose()
4398                .log_err()
4399                .flatten(),
4400            None => None,
4401        };
4402
4403        workspace.update_in(&mut cx, |workspace, window, cx| {
4404            let panel = GitPanel::new(workspace, window, cx);
4405
4406            if let Some(serialized_panel) = serialized_panel {
4407                panel.update(cx, |panel, cx| {
4408                    panel.width = serialized_panel.width;
4409                    panel.amend_pending = serialized_panel.amend_pending;
4410                    panel.signoff_enabled = serialized_panel.signoff_enabled;
4411                    cx.notify();
4412                })
4413            }
4414
4415            panel
4416        })
4417    }
4418
4419    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4420        let Some(op) = self.bulk_staging.as_ref() else {
4421            return;
4422        };
4423        let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4424            return;
4425        };
4426        if let Some(entry) = self.entries.get(index)
4427            && let Some(entry) = entry.status_entry()
4428        {
4429            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4430        }
4431        if index < anchor_index {
4432            std::mem::swap(&mut index, &mut anchor_index);
4433        }
4434        let entries = self
4435            .entries
4436            .get(anchor_index..=index)
4437            .unwrap_or_default()
4438            .iter()
4439            .filter_map(|entry| entry.status_entry().cloned())
4440            .collect::<Vec<_>>();
4441        self.change_file_stage(true, entries, cx);
4442    }
4443
4444    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4445        let Some(repo) = self.active_repository.as_ref() else {
4446            return;
4447        };
4448        self.bulk_staging = Some(BulkStaging {
4449            repo_id: repo.read(cx).id,
4450            anchor: path,
4451        });
4452    }
4453
4454    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4455        self.set_amend_pending(!self.amend_pending, cx);
4456        if self.amend_pending {
4457            self.load_last_commit_message_if_empty(cx);
4458        }
4459    }
4460}
4461
4462fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
4463    let is_enabled = agent_settings::AgentSettings::get_global(cx).enabled
4464        && !DisableAiSettings::get_global(cx).disable_ai;
4465
4466    is_enabled
4467        .then(|| {
4468            let ConfiguredModel { provider, model } =
4469                LanguageModelRegistry::read_global(cx).commit_message_model()?;
4470
4471            provider.is_authenticated(cx).then(|| model)
4472        })
4473        .flatten()
4474}
4475
4476impl Render for GitPanel {
4477    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4478        let project = self.project.read(cx);
4479        let has_entries = !self.entries.is_empty();
4480        let room = self
4481            .workspace
4482            .upgrade()
4483            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4484
4485        let has_write_access = self.has_write_access(cx);
4486
4487        let has_co_authors = room.is_some_and(|room| {
4488            self.load_local_committer(cx);
4489            let room = room.read(cx);
4490            room.remote_participants()
4491                .values()
4492                .any(|remote_participant| remote_participant.can_write())
4493        });
4494
4495        v_flex()
4496            .id("git_panel")
4497            .key_context(self.dispatch_context(window, cx))
4498            .track_focus(&self.focus_handle)
4499            .when(has_write_access && !project.is_read_only(cx), |this| {
4500                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4501                    .on_action(cx.listener(Self::stage_range))
4502                    .on_action(cx.listener(GitPanel::commit))
4503                    .on_action(cx.listener(GitPanel::amend))
4504                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4505                    .on_action(cx.listener(Self::stage_all))
4506                    .on_action(cx.listener(Self::unstage_all))
4507                    .on_action(cx.listener(Self::stage_selected))
4508                    .on_action(cx.listener(Self::unstage_selected))
4509                    .on_action(cx.listener(Self::restore_tracked_files))
4510                    .on_action(cx.listener(Self::revert_selected))
4511                    .on_action(cx.listener(Self::clean_all))
4512                    .on_action(cx.listener(Self::generate_commit_message_action))
4513                    .on_action(cx.listener(Self::stash_all))
4514                    .on_action(cx.listener(Self::stash_pop))
4515            })
4516            .on_action(cx.listener(Self::select_first))
4517            .on_action(cx.listener(Self::select_next))
4518            .on_action(cx.listener(Self::select_previous))
4519            .on_action(cx.listener(Self::select_last))
4520            .on_action(cx.listener(Self::close_panel))
4521            .on_action(cx.listener(Self::open_diff))
4522            .on_action(cx.listener(Self::open_file))
4523            .on_action(cx.listener(Self::focus_changes_list))
4524            .on_action(cx.listener(Self::focus_editor))
4525            .on_action(cx.listener(Self::expand_commit_editor))
4526            .when(has_write_access && has_co_authors, |git_panel| {
4527                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4528            })
4529            .on_hover(cx.listener(move |this, hovered, window, cx| {
4530                if *hovered {
4531                    this.horizontal_scrollbar.show(cx);
4532                    this.vertical_scrollbar.show(cx);
4533                    cx.notify();
4534                } else if !this.focus_handle.contains_focused(window, cx) {
4535                    this.hide_scrollbars(window, cx);
4536                }
4537            }))
4538            .size_full()
4539            .overflow_hidden()
4540            .bg(cx.theme().colors().panel_background)
4541            .child(
4542                v_flex()
4543                    .size_full()
4544                    .children(self.render_panel_header(window, cx))
4545                    .map(|this| {
4546                        if has_entries {
4547                            this.child(self.render_entries(has_write_access, window, cx))
4548                        } else {
4549                            this.child(self.render_empty_state(cx).into_any_element())
4550                        }
4551                    })
4552                    .children(self.render_footer(window, cx))
4553                    .when(self.amend_pending, |this| {
4554                        this.child(self.render_pending_amend(cx))
4555                    })
4556                    .when(!self.amend_pending, |this| {
4557                        this.children(self.render_previous_commit(cx))
4558                    })
4559                    .into_any_element(),
4560            )
4561            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4562                deferred(
4563                    anchored()
4564                        .position(*position)
4565                        .anchor(Corner::TopLeft)
4566                        .child(menu.clone()),
4567                )
4568                .with_priority(1)
4569            }))
4570    }
4571}
4572
4573impl Focusable for GitPanel {
4574    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4575        if self.entries.is_empty() {
4576            self.commit_editor.focus_handle(cx)
4577        } else {
4578            self.focus_handle.clone()
4579        }
4580    }
4581}
4582
4583impl EventEmitter<Event> for GitPanel {}
4584
4585impl EventEmitter<PanelEvent> for GitPanel {}
4586
4587pub(crate) struct GitPanelAddon {
4588    pub(crate) workspace: WeakEntity<Workspace>,
4589}
4590
4591impl editor::Addon for GitPanelAddon {
4592    fn to_any(&self) -> &dyn std::any::Any {
4593        self
4594    }
4595
4596    fn render_buffer_header_controls(
4597        &self,
4598        excerpt_info: &ExcerptInfo,
4599        window: &Window,
4600        cx: &App,
4601    ) -> Option<AnyElement> {
4602        let file = excerpt_info.buffer.file()?;
4603        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4604
4605        git_panel
4606            .read(cx)
4607            .render_buffer_header_controls(&git_panel, file, window, cx)
4608    }
4609}
4610
4611impl Panel for GitPanel {
4612    fn persistent_name() -> &'static str {
4613        "GitPanel"
4614    }
4615
4616    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4617        GitPanelSettings::get_global(cx).dock
4618    }
4619
4620    fn position_is_valid(&self, position: DockPosition) -> bool {
4621        matches!(position, DockPosition::Left | DockPosition::Right)
4622    }
4623
4624    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4625        settings::update_settings_file::<GitPanelSettings>(
4626            self.fs.clone(),
4627            cx,
4628            move |settings, _| settings.dock = Some(position),
4629        );
4630    }
4631
4632    fn size(&self, _: &Window, cx: &App) -> Pixels {
4633        self.width
4634            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4635    }
4636
4637    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4638        self.width = size;
4639        self.serialize(cx);
4640        cx.notify();
4641    }
4642
4643    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4644        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4645    }
4646
4647    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4648        Some("Git Panel")
4649    }
4650
4651    fn toggle_action(&self) -> Box<dyn Action> {
4652        Box::new(ToggleFocus)
4653    }
4654
4655    fn activation_priority(&self) -> u32 {
4656        2
4657    }
4658}
4659
4660impl PanelHeader for GitPanel {}
4661
4662struct GitPanelMessageTooltip {
4663    commit_tooltip: Option<Entity<CommitTooltip>>,
4664}
4665
4666impl GitPanelMessageTooltip {
4667    fn new(
4668        git_panel: Entity<GitPanel>,
4669        sha: SharedString,
4670        repository: Entity<Repository>,
4671        window: &mut Window,
4672        cx: &mut App,
4673    ) -> Entity<Self> {
4674        cx.new(|cx| {
4675            cx.spawn_in(window, async move |this, cx| {
4676                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4677                    (
4678                        git_panel.load_commit_details(sha.to_string(), cx),
4679                        git_panel.workspace.clone(),
4680                    )
4681                })?;
4682                let details = details.await?;
4683
4684                let commit_details = crate::commit_tooltip::CommitDetails {
4685                    sha: details.sha.clone(),
4686                    author_name: details.author_name.clone(),
4687                    author_email: details.author_email.clone(),
4688                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4689                    message: Some(ParsedCommitMessage {
4690                        message: details.message,
4691                        ..Default::default()
4692                    }),
4693                };
4694
4695                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4696                    this.commit_tooltip = Some(cx.new(move |cx| {
4697                        CommitTooltip::new(commit_details, repository, workspace, cx)
4698                    }));
4699                    cx.notify();
4700                })
4701            })
4702            .detach();
4703
4704            Self {
4705                commit_tooltip: None,
4706            }
4707        })
4708    }
4709}
4710
4711impl Render for GitPanelMessageTooltip {
4712    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4713        if let Some(commit_tooltip) = &self.commit_tooltip {
4714            commit_tooltip.clone().into_any_element()
4715        } else {
4716            gpui::Empty.into_any_element()
4717        }
4718    }
4719}
4720
4721#[derive(IntoElement, RegisterComponent)]
4722pub struct PanelRepoFooter {
4723    active_repository: SharedString,
4724    branch: Option<Branch>,
4725    head_commit: Option<CommitDetails>,
4726
4727    // Getting a GitPanel in previews will be difficult.
4728    //
4729    // For now just take an option here, and we won't bind handlers to buttons in previews.
4730    git_panel: Option<Entity<GitPanel>>,
4731}
4732
4733impl PanelRepoFooter {
4734    pub fn new(
4735        active_repository: SharedString,
4736        branch: Option<Branch>,
4737        head_commit: Option<CommitDetails>,
4738        git_panel: Option<Entity<GitPanel>>,
4739    ) -> Self {
4740        Self {
4741            active_repository,
4742            branch,
4743            head_commit,
4744            git_panel,
4745        }
4746    }
4747
4748    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4749        Self {
4750            active_repository,
4751            branch,
4752            head_commit: None,
4753            git_panel: None,
4754        }
4755    }
4756}
4757
4758impl RenderOnce for PanelRepoFooter {
4759    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4760        let project = self
4761            .git_panel
4762            .as_ref()
4763            .map(|panel| panel.read(cx).project.clone());
4764
4765        let repo = self
4766            .git_panel
4767            .as_ref()
4768            .and_then(|panel| panel.read(cx).active_repository.clone());
4769
4770        let single_repo = project
4771            .as_ref()
4772            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4773            .unwrap_or(true);
4774
4775        const MAX_BRANCH_LEN: usize = 16;
4776        const MAX_REPO_LEN: usize = 16;
4777        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4778        const MAX_SHORT_SHA_LEN: usize = 8;
4779
4780        let branch_name = self
4781            .branch
4782            .as_ref()
4783            .map(|branch| branch.name().to_owned())
4784            .or_else(|| {
4785                self.head_commit.as_ref().map(|commit| {
4786                    commit
4787                        .sha
4788                        .chars()
4789                        .take(MAX_SHORT_SHA_LEN)
4790                        .collect::<String>()
4791                })
4792            })
4793            .unwrap_or_else(|| " (no branch)".to_owned());
4794        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4795
4796        let active_repo_name = self.active_repository.clone();
4797
4798        let branch_actual_len = branch_name.len();
4799        let repo_actual_len = active_repo_name.len();
4800
4801        // ideally, show the whole branch and repo names but
4802        // when we can't, use a budget to allocate space between the two
4803        let (repo_display_len, branch_display_len) =
4804            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4805                (repo_actual_len, branch_actual_len)
4806            } else if branch_actual_len <= MAX_BRANCH_LEN {
4807                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4808                (repo_space, branch_actual_len)
4809            } else if repo_actual_len <= MAX_REPO_LEN {
4810                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4811                (repo_actual_len, branch_space)
4812            } else {
4813                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4814            };
4815
4816        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4817            active_repo_name.to_string()
4818        } else {
4819            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4820        };
4821
4822        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4823            branch_name
4824        } else {
4825            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4826        };
4827
4828        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4829            .style(ButtonStyle::Transparent)
4830            .size(ButtonSize::None)
4831            .label_size(LabelSize::Small)
4832            .color(Color::Muted);
4833
4834        let repo_selector = PopoverMenu::new("repository-switcher")
4835            .menu({
4836                let project = project;
4837                move |window, cx| {
4838                    let project = project.clone()?;
4839                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4840                }
4841            })
4842            .trigger_with_tooltip(
4843                repo_selector_trigger.disabled(single_repo).truncate(true),
4844                Tooltip::text("Switch Active Repository"),
4845            )
4846            .anchor(Corner::BottomLeft)
4847            .into_any_element();
4848
4849        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4850            .style(ButtonStyle::Transparent)
4851            .size(ButtonSize::None)
4852            .label_size(LabelSize::Small)
4853            .truncate(true)
4854            .tooltip(Tooltip::for_action_title(
4855                "Switch Branch",
4856                &zed_actions::git::Switch,
4857            ))
4858            .on_click(|_, window, cx| {
4859                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4860            });
4861
4862        let branch_selector = PopoverMenu::new("popover-button")
4863            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4864            .trigger_with_tooltip(
4865                branch_selector_button,
4866                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4867            )
4868            .anchor(Corner::BottomLeft)
4869            .offset(gpui::Point {
4870                x: px(0.0),
4871                y: px(-2.0),
4872            });
4873
4874        h_flex()
4875            .w_full()
4876            .px_2()
4877            .h(px(36.))
4878            .items_center()
4879            .justify_between()
4880            .gap_1()
4881            .child(
4882                h_flex()
4883                    .flex_1()
4884                    .overflow_hidden()
4885                    .items_center()
4886                    .child(
4887                        div().child(
4888                            Icon::new(IconName::GitBranchAlt)
4889                                .size(IconSize::Small)
4890                                .color(if single_repo {
4891                                    Color::Disabled
4892                                } else {
4893                                    Color::Muted
4894                                }),
4895                        ),
4896                    )
4897                    .child(repo_selector)
4898                    .when(show_separator, |this| {
4899                        this.child(
4900                            div()
4901                                .text_color(cx.theme().colors().text_muted)
4902                                .text_sm()
4903                                .child("/"),
4904                        )
4905                    })
4906                    .child(branch_selector),
4907            )
4908            .children(if let Some(git_panel) = self.git_panel {
4909                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4910            } else {
4911                None
4912            })
4913    }
4914}
4915
4916impl Component for PanelRepoFooter {
4917    fn scope() -> ComponentScope {
4918        ComponentScope::VersionControl
4919    }
4920
4921    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4922        let unknown_upstream = None;
4923        let no_remote_upstream = Some(UpstreamTracking::Gone);
4924        let ahead_of_upstream = Some(
4925            UpstreamTrackingStatus {
4926                ahead: 2,
4927                behind: 0,
4928            }
4929            .into(),
4930        );
4931        let behind_upstream = Some(
4932            UpstreamTrackingStatus {
4933                ahead: 0,
4934                behind: 2,
4935            }
4936            .into(),
4937        );
4938        let ahead_and_behind_upstream = Some(
4939            UpstreamTrackingStatus {
4940                ahead: 3,
4941                behind: 1,
4942            }
4943            .into(),
4944        );
4945
4946        let not_ahead_or_behind_upstream = Some(
4947            UpstreamTrackingStatus {
4948                ahead: 0,
4949                behind: 0,
4950            }
4951            .into(),
4952        );
4953
4954        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4955            Branch {
4956                is_head: true,
4957                ref_name: "some-branch".into(),
4958                upstream: upstream.map(|tracking| Upstream {
4959                    ref_name: "origin/some-branch".into(),
4960                    tracking,
4961                }),
4962                most_recent_commit: Some(CommitSummary {
4963                    sha: "abc123".into(),
4964                    subject: "Modify stuff".into(),
4965                    commit_timestamp: 1710932954,
4966                    has_parent: true,
4967                }),
4968            }
4969        }
4970
4971        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4972            Branch {
4973                is_head: true,
4974                ref_name: branch_name.to_string().into(),
4975                upstream: upstream.map(|tracking| Upstream {
4976                    ref_name: format!("zed/{}", branch_name).into(),
4977                    tracking,
4978                }),
4979                most_recent_commit: Some(CommitSummary {
4980                    sha: "abc123".into(),
4981                    subject: "Modify stuff".into(),
4982                    commit_timestamp: 1710932954,
4983                    has_parent: true,
4984                }),
4985            }
4986        }
4987
4988        fn active_repository(id: usize) -> SharedString {
4989            format!("repo-{}", id).into()
4990        }
4991
4992        let example_width = px(340.);
4993        Some(
4994            v_flex()
4995                .gap_6()
4996                .w_full()
4997                .flex_none()
4998                .children(vec![
4999                    example_group_with_title(
5000                        "Action Button States",
5001                        vec![
5002                            single_example(
5003                                "No Branch",
5004                                div()
5005                                    .w(example_width)
5006                                    .overflow_hidden()
5007                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
5008                                    .into_any_element(),
5009                            ),
5010                            single_example(
5011                                "Remote status unknown",
5012                                div()
5013                                    .w(example_width)
5014                                    .overflow_hidden()
5015                                    .child(PanelRepoFooter::new_preview(
5016                                        active_repository(2),
5017                                        Some(branch(unknown_upstream)),
5018                                    ))
5019                                    .into_any_element(),
5020                            ),
5021                            single_example(
5022                                "No Remote Upstream",
5023                                div()
5024                                    .w(example_width)
5025                                    .overflow_hidden()
5026                                    .child(PanelRepoFooter::new_preview(
5027                                        active_repository(3),
5028                                        Some(branch(no_remote_upstream)),
5029                                    ))
5030                                    .into_any_element(),
5031                            ),
5032                            single_example(
5033                                "Not Ahead or Behind",
5034                                div()
5035                                    .w(example_width)
5036                                    .overflow_hidden()
5037                                    .child(PanelRepoFooter::new_preview(
5038                                        active_repository(4),
5039                                        Some(branch(not_ahead_or_behind_upstream)),
5040                                    ))
5041                                    .into_any_element(),
5042                            ),
5043                            single_example(
5044                                "Behind remote",
5045                                div()
5046                                    .w(example_width)
5047                                    .overflow_hidden()
5048                                    .child(PanelRepoFooter::new_preview(
5049                                        active_repository(5),
5050                                        Some(branch(behind_upstream)),
5051                                    ))
5052                                    .into_any_element(),
5053                            ),
5054                            single_example(
5055                                "Ahead of remote",
5056                                div()
5057                                    .w(example_width)
5058                                    .overflow_hidden()
5059                                    .child(PanelRepoFooter::new_preview(
5060                                        active_repository(6),
5061                                        Some(branch(ahead_of_upstream)),
5062                                    ))
5063                                    .into_any_element(),
5064                            ),
5065                            single_example(
5066                                "Ahead and behind remote",
5067                                div()
5068                                    .w(example_width)
5069                                    .overflow_hidden()
5070                                    .child(PanelRepoFooter::new_preview(
5071                                        active_repository(7),
5072                                        Some(branch(ahead_and_behind_upstream)),
5073                                    ))
5074                                    .into_any_element(),
5075                            ),
5076                        ],
5077                    )
5078                    .grow()
5079                    .vertical(),
5080                ])
5081                .children(vec![
5082                    example_group_with_title(
5083                        "Labels",
5084                        vec![
5085                            single_example(
5086                                "Short Branch & Repo",
5087                                div()
5088                                    .w(example_width)
5089                                    .overflow_hidden()
5090                                    .child(PanelRepoFooter::new_preview(
5091                                        SharedString::from("zed"),
5092                                        Some(custom("main", behind_upstream)),
5093                                    ))
5094                                    .into_any_element(),
5095                            ),
5096                            single_example(
5097                                "Long Branch",
5098                                div()
5099                                    .w(example_width)
5100                                    .overflow_hidden()
5101                                    .child(PanelRepoFooter::new_preview(
5102                                        SharedString::from("zed"),
5103                                        Some(custom(
5104                                            "redesign-and-update-git-ui-list-entry-style",
5105                                            behind_upstream,
5106                                        )),
5107                                    ))
5108                                    .into_any_element(),
5109                            ),
5110                            single_example(
5111                                "Long Repo",
5112                                div()
5113                                    .w(example_width)
5114                                    .overflow_hidden()
5115                                    .child(PanelRepoFooter::new_preview(
5116                                        SharedString::from("zed-industries-community-examples"),
5117                                        Some(custom("gpui", ahead_of_upstream)),
5118                                    ))
5119                                    .into_any_element(),
5120                            ),
5121                            single_example(
5122                                "Long Repo & Branch",
5123                                div()
5124                                    .w(example_width)
5125                                    .overflow_hidden()
5126                                    .child(PanelRepoFooter::new_preview(
5127                                        SharedString::from("zed-industries-community-examples"),
5128                                        Some(custom(
5129                                            "redesign-and-update-git-ui-list-entry-style",
5130                                            behind_upstream,
5131                                        )),
5132                                    ))
5133                                    .into_any_element(),
5134                            ),
5135                            single_example(
5136                                "Uppercase Repo",
5137                                div()
5138                                    .w(example_width)
5139                                    .overflow_hidden()
5140                                    .child(PanelRepoFooter::new_preview(
5141                                        SharedString::from("LICENSES"),
5142                                        Some(custom("main", ahead_of_upstream)),
5143                                    ))
5144                                    .into_any_element(),
5145                            ),
5146                            single_example(
5147                                "Uppercase Branch",
5148                                div()
5149                                    .w(example_width)
5150                                    .overflow_hidden()
5151                                    .child(PanelRepoFooter::new_preview(
5152                                        SharedString::from("zed"),
5153                                        Some(custom("update-README", behind_upstream)),
5154                                    ))
5155                                    .into_any_element(),
5156                            ),
5157                        ],
5158                    )
5159                    .grow()
5160                    .vertical(),
5161                ])
5162                .into_any_element(),
5163        )
5164    }
5165}
5166
5167#[cfg(test)]
5168mod tests {
5169    use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
5170    use gpui::{TestAppContext, VisualTestContext};
5171    use project::{FakeFs, WorktreeSettings};
5172    use serde_json::json;
5173    use settings::SettingsStore;
5174    use theme::LoadThemes;
5175    use util::path;
5176
5177    use super::*;
5178
5179    fn init_test(cx: &mut gpui::TestAppContext) {
5180        zlog::init_test();
5181
5182        cx.update(|cx| {
5183            let settings_store = SettingsStore::test(cx);
5184            cx.set_global(settings_store);
5185            AgentSettings::register(cx);
5186            WorktreeSettings::register(cx);
5187            workspace::init_settings(cx);
5188            theme::init(LoadThemes::JustBase, cx);
5189            language::init(cx);
5190            editor::init(cx);
5191            Project::init_settings(cx);
5192            crate::init(cx);
5193        });
5194    }
5195
5196    #[gpui::test]
5197    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5198        init_test(cx);
5199        let fs = FakeFs::new(cx.background_executor.clone());
5200        fs.insert_tree(
5201            "/root",
5202            json!({
5203                "zed": {
5204                    ".git": {},
5205                    "crates": {
5206                        "gpui": {
5207                            "gpui.rs": "fn main() {}"
5208                        },
5209                        "util": {
5210                            "util.rs": "fn do_it() {}"
5211                        }
5212                    }
5213                },
5214            }),
5215        )
5216        .await;
5217
5218        fs.set_status_for_repo(
5219            Path::new(path!("/root/zed/.git")),
5220            &[
5221                (
5222                    Path::new("crates/gpui/gpui.rs"),
5223                    StatusCode::Modified.worktree(),
5224                ),
5225                (
5226                    Path::new("crates/util/util.rs"),
5227                    StatusCode::Modified.worktree(),
5228                ),
5229            ],
5230        );
5231
5232        let project =
5233            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5234        let workspace =
5235            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5236        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5237
5238        cx.read(|cx| {
5239            project
5240                .read(cx)
5241                .worktrees(cx)
5242                .next()
5243                .unwrap()
5244                .read(cx)
5245                .as_local()
5246                .unwrap()
5247                .scan_complete()
5248        })
5249        .await;
5250
5251        cx.executor().run_until_parked();
5252
5253        let panel = workspace.update(cx, GitPanel::new).unwrap();
5254
5255        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5256            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5257        });
5258        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5259        handle.await;
5260
5261        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5262        pretty_assertions::assert_eq!(
5263            entries,
5264            [
5265                GitListEntry::Header(GitHeaderEntry {
5266                    header: Section::Tracked
5267                }),
5268                GitListEntry::Status(GitStatusEntry {
5269                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5270                    repo_path: "crates/gpui/gpui.rs".into(),
5271                    status: StatusCode::Modified.worktree(),
5272                    staging: StageStatus::Unstaged,
5273                }),
5274                GitListEntry::Status(GitStatusEntry {
5275                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5276                    repo_path: "crates/util/util.rs".into(),
5277                    status: StatusCode::Modified.worktree(),
5278                    staging: StageStatus::Unstaged,
5279                },),
5280            ],
5281        );
5282
5283        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5284            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5285        });
5286        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5287        handle.await;
5288        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5289        pretty_assertions::assert_eq!(
5290            entries,
5291            [
5292                GitListEntry::Header(GitHeaderEntry {
5293                    header: Section::Tracked
5294                }),
5295                GitListEntry::Status(GitStatusEntry {
5296                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5297                    repo_path: "crates/gpui/gpui.rs".into(),
5298                    status: StatusCode::Modified.worktree(),
5299                    staging: StageStatus::Unstaged,
5300                }),
5301                GitListEntry::Status(GitStatusEntry {
5302                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5303                    repo_path: "crates/util/util.rs".into(),
5304                    status: StatusCode::Modified.worktree(),
5305                    staging: StageStatus::Unstaged,
5306                },),
5307            ],
5308        );
5309    }
5310
5311    #[gpui::test]
5312    async fn test_bulk_staging(cx: &mut TestAppContext) {
5313        use GitListEntry::*;
5314
5315        init_test(cx);
5316        let fs = FakeFs::new(cx.background_executor.clone());
5317        fs.insert_tree(
5318            "/root",
5319            json!({
5320                "project": {
5321                    ".git": {},
5322                    "src": {
5323                        "main.rs": "fn main() {}",
5324                        "lib.rs": "pub fn hello() {}",
5325                        "utils.rs": "pub fn util() {}"
5326                    },
5327                    "tests": {
5328                        "test.rs": "fn test() {}"
5329                    },
5330                    "new_file.txt": "new content",
5331                    "another_new.rs": "// new file",
5332                    "conflict.txt": "conflicted content"
5333                }
5334            }),
5335        )
5336        .await;
5337
5338        fs.set_status_for_repo(
5339            Path::new(path!("/root/project/.git")),
5340            &[
5341                (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5342                (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5343                (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5344                (Path::new("new_file.txt"), FileStatus::Untracked),
5345                (Path::new("another_new.rs"), FileStatus::Untracked),
5346                (Path::new("src/utils.rs"), FileStatus::Untracked),
5347                (
5348                    Path::new("conflict.txt"),
5349                    UnmergedStatus {
5350                        first_head: UnmergedStatusCode::Updated,
5351                        second_head: UnmergedStatusCode::Updated,
5352                    }
5353                    .into(),
5354                ),
5355            ],
5356        );
5357
5358        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5359        let workspace =
5360            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5361        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5362
5363        cx.read(|cx| {
5364            project
5365                .read(cx)
5366                .worktrees(cx)
5367                .next()
5368                .unwrap()
5369                .read(cx)
5370                .as_local()
5371                .unwrap()
5372                .scan_complete()
5373        })
5374        .await;
5375
5376        cx.executor().run_until_parked();
5377
5378        let panel = workspace.update(cx, GitPanel::new).unwrap();
5379
5380        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5381            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5382        });
5383        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5384        handle.await;
5385
5386        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5387        #[rustfmt::skip]
5388        pretty_assertions::assert_matches!(
5389            entries.as_slice(),
5390            &[
5391                Header(GitHeaderEntry { header: Section::Conflict }),
5392                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5393                Header(GitHeaderEntry { header: Section::Tracked }),
5394                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5395                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5396                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5397                Header(GitHeaderEntry { header: Section::New }),
5398                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5399                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5400                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5401            ],
5402        );
5403
5404        let second_status_entry = entries[3].clone();
5405        panel.update_in(cx, |panel, window, cx| {
5406            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5407        });
5408
5409        panel.update_in(cx, |panel, window, cx| {
5410            panel.selected_entry = Some(7);
5411            panel.stage_range(&git::StageRange, window, cx);
5412        });
5413
5414        cx.read(|cx| {
5415            project
5416                .read(cx)
5417                .worktrees(cx)
5418                .next()
5419                .unwrap()
5420                .read(cx)
5421                .as_local()
5422                .unwrap()
5423                .scan_complete()
5424        })
5425        .await;
5426
5427        cx.executor().run_until_parked();
5428
5429        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5430            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5431        });
5432        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5433        handle.await;
5434
5435        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5436        #[rustfmt::skip]
5437        pretty_assertions::assert_matches!(
5438            entries.as_slice(),
5439            &[
5440                Header(GitHeaderEntry { header: Section::Conflict }),
5441                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5442                Header(GitHeaderEntry { header: Section::Tracked }),
5443                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5444                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5445                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5446                Header(GitHeaderEntry { header: Section::New }),
5447                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5448                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5449                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5450            ],
5451        );
5452
5453        let third_status_entry = entries[4].clone();
5454        panel.update_in(cx, |panel, window, cx| {
5455            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5456        });
5457
5458        panel.update_in(cx, |panel, window, cx| {
5459            panel.selected_entry = Some(9);
5460            panel.stage_range(&git::StageRange, window, cx);
5461        });
5462
5463        cx.read(|cx| {
5464            project
5465                .read(cx)
5466                .worktrees(cx)
5467                .next()
5468                .unwrap()
5469                .read(cx)
5470                .as_local()
5471                .unwrap()
5472                .scan_complete()
5473        })
5474        .await;
5475
5476        cx.executor().run_until_parked();
5477
5478        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5479            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5480        });
5481        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5482        handle.await;
5483
5484        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5485        #[rustfmt::skip]
5486        pretty_assertions::assert_matches!(
5487            entries.as_slice(),
5488            &[
5489                Header(GitHeaderEntry { header: Section::Conflict }),
5490                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5491                Header(GitHeaderEntry { header: Section::Tracked }),
5492                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5493                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5494                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5495                Header(GitHeaderEntry { header: Section::New }),
5496                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5497                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5498                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5499            ],
5500        );
5501    }
5502}