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