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