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.commit_changes(
1566                        CommitOptions {
1567                            amend: true,
1568                            signoff: self.signoff_enabled,
1569                        },
1570                        window,
1571                        cx,
1572                    );
1573                }
1574            }
1575        } else {
1576            cx.propagate();
1577        }
1578    }
1579
1580    pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
1581        self.active_repository
1582            .as_ref()
1583            .and_then(|repo| repo.read(cx).head_commit.as_ref())
1584            .cloned()
1585    }
1586
1587    pub fn load_last_commit_message_if_empty(&mut self, cx: &mut Context<Self>) {
1588        if !self.commit_editor.read(cx).is_empty(cx) {
1589            return;
1590        }
1591        let Some(head_commit) = self.head_commit(cx) else {
1592            return;
1593        };
1594        let recent_sha = head_commit.sha.to_string();
1595        let detail_task = self.load_commit_details(recent_sha, cx);
1596        cx.spawn(async move |this, cx| {
1597            if let Ok(message) = detail_task.await.map(|detail| detail.message) {
1598                this.update(cx, |this, cx| {
1599                    this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1600                        let start = buffer.anchor_before(0);
1601                        let end = buffer.anchor_after(buffer.len());
1602                        buffer.edit([(start..end, message)], None, cx);
1603                    });
1604                })
1605                .log_err();
1606            }
1607        })
1608        .detach();
1609    }
1610
1611    fn custom_or_suggested_commit_message(
1612        &self,
1613        window: &mut Window,
1614        cx: &mut Context<Self>,
1615    ) -> Option<String> {
1616        let git_commit_language = self.commit_editor.read(cx).language_at(0, cx);
1617        let message = self.commit_editor.read(cx).text(cx);
1618        if message.is_empty() {
1619            return self
1620                .suggest_commit_message(cx)
1621                .filter(|message| !message.trim().is_empty());
1622        } else if message.trim().is_empty() {
1623            return None;
1624        }
1625        let buffer = cx.new(|cx| {
1626            let mut buffer = Buffer::local(message, cx);
1627            buffer.set_language(git_commit_language, cx);
1628            buffer
1629        });
1630        let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
1631        let wrapped_message = editor.update(cx, |editor, cx| {
1632            editor.select_all(&Default::default(), window, cx);
1633            editor.rewrap(&Default::default(), window, cx);
1634            editor.text(cx)
1635        });
1636        if wrapped_message.trim().is_empty() {
1637            return None;
1638        }
1639        Some(wrapped_message)
1640    }
1641
1642    fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
1643        let text = self.commit_editor.read(cx).text(cx);
1644        if !text.trim().is_empty() {
1645            true
1646        } else if text.is_empty() {
1647            self.suggest_commit_message(cx)
1648                .is_some_and(|text| !text.trim().is_empty())
1649        } else {
1650            false
1651        }
1652    }
1653
1654    pub(crate) fn commit_changes(
1655        &mut self,
1656        options: CommitOptions,
1657        window: &mut Window,
1658        cx: &mut Context<Self>,
1659    ) {
1660        let Some(active_repository) = self.active_repository.clone() else {
1661            return;
1662        };
1663        let error_spawn = |message, window: &mut Window, cx: &mut App| {
1664            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1665            cx.spawn(async move |_| {
1666                prompt.await.ok();
1667            })
1668            .detach();
1669        };
1670
1671        if self.has_unstaged_conflicts() {
1672            error_spawn(
1673                "There are still conflicts. You must stage these before committing",
1674                window,
1675                cx,
1676            );
1677            return;
1678        }
1679
1680        let commit_message = self.custom_or_suggested_commit_message(window, cx);
1681
1682        let Some(mut message) = commit_message else {
1683            self.commit_editor.read(cx).focus_handle(cx).focus(window);
1684            return;
1685        };
1686
1687        if self.add_coauthors {
1688            self.fill_co_authors(&mut message, cx);
1689        }
1690
1691        let task = if self.has_staged_changes() {
1692            // Repository serializes all git operations, so we can just send a commit immediately
1693            let commit_task = active_repository.update(cx, |repo, cx| {
1694                repo.commit(message.into(), None, options, cx)
1695            });
1696            cx.background_spawn(async move { commit_task.await? })
1697        } else {
1698            let changed_files = self
1699                .entries
1700                .iter()
1701                .filter_map(|entry| entry.status_entry())
1702                .filter(|status_entry| !status_entry.status.is_created())
1703                .map(|status_entry| status_entry.repo_path.clone())
1704                .collect::<Vec<_>>();
1705
1706            if changed_files.is_empty() {
1707                error_spawn("No changes to commit", window, cx);
1708                return;
1709            }
1710
1711            let stage_task =
1712                active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1713            cx.spawn(async move |_, cx| {
1714                stage_task.await?;
1715                let commit_task = active_repository.update(cx, |repo, cx| {
1716                    repo.commit(message.into(), None, options, cx)
1717                })?;
1718                commit_task.await?
1719            })
1720        };
1721        let task = cx.spawn_in(window, async move |this, cx| {
1722            let result = task.await;
1723            this.update_in(cx, |this, window, cx| {
1724                this.pending_commit.take();
1725                match result {
1726                    Ok(()) => {
1727                        this.commit_editor
1728                            .update(cx, |editor, cx| editor.clear(window, cx));
1729                        this.original_commit_message = None;
1730                    }
1731                    Err(e) => this.show_error_toast("commit", e, cx),
1732                }
1733            })
1734            .ok();
1735        });
1736
1737        self.pending_commit = Some(task);
1738        if options.amend {
1739            self.set_amend_pending(false, cx);
1740        }
1741    }
1742
1743    pub(crate) fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1744        let Some(repo) = self.active_repository.clone() else {
1745            return;
1746        };
1747        telemetry::event!("Git Uncommitted");
1748
1749        let confirmation = self.check_for_pushed_commits(window, cx);
1750        let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1751
1752        let task = cx.spawn_in(window, async move |this, cx| {
1753            let result = maybe!(async {
1754                if let Ok(true) = confirmation.await {
1755                    let prior_head = prior_head.await?;
1756
1757                    repo.update(cx, |repo, cx| {
1758                        repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1759                    })?
1760                    .await??;
1761
1762                    Ok(Some(prior_head))
1763                } else {
1764                    Ok(None)
1765                }
1766            })
1767            .await;
1768
1769            this.update_in(cx, |this, window, cx| {
1770                this.pending_commit.take();
1771                match result {
1772                    Ok(None) => {}
1773                    Ok(Some(prior_commit)) => {
1774                        this.commit_editor.update(cx, |editor, cx| {
1775                            editor.set_text(prior_commit.message, window, cx)
1776                        });
1777                    }
1778                    Err(e) => this.show_error_toast("reset", e, cx),
1779                }
1780            })
1781            .ok();
1782        });
1783
1784        self.pending_commit = Some(task);
1785    }
1786
1787    fn check_for_pushed_commits(
1788        &mut self,
1789        window: &mut Window,
1790        cx: &mut Context<Self>,
1791    ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
1792        let repo = self.active_repository.clone();
1793        let mut cx = window.to_async(cx);
1794
1795        async move {
1796            let repo = repo.context("No active repository")?;
1797
1798            let pushed_to: Vec<SharedString> = repo
1799                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1800                .await??;
1801
1802            if pushed_to.is_empty() {
1803                Ok(true)
1804            } else {
1805                #[derive(strum::EnumIter, strum::VariantNames)]
1806                #[strum(serialize_all = "title_case")]
1807                enum CancelUncommit {
1808                    Uncommit,
1809                    Cancel,
1810                }
1811                let detail = format!(
1812                    "This commit was already pushed to {}.",
1813                    pushed_to.into_iter().join(", ")
1814                );
1815                let result = cx
1816                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1817                    .await?;
1818
1819                match result {
1820                    CancelUncommit::Cancel => Ok(false),
1821                    CancelUncommit::Uncommit => Ok(true),
1822                }
1823            }
1824        }
1825    }
1826
1827    /// Suggests a commit message based on the changed files and their statuses
1828    pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
1829        if let Some(merge_message) = self
1830            .active_repository
1831            .as_ref()
1832            .and_then(|repo| repo.read(cx).merge.message.as_ref())
1833        {
1834            return Some(merge_message.to_string());
1835        }
1836
1837        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1838            Some(staged_entry)
1839        } else if self.total_staged_count() == 0
1840            && let Some(single_tracked_entry) = &self.single_tracked_entry
1841        {
1842            Some(single_tracked_entry)
1843        } else {
1844            None
1845        }?;
1846
1847        let action_text = if git_status_entry.status.is_deleted() {
1848            Some("Delete")
1849        } else if git_status_entry.status.is_created() {
1850            Some("Create")
1851        } else if git_status_entry.status.is_modified() {
1852            Some("Update")
1853        } else {
1854            None
1855        }?;
1856
1857        let file_name = git_status_entry
1858            .repo_path
1859            .file_name()
1860            .unwrap_or_default()
1861            .to_string_lossy();
1862
1863        Some(format!("{} {}", action_text, file_name))
1864    }
1865
1866    fn generate_commit_message_action(
1867        &mut self,
1868        _: &git::GenerateCommitMessage,
1869        _window: &mut Window,
1870        cx: &mut Context<Self>,
1871    ) {
1872        self.generate_commit_message(cx);
1873    }
1874
1875    /// Generates a commit message using an LLM.
1876    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1877        if !self.can_commit()
1878            || DisableAiSettings::get_global(cx).disable_ai
1879            || !agent_settings::AgentSettings::get_global(cx).enabled
1880        {
1881            return;
1882        }
1883
1884        let Some(ConfiguredModel { provider, model }) =
1885            LanguageModelRegistry::read_global(cx).commit_message_model()
1886        else {
1887            return;
1888        };
1889
1890        let Some(repo) = self.active_repository.as_ref() else {
1891            return;
1892        };
1893
1894        telemetry::event!("Git Commit Message Generated");
1895
1896        let diff = repo.update(cx, |repo, cx| {
1897            if self.has_staged_changes() {
1898                repo.diff(DiffType::HeadToIndex, cx)
1899            } else {
1900                repo.diff(DiffType::HeadToWorktree, cx)
1901            }
1902        });
1903
1904        let temperature = AgentSettings::temperature_for_model(&model, cx);
1905
1906        self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1907             async move {
1908                let _defer = cx.on_drop(&this, |this, _cx| {
1909                    this.generate_commit_message_task.take();
1910                });
1911
1912                if let Some(task) = cx.update(|cx| {
1913                    if !provider.is_authenticated(cx) {
1914                        Some(provider.authenticate(cx))
1915                    } else {
1916                        None
1917                    }
1918                })? {
1919                    task.await.log_err();
1920                };
1921
1922                let mut diff_text = match diff.await {
1923                    Ok(result) => match result {
1924                        Ok(text) => text,
1925                        Err(e) => {
1926                            Self::show_commit_message_error(&this, &e, cx);
1927                            return anyhow::Ok(());
1928                        }
1929                    },
1930                    Err(e) => {
1931                        Self::show_commit_message_error(&this, &e, cx);
1932                        return anyhow::Ok(());
1933                    }
1934                };
1935
1936                const ONE_MB: usize = 1_000_000;
1937                if diff_text.len() > ONE_MB {
1938                    diff_text = diff_text.chars().take(ONE_MB).collect()
1939                }
1940
1941                let subject = this.update(cx, |this, cx| {
1942                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1943                })?;
1944
1945                let text_empty = subject.trim().is_empty();
1946
1947                let content = if text_empty {
1948                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1949                } else {
1950                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1951                };
1952
1953                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1954
1955                let request = LanguageModelRequest {
1956                    thread_id: None,
1957                    prompt_id: None,
1958                    intent: Some(CompletionIntent::GenerateGitCommitMessage),
1959                    mode: None,
1960                    messages: vec![LanguageModelRequestMessage {
1961                        role: Role::User,
1962                        content: vec![content.into()],
1963                        cache: false,
1964                    }],
1965                    tools: Vec::new(),
1966                    tool_choice: None,
1967                    stop: Vec::new(),
1968                    temperature,
1969                    thinking_allowed: false,
1970                };
1971
1972                let stream = model.stream_completion_text(request, cx);
1973                match stream.await {
1974                    Ok(mut messages) => {
1975                        if !text_empty {
1976                            this.update(cx, |this, cx| {
1977                                this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1978                                    let insert_position = buffer.anchor_before(buffer.len());
1979                                    buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1980                                });
1981                            })?;
1982                        }
1983
1984                        while let Some(message) = messages.stream.next().await {
1985                            match message {
1986                                Ok(text) => {
1987                                    this.update(cx, |this, cx| {
1988                                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1989                                            let insert_position = buffer.anchor_before(buffer.len());
1990                                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1991                                        });
1992                                    })?;
1993                                }
1994                                Err(e) => {
1995                                    Self::show_commit_message_error(&this, &e, cx);
1996                                    break;
1997                                }
1998                            }
1999                        }
2000                    }
2001                    Err(e) => {
2002                        Self::show_commit_message_error(&this, &e, cx);
2003                    }
2004                }
2005
2006                anyhow::Ok(())
2007            }
2008            .log_err().await
2009        }));
2010    }
2011
2012    fn get_fetch_options(
2013        &self,
2014        window: &mut Window,
2015        cx: &mut Context<Self>,
2016    ) -> Task<Option<FetchOptions>> {
2017        let repo = self.active_repository.clone();
2018        let workspace = self.workspace.clone();
2019
2020        cx.spawn_in(window, async move |_, cx| {
2021            let repo = repo?;
2022            let remotes = repo
2023                .update(cx, |repo, _| repo.get_remotes(None))
2024                .ok()?
2025                .await
2026                .ok()?
2027                .log_err()?;
2028
2029            let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
2030            if remotes.len() > 1 {
2031                remotes.push(FetchOptions::All);
2032            }
2033            let selection = cx
2034                .update(|window, cx| {
2035                    picker_prompt::prompt(
2036                        "Pick which remote to fetch",
2037                        remotes.iter().map(|r| r.name()).collect(),
2038                        workspace,
2039                        window,
2040                        cx,
2041                    )
2042                })
2043                .ok()?
2044                .await?;
2045            remotes.get(selection).cloned()
2046        })
2047    }
2048
2049    pub(crate) fn fetch(
2050        &mut self,
2051        is_fetch_all: bool,
2052        window: &mut Window,
2053        cx: &mut Context<Self>,
2054    ) {
2055        if !self.can_push_and_pull(cx) {
2056            return;
2057        }
2058
2059        let Some(repo) = self.active_repository.clone() else {
2060            return;
2061        };
2062        telemetry::event!("Git Fetched");
2063        let askpass = self.askpass_delegate("git fetch", window, cx);
2064        let this = cx.weak_entity();
2065
2066        let fetch_options = if is_fetch_all {
2067            Task::ready(Some(FetchOptions::All))
2068        } else {
2069            self.get_fetch_options(window, cx)
2070        };
2071
2072        window
2073            .spawn(cx, async move |cx| {
2074                let Some(fetch_options) = fetch_options.await else {
2075                    return Ok(());
2076                };
2077                let fetch = repo.update(cx, |repo, cx| {
2078                    repo.fetch(fetch_options.clone(), askpass, cx)
2079                })?;
2080
2081                let remote_message = fetch.await?;
2082                this.update(cx, |this, cx| {
2083                    let action = match fetch_options {
2084                        FetchOptions::All => RemoteAction::Fetch(None),
2085                        FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2086                    };
2087                    match remote_message {
2088                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2089                        Err(e) => {
2090                            log::error!("Error while fetching {:?}", e);
2091                            this.show_error_toast(action.name(), e, cx)
2092                        }
2093                    }
2094
2095                    anyhow::Ok(())
2096                })
2097                .ok();
2098                anyhow::Ok(())
2099            })
2100            .detach_and_log_err(cx);
2101    }
2102
2103    pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
2104        let path = cx.prompt_for_paths(gpui::PathPromptOptions {
2105            files: false,
2106            directories: true,
2107            multiple: false,
2108            prompt: Some("Select as Repository Destination".into()),
2109        });
2110
2111        let workspace = self.workspace.clone();
2112
2113        cx.spawn_in(window, async move |this, cx| {
2114            let mut paths = path.await.ok()?.ok()??;
2115            let mut path = paths.pop()?;
2116            let repo_name = repo
2117                .split(std::path::MAIN_SEPARATOR_STR)
2118                .last()?
2119                .strip_suffix(".git")?
2120                .to_owned();
2121
2122            let fs = this.read_with(cx, |this, _| this.fs.clone()).ok()?;
2123
2124            let prompt_answer = match fs.git_clone(&repo, path.as_path()).await {
2125                Ok(_) => cx.update(|window, cx| {
2126                    window.prompt(
2127                        PromptLevel::Info,
2128                        &format!("Git Clone: {}", repo_name),
2129                        None,
2130                        &["Add repo to project", "Open repo in new project"],
2131                        cx,
2132                    )
2133                }),
2134                Err(e) => {
2135                    this.update(cx, |this: &mut GitPanel, cx| {
2136                        let toast = StatusToast::new(e.to_string(), cx, |this, _| {
2137                            this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2138                                .dismiss_button(true)
2139                        });
2140
2141                        this.workspace
2142                            .update(cx, |workspace, cx| {
2143                                workspace.toggle_status_toast(toast, cx);
2144                            })
2145                            .ok();
2146                    })
2147                    .ok()?;
2148
2149                    return None;
2150                }
2151            }
2152            .ok()?;
2153
2154            path.push(repo_name);
2155            match prompt_answer.await.ok()? {
2156                0 => {
2157                    workspace
2158                        .update(cx, |workspace, cx| {
2159                            workspace
2160                                .project()
2161                                .update(cx, |project, cx| {
2162                                    project.create_worktree(path.as_path(), true, cx)
2163                                })
2164                                .detach();
2165                        })
2166                        .ok();
2167                }
2168                1 => {
2169                    workspace
2170                        .update(cx, move |workspace, cx| {
2171                            workspace::open_new(
2172                                Default::default(),
2173                                workspace.app_state().clone(),
2174                                cx,
2175                                move |workspace, _, cx| {
2176                                    cx.activate(true);
2177                                    workspace
2178                                        .project()
2179                                        .update(cx, |project, cx| {
2180                                            project.create_worktree(&path, true, cx)
2181                                        })
2182                                        .detach();
2183                                },
2184                            )
2185                            .detach();
2186                        })
2187                        .ok();
2188                }
2189                _ => {}
2190            }
2191
2192            Some(())
2193        })
2194        .detach();
2195    }
2196
2197    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2198        let worktrees = self
2199            .project
2200            .read(cx)
2201            .visible_worktrees(cx)
2202            .collect::<Vec<_>>();
2203
2204        let worktree = if worktrees.len() == 1 {
2205            Task::ready(Some(worktrees.first().unwrap().clone()))
2206        } else if worktrees.is_empty() {
2207            let result = window.prompt(
2208                PromptLevel::Warning,
2209                "Unable to initialize a git repository",
2210                Some("Open a directory first"),
2211                &["Ok"],
2212                cx,
2213            );
2214            cx.background_executor()
2215                .spawn(async move {
2216                    result.await.ok();
2217                })
2218                .detach();
2219            return;
2220        } else {
2221            let worktree_directories = worktrees
2222                .iter()
2223                .map(|worktree| worktree.read(cx).abs_path())
2224                .map(|worktree_abs_path| {
2225                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2226                        Path::new("~")
2227                            .join(path)
2228                            .to_string_lossy()
2229                            .to_string()
2230                            .into()
2231                    } else {
2232                        worktree_abs_path.to_string_lossy().to_string().into()
2233                    }
2234                })
2235                .collect_vec();
2236            let prompt = picker_prompt::prompt(
2237                "Where would you like to initialize this git repository?",
2238                worktree_directories,
2239                self.workspace.clone(),
2240                window,
2241                cx,
2242            );
2243
2244            cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2245        };
2246
2247        cx.spawn_in(window, async move |this, cx| {
2248            let worktree = match worktree.await {
2249                Some(worktree) => worktree,
2250                None => {
2251                    return;
2252                }
2253            };
2254
2255            let Ok(result) = this.update(cx, |this, cx| {
2256                let fallback_branch_name = GitPanelSettings::get_global(cx)
2257                    .fallback_branch_name
2258                    .clone();
2259                this.project.read(cx).git_init(
2260                    worktree.read(cx).abs_path(),
2261                    fallback_branch_name,
2262                    cx,
2263                )
2264            }) else {
2265                return;
2266            };
2267
2268            let result = result.await;
2269
2270            this.update_in(cx, |this, _, cx| match result {
2271                Ok(()) => {}
2272                Err(e) => this.show_error_toast("init", e, cx),
2273            })
2274            .ok();
2275        })
2276        .detach();
2277    }
2278
2279    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2280        if !self.can_push_and_pull(cx) {
2281            return;
2282        }
2283        let Some(repo) = self.active_repository.clone() else {
2284            return;
2285        };
2286        let Some(branch) = repo.read(cx).branch.as_ref() else {
2287            return;
2288        };
2289        telemetry::event!("Git Pulled");
2290        let branch = branch.clone();
2291        let remote = self.get_remote(false, window, cx);
2292        cx.spawn_in(window, async move |this, cx| {
2293            let remote = match remote.await {
2294                Ok(Some(remote)) => remote,
2295                Ok(None) => {
2296                    return Ok(());
2297                }
2298                Err(e) => {
2299                    log::error!("Failed to get current remote: {}", e);
2300                    this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2301                        .ok();
2302                    return Ok(());
2303                }
2304            };
2305
2306            let askpass = this.update_in(cx, |this, window, cx| {
2307                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2308            })?;
2309
2310            let pull = repo.update(cx, |repo, cx| {
2311                repo.pull(
2312                    branch.name().to_owned().into(),
2313                    remote.name.clone(),
2314                    askpass,
2315                    cx,
2316                )
2317            })?;
2318
2319            let remote_message = pull.await?;
2320
2321            let action = RemoteAction::Pull(remote);
2322            this.update(cx, |this, cx| match remote_message {
2323                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2324                Err(e) => {
2325                    log::error!("Error while pulling {:?}", e);
2326                    this.show_error_toast(action.name(), e, cx)
2327                }
2328            })
2329            .ok();
2330
2331            anyhow::Ok(())
2332        })
2333        .detach_and_log_err(cx);
2334    }
2335
2336    pub(crate) fn push(
2337        &mut self,
2338        force_push: bool,
2339        select_remote: bool,
2340        window: &mut Window,
2341        cx: &mut Context<Self>,
2342    ) {
2343        if !self.can_push_and_pull(cx) {
2344            return;
2345        }
2346        let Some(repo) = self.active_repository.clone() else {
2347            return;
2348        };
2349        let Some(branch) = repo.read(cx).branch.as_ref() else {
2350            return;
2351        };
2352        telemetry::event!("Git Pushed");
2353        let branch = branch.clone();
2354
2355        let options = if force_push {
2356            Some(PushOptions::Force)
2357        } else {
2358            match branch.upstream {
2359                Some(Upstream {
2360                    tracking: UpstreamTracking::Gone,
2361                    ..
2362                })
2363                | None => Some(PushOptions::SetUpstream),
2364                _ => None,
2365            }
2366        };
2367        let remote = self.get_remote(select_remote, window, cx);
2368
2369        cx.spawn_in(window, async move |this, cx| {
2370            let remote = match remote.await {
2371                Ok(Some(remote)) => remote,
2372                Ok(None) => {
2373                    return Ok(());
2374                }
2375                Err(e) => {
2376                    log::error!("Failed to get current remote: {}", e);
2377                    this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2378                        .ok();
2379                    return Ok(());
2380                }
2381            };
2382
2383            let askpass_delegate = this.update_in(cx, |this, window, cx| {
2384                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2385            })?;
2386
2387            let push = repo.update(cx, |repo, cx| {
2388                repo.push(
2389                    branch.name().to_owned().into(),
2390                    remote.name.clone(),
2391                    options,
2392                    askpass_delegate,
2393                    cx,
2394                )
2395            })?;
2396
2397            let remote_output = push.await?;
2398
2399            let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2400            this.update(cx, |this, cx| match remote_output {
2401                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2402                Err(e) => {
2403                    log::error!("Error while pushing {:?}", e);
2404                    this.show_error_toast(action.name(), e, cx)
2405                }
2406            })?;
2407
2408            anyhow::Ok(())
2409        })
2410        .detach_and_log_err(cx);
2411    }
2412
2413    fn askpass_delegate(
2414        &self,
2415        operation: impl Into<SharedString>,
2416        window: &mut Window,
2417        cx: &mut Context<Self>,
2418    ) -> AskPassDelegate {
2419        let this = cx.weak_entity();
2420        let operation = operation.into();
2421        let window = window.window_handle();
2422        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2423            window
2424                .update(cx, |_, window, cx| {
2425                    this.update(cx, |this, cx| {
2426                        this.workspace.update(cx, |workspace, cx| {
2427                            workspace.toggle_modal(window, cx, |window, cx| {
2428                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2429                            });
2430                        })
2431                    })
2432                })
2433                .ok();
2434        })
2435    }
2436
2437    fn can_push_and_pull(&self, cx: &App) -> bool {
2438        !self.project.read(cx).is_via_collab()
2439    }
2440
2441    fn get_remote(
2442        &mut self,
2443        always_select: bool,
2444        window: &mut Window,
2445        cx: &mut Context<Self>,
2446    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2447        let repo = self.active_repository.clone();
2448        let workspace = self.workspace.clone();
2449        let mut cx = window.to_async(cx);
2450
2451        async move {
2452            let repo = repo.context("No active repository")?;
2453            let current_remotes: Vec<Remote> = repo
2454                .update(&mut cx, |repo, _| {
2455                    let current_branch = if always_select {
2456                        None
2457                    } else {
2458                        let current_branch = repo.branch.as_ref().context("No active branch")?;
2459                        Some(current_branch.name().to_string())
2460                    };
2461                    anyhow::Ok(repo.get_remotes(current_branch))
2462                })??
2463                .await??;
2464
2465            let current_remotes: Vec<_> = current_remotes
2466                .into_iter()
2467                .map(|remotes| remotes.name)
2468                .collect();
2469            let selection = cx
2470                .update(|window, cx| {
2471                    picker_prompt::prompt(
2472                        "Pick which remote to push to",
2473                        current_remotes.clone(),
2474                        workspace,
2475                        window,
2476                        cx,
2477                    )
2478                })?
2479                .await;
2480
2481            Ok(selection.map(|selection| Remote {
2482                name: current_remotes[selection].clone(),
2483            }))
2484        }
2485    }
2486
2487    pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2488        if self.local_committer_task.is_none() {
2489            self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2490                let committer = get_git_committer(cx).await;
2491                this.update(cx, |this, cx| {
2492                    this.local_committer = Some(committer);
2493                    cx.notify()
2494                })
2495                .ok();
2496            }));
2497        }
2498    }
2499
2500    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2501        let mut new_co_authors = Vec::new();
2502        let project = self.project.read(cx);
2503
2504        let Some(room) = self
2505            .workspace
2506            .upgrade()
2507            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2508        else {
2509            return Vec::default();
2510        };
2511
2512        let room = room.read(cx);
2513
2514        for (peer_id, collaborator) in project.collaborators() {
2515            if collaborator.is_host {
2516                continue;
2517            }
2518
2519            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2520                continue;
2521            };
2522            if !participant.can_write() {
2523                continue;
2524            }
2525            if let Some(email) = &collaborator.committer_email {
2526                let name = collaborator
2527                    .committer_name
2528                    .clone()
2529                    .or_else(|| participant.user.name.clone())
2530                    .unwrap_or_else(|| participant.user.github_login.clone().to_string());
2531                new_co_authors.push((name.clone(), email.clone()))
2532            }
2533        }
2534        if !project.is_local()
2535            && !project.is_read_only(cx)
2536            && let Some(local_committer) = self.local_committer(room, cx)
2537        {
2538            new_co_authors.push(local_committer);
2539        }
2540        new_co_authors
2541    }
2542
2543    fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2544        let user = room.local_participant_user(cx)?;
2545        let committer = self.local_committer.as_ref()?;
2546        let email = committer.email.clone()?;
2547        let name = committer
2548            .name
2549            .clone()
2550            .or_else(|| user.name.clone())
2551            .unwrap_or_else(|| user.github_login.clone().to_string());
2552        Some((name, email))
2553    }
2554
2555    fn toggle_fill_co_authors(
2556        &mut self,
2557        _: &ToggleFillCoAuthors,
2558        _: &mut Window,
2559        cx: &mut Context<Self>,
2560    ) {
2561        self.add_coauthors = !self.add_coauthors;
2562        cx.notify();
2563    }
2564
2565    fn toggle_sort_by_path(
2566        &mut self,
2567        _: &ToggleSortByPath,
2568        _: &mut Window,
2569        cx: &mut Context<Self>,
2570    ) {
2571        let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
2572        if let Some(workspace) = self.workspace.upgrade() {
2573            let workspace = workspace.read(cx);
2574            let fs = workspace.app_state().fs.clone();
2575            cx.update_global::<SettingsStore, _>(|store, _cx| {
2576                store.update_settings_file::<GitPanelSettings>(fs, move |settings, _cx| {
2577                    settings.sort_by_path = Some(!current_setting);
2578                });
2579            });
2580        }
2581    }
2582
2583    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2584        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2585
2586        let existing_text = message.to_ascii_lowercase();
2587        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2588        let mut ends_with_co_authors = false;
2589        let existing_co_authors = existing_text
2590            .lines()
2591            .filter_map(|line| {
2592                let line = line.trim();
2593                if line.starts_with(&lowercase_co_author_prefix) {
2594                    ends_with_co_authors = true;
2595                    Some(line)
2596                } else {
2597                    ends_with_co_authors = false;
2598                    None
2599                }
2600            })
2601            .collect::<HashSet<_>>();
2602
2603        let new_co_authors = self
2604            .potential_co_authors(cx)
2605            .into_iter()
2606            .filter(|(_, email)| {
2607                !existing_co_authors
2608                    .iter()
2609                    .any(|existing| existing.contains(email.as_str()))
2610            })
2611            .collect::<Vec<_>>();
2612
2613        if new_co_authors.is_empty() {
2614            return;
2615        }
2616
2617        if !ends_with_co_authors {
2618            message.push('\n');
2619        }
2620        for (name, email) in new_co_authors {
2621            message.push('\n');
2622            message.push_str(CO_AUTHOR_PREFIX);
2623            message.push_str(&name);
2624            message.push_str(" <");
2625            message.push_str(&email);
2626            message.push('>');
2627        }
2628        message.push('\n');
2629    }
2630
2631    fn schedule_update(
2632        &mut self,
2633        clear_pending: bool,
2634        window: &mut Window,
2635        cx: &mut Context<Self>,
2636    ) {
2637        let handle = cx.entity().downgrade();
2638        self.reopen_commit_buffer(window, cx);
2639        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2640            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2641            if let Some(git_panel) = handle.upgrade() {
2642                git_panel
2643                    .update_in(cx, |git_panel, window, cx| {
2644                        if clear_pending {
2645                            git_panel.clear_pending();
2646                        }
2647                        git_panel.update_visible_entries(cx);
2648                        git_panel.update_scrollbar_properties(window, cx);
2649                    })
2650                    .ok();
2651            }
2652        });
2653    }
2654
2655    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2656        let Some(active_repo) = self.active_repository.as_ref() else {
2657            return;
2658        };
2659        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2660            let project = self.project.read(cx);
2661            active_repo.open_commit_buffer(
2662                Some(project.languages().clone()),
2663                project.buffer_store().clone(),
2664                cx,
2665            )
2666        });
2667
2668        cx.spawn_in(window, async move |git_panel, cx| {
2669            let buffer = load_buffer.await?;
2670            git_panel.update_in(cx, |git_panel, window, cx| {
2671                if git_panel
2672                    .commit_editor
2673                    .read(cx)
2674                    .buffer()
2675                    .read(cx)
2676                    .as_singleton()
2677                    .as_ref()
2678                    != Some(&buffer)
2679                {
2680                    git_panel.commit_editor = cx.new(|cx| {
2681                        commit_message_editor(
2682                            buffer,
2683                            git_panel.suggest_commit_message(cx).map(SharedString::from),
2684                            git_panel.project.clone(),
2685                            true,
2686                            window,
2687                            cx,
2688                        )
2689                    });
2690                }
2691            })
2692        })
2693        .detach_and_log_err(cx);
2694    }
2695
2696    fn clear_pending(&mut self) {
2697        self.pending.retain(|v| !v.finished)
2698    }
2699
2700    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2701        let bulk_staging = self.bulk_staging.take();
2702        let last_staged_path_prev_index = bulk_staging
2703            .as_ref()
2704            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2705
2706        self.entries.clear();
2707        self.single_staged_entry.take();
2708        self.single_tracked_entry.take();
2709        self.conflicted_count = 0;
2710        self.conflicted_staged_count = 0;
2711        self.new_count = 0;
2712        self.tracked_count = 0;
2713        self.new_staged_count = 0;
2714        self.tracked_staged_count = 0;
2715        self.entry_count = 0;
2716
2717        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2718
2719        let mut changed_entries = Vec::new();
2720        let mut new_entries = Vec::new();
2721        let mut conflict_entries = Vec::new();
2722        let mut single_staged_entry = None;
2723        let mut staged_count = 0;
2724        let mut max_width_item: Option<(RepoPath, usize)> = None;
2725
2726        let Some(repo) = self.active_repository.as_ref() else {
2727            // Just clear entries if no repository is active.
2728            cx.notify();
2729            return;
2730        };
2731
2732        let repo = repo.read(cx);
2733
2734        for entry in repo.cached_status() {
2735            let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2736            let is_new = entry.status.is_created();
2737            let staging = entry.status.staging();
2738
2739            if self.pending.iter().any(|pending| {
2740                pending.target_status == TargetStatus::Reverted
2741                    && !pending.finished
2742                    && pending
2743                        .entries
2744                        .iter()
2745                        .any(|pending| pending.repo_path == entry.repo_path)
2746            }) {
2747                continue;
2748            }
2749
2750            let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2751            let entry = GitStatusEntry {
2752                repo_path: entry.repo_path.clone(),
2753                abs_path,
2754                status: entry.status,
2755                staging,
2756            };
2757
2758            if staging.has_staged() {
2759                staged_count += 1;
2760                single_staged_entry = Some(entry.clone());
2761            }
2762
2763            let width_estimate = Self::item_width_estimate(
2764                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2765                entry.display_name().len(),
2766            );
2767
2768            match max_width_item.as_mut() {
2769                Some((repo_path, estimate)) => {
2770                    if width_estimate > *estimate {
2771                        *repo_path = entry.repo_path.clone();
2772                        *estimate = width_estimate;
2773                    }
2774                }
2775                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2776            }
2777
2778            if sort_by_path {
2779                changed_entries.push(entry);
2780            } else if is_conflict {
2781                conflict_entries.push(entry);
2782            } else if is_new {
2783                new_entries.push(entry);
2784            } else {
2785                changed_entries.push(entry);
2786            }
2787        }
2788
2789        let mut pending_staged_count = 0;
2790        let mut last_pending_staged = None;
2791        let mut pending_status_for_single_staged = None;
2792        for pending in self.pending.iter() {
2793            if pending.target_status == TargetStatus::Staged {
2794                pending_staged_count += pending.entries.len();
2795                last_pending_staged = pending.entries.first().cloned();
2796            }
2797            if let Some(single_staged) = &single_staged_entry
2798                && pending
2799                    .entries
2800                    .iter()
2801                    .any(|entry| entry.repo_path == single_staged.repo_path)
2802            {
2803                pending_status_for_single_staged = Some(pending.target_status);
2804            }
2805        }
2806
2807        if conflict_entries.is_empty() && staged_count == 1 && pending_staged_count == 0 {
2808            match pending_status_for_single_staged {
2809                Some(TargetStatus::Staged) | None => {
2810                    self.single_staged_entry = single_staged_entry;
2811                }
2812                _ => {}
2813            }
2814        } else if conflict_entries.is_empty() && pending_staged_count == 1 {
2815            self.single_staged_entry = last_pending_staged;
2816        }
2817
2818        if conflict_entries.is_empty() && changed_entries.len() == 1 {
2819            self.single_tracked_entry = changed_entries.first().cloned();
2820        }
2821
2822        if !conflict_entries.is_empty() {
2823            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2824                header: Section::Conflict,
2825            }));
2826            self.entries
2827                .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2828        }
2829
2830        if !changed_entries.is_empty() {
2831            if !sort_by_path {
2832                self.entries.push(GitListEntry::Header(GitHeaderEntry {
2833                    header: Section::Tracked,
2834                }));
2835            }
2836            self.entries
2837                .extend(changed_entries.into_iter().map(GitListEntry::Status));
2838        }
2839        if !new_entries.is_empty() {
2840            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2841                header: Section::New,
2842            }));
2843            self.entries
2844                .extend(new_entries.into_iter().map(GitListEntry::Status));
2845        }
2846
2847        if let Some((repo_path, _)) = max_width_item {
2848            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2849                GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2850                GitListEntry::Header(_) => false,
2851            });
2852        }
2853
2854        self.update_counts(repo);
2855
2856        let bulk_staging_anchor_new_index = bulk_staging
2857            .as_ref()
2858            .filter(|op| op.repo_id == repo.id)
2859            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2860        if bulk_staging_anchor_new_index == last_staged_path_prev_index
2861            && let Some(index) = bulk_staging_anchor_new_index
2862            && let Some(entry) = self.entries.get(index)
2863            && let Some(entry) = entry.status_entry()
2864            && self.entry_staging(entry) == StageStatus::Staged
2865        {
2866            self.bulk_staging = bulk_staging;
2867        }
2868
2869        self.select_first_entry_if_none(cx);
2870
2871        let suggested_commit_message = self.suggest_commit_message(cx);
2872        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2873
2874        self.commit_editor.update(cx, |editor, cx| {
2875            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2876        });
2877
2878        cx.notify();
2879    }
2880
2881    fn header_state(&self, header_type: Section) -> ToggleState {
2882        let (staged_count, count) = match header_type {
2883            Section::New => (self.new_staged_count, self.new_count),
2884            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2885            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2886        };
2887        if staged_count == 0 {
2888            ToggleState::Unselected
2889        } else if count == staged_count {
2890            ToggleState::Selected
2891        } else {
2892            ToggleState::Indeterminate
2893        }
2894    }
2895
2896    fn update_counts(&mut self, repo: &Repository) {
2897        self.show_placeholders = false;
2898        self.conflicted_count = 0;
2899        self.conflicted_staged_count = 0;
2900        self.new_count = 0;
2901        self.tracked_count = 0;
2902        self.new_staged_count = 0;
2903        self.tracked_staged_count = 0;
2904        self.entry_count = 0;
2905        for entry in &self.entries {
2906            let Some(status_entry) = entry.status_entry() else {
2907                continue;
2908            };
2909            self.entry_count += 1;
2910            if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2911                self.conflicted_count += 1;
2912                if self.entry_staging(status_entry).has_staged() {
2913                    self.conflicted_staged_count += 1;
2914                }
2915            } else if status_entry.status.is_created() {
2916                self.new_count += 1;
2917                if self.entry_staging(status_entry).has_staged() {
2918                    self.new_staged_count += 1;
2919                }
2920            } else {
2921                self.tracked_count += 1;
2922                if self.entry_staging(status_entry).has_staged() {
2923                    self.tracked_staged_count += 1;
2924                }
2925            }
2926        }
2927    }
2928
2929    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2930        for pending in self.pending.iter().rev() {
2931            if pending
2932                .entries
2933                .iter()
2934                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2935            {
2936                match pending.target_status {
2937                    TargetStatus::Staged => return StageStatus::Staged,
2938                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2939                    TargetStatus::Reverted => continue,
2940                    TargetStatus::Unchanged => continue,
2941                }
2942            }
2943        }
2944        entry.staging
2945    }
2946
2947    pub(crate) fn has_staged_changes(&self) -> bool {
2948        self.tracked_staged_count > 0
2949            || self.new_staged_count > 0
2950            || self.conflicted_staged_count > 0
2951    }
2952
2953    pub(crate) fn has_unstaged_changes(&self) -> bool {
2954        self.tracked_count > self.tracked_staged_count
2955            || self.new_count > self.new_staged_count
2956            || self.conflicted_count > self.conflicted_staged_count
2957    }
2958
2959    fn has_tracked_changes(&self) -> bool {
2960        self.tracked_count > 0
2961    }
2962
2963    pub fn has_unstaged_conflicts(&self) -> bool {
2964        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2965    }
2966
2967    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2968        let action = action.into();
2969        let Some(workspace) = self.workspace.upgrade() else {
2970            return;
2971        };
2972
2973        let message = e.to_string().trim().to_string();
2974        if message
2975            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2976            .next()
2977            .is_some()
2978        { // Hide the cancelled by user message
2979        } else {
2980            workspace.update(cx, |workspace, cx| {
2981                let workspace_weak = cx.weak_entity();
2982                let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2983                    this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2984                        .action("View Log", move |window, cx| {
2985                            let message = message.clone();
2986                            let action = action.clone();
2987                            workspace_weak
2988                                .update(cx, move |workspace, cx| {
2989                                    Self::open_output(action, workspace, &message, window, cx)
2990                                })
2991                                .ok();
2992                        })
2993                });
2994                workspace.toggle_status_toast(toast, cx)
2995            });
2996        }
2997    }
2998
2999    fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3000    where
3001        E: std::fmt::Debug + std::fmt::Display,
3002    {
3003        if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3004            let _ = workspace.update(cx, |workspace, cx| {
3005                struct CommitMessageError;
3006                let notification_id = NotificationId::unique::<CommitMessageError>();
3007                workspace.show_notification(notification_id, cx, |cx| {
3008                    cx.new(|cx| {
3009                        ErrorMessagePrompt::new(
3010                            format!("Failed to generate commit message: {err}"),
3011                            cx,
3012                        )
3013                    })
3014                });
3015            });
3016        }
3017    }
3018
3019    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
3020        let Some(workspace) = self.workspace.upgrade() else {
3021            return;
3022        };
3023
3024        workspace.update(cx, |workspace, cx| {
3025            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3026            let workspace_weak = cx.weak_entity();
3027            let operation = action.name();
3028
3029            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3030                use remote_output::SuccessStyle::*;
3031                match style {
3032                    Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3033                    ToastWithLog { output } => this
3034                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3035                        .action("View Log", move |window, cx| {
3036                            let output = output.clone();
3037                            let output =
3038                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3039                            workspace_weak
3040                                .update(cx, move |workspace, cx| {
3041                                    Self::open_output(operation, workspace, &output, window, cx)
3042                                })
3043                                .ok();
3044                        }),
3045                    PushPrLink { text, link } => this
3046                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3047                        .action(text, move |_, cx| cx.open_url(&link)),
3048                }
3049            });
3050            workspace.toggle_status_toast(status_toast, cx)
3051        });
3052    }
3053
3054    fn open_output(
3055        operation: impl Into<SharedString>,
3056        workspace: &mut Workspace,
3057        output: &str,
3058        window: &mut Window,
3059        cx: &mut Context<Workspace>,
3060    ) {
3061        let operation = operation.into();
3062        let buffer = cx.new(|cx| Buffer::local(output, cx));
3063        buffer.update(cx, |buffer, cx| {
3064            buffer.set_capability(language::Capability::ReadOnly, cx);
3065        });
3066        let editor = cx.new(|cx| {
3067            let mut editor = Editor::for_buffer(buffer, None, window, cx);
3068            editor.buffer().update(cx, |buffer, cx| {
3069                buffer.set_title(format!("Output from git {operation}"), cx);
3070            });
3071            editor.set_read_only(true);
3072            editor
3073        });
3074
3075        workspace.add_item_to_center(Box::new(editor), window, cx);
3076    }
3077
3078    pub fn can_commit(&self) -> bool {
3079        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3080    }
3081
3082    pub fn can_stage_all(&self) -> bool {
3083        self.has_unstaged_changes()
3084    }
3085
3086    pub fn can_unstage_all(&self) -> bool {
3087        self.has_staged_changes()
3088    }
3089
3090    // eventually we'll need to take depth into account here
3091    // if we add a tree view
3092    fn item_width_estimate(path: usize, file_name: usize) -> usize {
3093        path + file_name
3094    }
3095
3096    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3097        let focus_handle = self.focus_handle.clone();
3098        let has_tracked_changes = self.has_tracked_changes();
3099        let has_staged_changes = self.has_staged_changes();
3100        let has_unstaged_changes = self.has_unstaged_changes();
3101        let has_new_changes = self.new_count > 0;
3102
3103        PopoverMenu::new(id.into())
3104            .trigger(
3105                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3106                    .icon_size(IconSize::Small)
3107                    .icon_color(Color::Muted),
3108            )
3109            .menu(move |window, cx| {
3110                Some(git_panel_context_menu(
3111                    focus_handle.clone(),
3112                    GitMenuState {
3113                        has_tracked_changes,
3114                        has_staged_changes,
3115                        has_unstaged_changes,
3116                        has_new_changes,
3117                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3118                    },
3119                    window,
3120                    cx,
3121                ))
3122            })
3123            .anchor(Corner::TopRight)
3124    }
3125
3126    pub(crate) fn render_generate_commit_message_button(
3127        &self,
3128        cx: &Context<Self>,
3129    ) -> Option<AnyElement> {
3130        if !agent_settings::AgentSettings::get_global(cx).enabled
3131            || DisableAiSettings::get_global(cx).disable_ai
3132            || LanguageModelRegistry::read_global(cx)
3133                .commit_message_model()
3134                .is_none()
3135        {
3136            return None;
3137        }
3138
3139        if self.generate_commit_message_task.is_some() {
3140            return Some(
3141                h_flex()
3142                    .gap_1()
3143                    .child(
3144                        Icon::new(IconName::ArrowCircle)
3145                            .size(IconSize::XSmall)
3146                            .color(Color::Info)
3147                            .with_rotate_animation(2),
3148                    )
3149                    .child(
3150                        Label::new("Generating Commit...")
3151                            .size(LabelSize::Small)
3152                            .color(Color::Muted),
3153                    )
3154                    .into_any_element(),
3155            );
3156        }
3157
3158        let can_commit = self.can_commit();
3159        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3160        Some(
3161            IconButton::new("generate-commit-message", IconName::AiEdit)
3162                .shape(ui::IconButtonShape::Square)
3163                .icon_color(Color::Muted)
3164                .tooltip(move |window, cx| {
3165                    if can_commit {
3166                        Tooltip::for_action_in(
3167                            "Generate Commit Message",
3168                            &git::GenerateCommitMessage,
3169                            &editor_focus_handle,
3170                            window,
3171                            cx,
3172                        )
3173                    } else {
3174                        Tooltip::simple("No changes to commit", cx)
3175                    }
3176                })
3177                .disabled(!can_commit)
3178                .on_click(cx.listener(move |this, _event, _window, cx| {
3179                    this.generate_commit_message(cx);
3180                }))
3181                .into_any_element(),
3182        )
3183    }
3184
3185    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3186        let potential_co_authors = self.potential_co_authors(cx);
3187
3188        let (tooltip_label, icon) = if self.add_coauthors {
3189            ("Remove co-authored-by", IconName::Person)
3190        } else {
3191            ("Add co-authored-by", IconName::UserCheck)
3192        };
3193
3194        if potential_co_authors.is_empty() {
3195            None
3196        } else {
3197            Some(
3198                IconButton::new("co-authors", icon)
3199                    .shape(ui::IconButtonShape::Square)
3200                    .icon_color(Color::Disabled)
3201                    .selected_icon_color(Color::Selected)
3202                    .toggle_state(self.add_coauthors)
3203                    .tooltip(move |_, cx| {
3204                        let title = format!(
3205                            "{}:{}{}",
3206                            tooltip_label,
3207                            if potential_co_authors.len() == 1 {
3208                                ""
3209                            } else {
3210                                "\n"
3211                            },
3212                            potential_co_authors
3213                                .iter()
3214                                .map(|(name, email)| format!(" {} <{}>", name, email))
3215                                .join("\n")
3216                        );
3217                        Tooltip::simple(title, cx)
3218                    })
3219                    .on_click(cx.listener(|this, _, _, cx| {
3220                        this.add_coauthors = !this.add_coauthors;
3221                        cx.notify();
3222                    }))
3223                    .into_any_element(),
3224            )
3225        }
3226    }
3227
3228    fn render_git_commit_menu(
3229        &self,
3230        id: impl Into<ElementId>,
3231        keybinding_target: Option<FocusHandle>,
3232        cx: &mut Context<Self>,
3233    ) -> impl IntoElement {
3234        PopoverMenu::new(id.into())
3235            .trigger(
3236                ui::ButtonLike::new_rounded_right("commit-split-button-right")
3237                    .layer(ui::ElevationIndex::ModalSurface)
3238                    .size(ButtonSize::None)
3239                    .child(
3240                        h_flex()
3241                            .px_1()
3242                            .h_full()
3243                            .justify_center()
3244                            .border_l_1()
3245                            .border_color(cx.theme().colors().border)
3246                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3247                    ),
3248            )
3249            .menu({
3250                let git_panel = cx.entity();
3251                let has_previous_commit = self.head_commit(cx).is_some();
3252                let amend = self.amend_pending();
3253                let signoff = self.signoff_enabled;
3254
3255                move |window, cx| {
3256                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3257                        context_menu
3258                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
3259                                el.context(keybinding_target)
3260                            })
3261                            .when(has_previous_commit, |this| {
3262                                this.toggleable_entry(
3263                                    "Amend",
3264                                    amend,
3265                                    IconPosition::Start,
3266                                    Some(Box::new(Amend)),
3267                                    {
3268                                        let git_panel = git_panel.downgrade();
3269                                        move |_, cx| {
3270                                            git_panel
3271                                                .update(cx, |git_panel, cx| {
3272                                                    git_panel.toggle_amend_pending(cx);
3273                                                })
3274                                                .ok();
3275                                        }
3276                                    },
3277                                )
3278                            })
3279                            .toggleable_entry(
3280                                "Signoff",
3281                                signoff,
3282                                IconPosition::Start,
3283                                Some(Box::new(Signoff)),
3284                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3285                            )
3286                    }))
3287                }
3288            })
3289            .anchor(Corner::TopRight)
3290    }
3291
3292    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3293        if self.has_unstaged_conflicts() {
3294            (false, "You must resolve conflicts before committing")
3295        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
3296            (false, "No changes to commit")
3297        } else if self.pending_commit.is_some() {
3298            (false, "Commit in progress")
3299        } else if !self.has_commit_message(cx) {
3300            (false, "No commit message")
3301        } else if !self.has_write_access(cx) {
3302            (false, "You do not have write access to this project")
3303        } else {
3304            (true, self.commit_button_title())
3305        }
3306    }
3307
3308    pub fn commit_button_title(&self) -> &'static str {
3309        if self.amend_pending {
3310            if self.has_staged_changes() {
3311                "Amend"
3312            } else {
3313                "Amend Tracked"
3314            }
3315        } else if self.has_staged_changes() {
3316            "Commit"
3317        } else {
3318            "Commit Tracked"
3319        }
3320    }
3321
3322    fn expand_commit_editor(
3323        &mut self,
3324        _: &git::ExpandCommitEditor,
3325        window: &mut Window,
3326        cx: &mut Context<Self>,
3327    ) {
3328        let workspace = self.workspace.clone();
3329        window.defer(cx, move |window, cx| {
3330            workspace
3331                .update(cx, |workspace, cx| {
3332                    CommitModal::toggle(workspace, None, window, cx)
3333                })
3334                .ok();
3335        })
3336    }
3337
3338    fn render_panel_header(
3339        &self,
3340        window: &mut Window,
3341        cx: &mut Context<Self>,
3342    ) -> Option<impl IntoElement> {
3343        self.active_repository.as_ref()?;
3344
3345        let text;
3346        let action;
3347        let tooltip;
3348        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3349            text = "Unstage All";
3350            action = git::UnstageAll.boxed_clone();
3351            tooltip = "git reset";
3352        } else {
3353            text = "Stage All";
3354            action = git::StageAll.boxed_clone();
3355            tooltip = "git add --all ."
3356        }
3357
3358        let change_string = match self.entry_count {
3359            0 => "No Changes".to_string(),
3360            1 => "1 Change".to_string(),
3361            _ => format!("{} Changes", self.entry_count),
3362        };
3363
3364        Some(
3365            self.panel_header_container(window, cx)
3366                .px_2()
3367                .justify_between()
3368                .child(
3369                    panel_button(change_string)
3370                        .color(Color::Muted)
3371                        .tooltip(Tooltip::for_action_title_in(
3372                            "Open Diff",
3373                            &Diff,
3374                            &self.focus_handle,
3375                        ))
3376                        .on_click(|_, _, cx| {
3377                            cx.defer(|cx| {
3378                                cx.dispatch_action(&Diff);
3379                            })
3380                        }),
3381                )
3382                .child(
3383                    h_flex()
3384                        .gap_1()
3385                        .child(self.render_overflow_menu("overflow_menu"))
3386                        .child(
3387                            panel_filled_button(text)
3388                                .tooltip(Tooltip::for_action_title_in(
3389                                    tooltip,
3390                                    action.as_ref(),
3391                                    &self.focus_handle,
3392                                ))
3393                                .disabled(self.entry_count == 0)
3394                                .on_click(move |_, _, cx| {
3395                                    let action = action.boxed_clone();
3396                                    cx.defer(move |cx| {
3397                                        cx.dispatch_action(action.as_ref());
3398                                    })
3399                                }),
3400                        ),
3401                ),
3402        )
3403    }
3404
3405    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3406        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3407        if !self.can_push_and_pull(cx) {
3408            return None;
3409        }
3410        Some(
3411            h_flex()
3412                .gap_1()
3413                .flex_shrink_0()
3414                .when_some(branch, |this, branch| {
3415                    let focus_handle = Some(self.focus_handle(cx));
3416
3417                    this.children(render_remote_button(
3418                        "remote-button",
3419                        &branch,
3420                        focus_handle,
3421                        true,
3422                    ))
3423                })
3424                .into_any_element(),
3425        )
3426    }
3427
3428    pub fn render_footer(
3429        &self,
3430        window: &mut Window,
3431        cx: &mut Context<Self>,
3432    ) -> Option<impl IntoElement> {
3433        let active_repository = self.active_repository.clone()?;
3434        let panel_editor_style = panel_editor_style(true, window, cx);
3435
3436        let enable_coauthors = self.render_co_authors(cx);
3437
3438        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3439        let expand_tooltip_focus_handle = editor_focus_handle;
3440
3441        let branch = active_repository.read(cx).branch.clone();
3442        let head_commit = active_repository.read(cx).head_commit.clone();
3443
3444        let footer_size = px(32.);
3445        let gap = px(9.0);
3446        let max_height = panel_editor_style
3447            .text
3448            .line_height_in_pixels(window.rem_size())
3449            * MAX_PANEL_EDITOR_LINES
3450            + gap;
3451
3452        let git_panel = cx.entity();
3453        let display_name = SharedString::from(Arc::from(
3454            active_repository
3455                .read(cx)
3456                .display_name()
3457                .trim_end_matches("/"),
3458        ));
3459        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3460            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3461        });
3462
3463        let footer = v_flex()
3464            .child(PanelRepoFooter::new(
3465                display_name,
3466                branch,
3467                head_commit,
3468                Some(git_panel),
3469            ))
3470            .child(
3471                panel_editor_container(window, cx)
3472                    .id("commit-editor-container")
3473                    .relative()
3474                    .w_full()
3475                    .h(max_height + footer_size)
3476                    .border_t_1()
3477                    .border_color(cx.theme().colors().border)
3478                    .cursor_text()
3479                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3480                        window.focus(&this.commit_editor.focus_handle(cx));
3481                    }))
3482                    .child(
3483                        h_flex()
3484                            .id("commit-footer")
3485                            .border_t_1()
3486                            .when(editor_is_long, |el| {
3487                                el.border_color(cx.theme().colors().border_variant)
3488                            })
3489                            .absolute()
3490                            .bottom_0()
3491                            .left_0()
3492                            .w_full()
3493                            .px_2()
3494                            .h(footer_size)
3495                            .flex_none()
3496                            .justify_between()
3497                            .child(
3498                                self.render_generate_commit_message_button(cx)
3499                                    .unwrap_or_else(|| div().into_any_element()),
3500                            )
3501                            .child(
3502                                h_flex()
3503                                    .gap_0p5()
3504                                    .children(enable_coauthors)
3505                                    .child(self.render_commit_button(cx)),
3506                            ),
3507                    )
3508                    .child(
3509                        div()
3510                            .pr_2p5()
3511                            .on_action(|&editor::actions::MoveUp, _, cx| {
3512                                cx.stop_propagation();
3513                            })
3514                            .on_action(|&editor::actions::MoveDown, _, cx| {
3515                                cx.stop_propagation();
3516                            })
3517                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3518                    )
3519                    .child(
3520                        h_flex()
3521                            .absolute()
3522                            .top_2()
3523                            .right_2()
3524                            .opacity(0.5)
3525                            .hover(|this| this.opacity(1.0))
3526                            .child(
3527                                panel_icon_button("expand-commit-editor", IconName::Maximize)
3528                                    .icon_size(IconSize::Small)
3529                                    .size(ui::ButtonSize::Default)
3530                                    .tooltip(move |window, cx| {
3531                                        Tooltip::for_action_in(
3532                                            "Open Commit Modal",
3533                                            &git::ExpandCommitEditor,
3534                                            &expand_tooltip_focus_handle,
3535                                            window,
3536                                            cx,
3537                                        )
3538                                    })
3539                                    .on_click(cx.listener({
3540                                        move |_, _, window, cx| {
3541                                            window.dispatch_action(
3542                                                git::ExpandCommitEditor.boxed_clone(),
3543                                                cx,
3544                                            )
3545                                        }
3546                                    })),
3547                            ),
3548                    ),
3549            );
3550
3551        Some(footer)
3552    }
3553
3554    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3555        let (can_commit, tooltip) = self.configure_commit_button(cx);
3556        let title = self.commit_button_title();
3557        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3558        let amend = self.amend_pending();
3559        let signoff = self.signoff_enabled;
3560
3561        div()
3562            .id("commit-wrapper")
3563            .on_hover(cx.listener(move |this, hovered, _, cx| {
3564                this.show_placeholders =
3565                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3566                cx.notify()
3567            }))
3568            .child(SplitButton::new(
3569                ui::ButtonLike::new_rounded_left(ElementId::Name(
3570                    format!("split-button-left-{}", title).into(),
3571                ))
3572                .layer(ui::ElevationIndex::ModalSurface)
3573                .size(ui::ButtonSize::Compact)
3574                .child(
3575                    div()
3576                        .child(Label::new(title).size(LabelSize::Small))
3577                        .mr_0p5(),
3578                )
3579                .on_click({
3580                    let git_panel = cx.weak_entity();
3581                    move |_, window, cx| {
3582                        telemetry::event!("Git Committed", source = "Git Panel");
3583                        git_panel
3584                            .update(cx, |git_panel, cx| {
3585                                git_panel.commit_changes(
3586                                    CommitOptions { amend, signoff },
3587                                    window,
3588                                    cx,
3589                                );
3590                            })
3591                            .ok();
3592                    }
3593                })
3594                .disabled(!can_commit || self.modal_open)
3595                .tooltip({
3596                    let handle = commit_tooltip_focus_handle.clone();
3597                    move |window, cx| {
3598                        if can_commit {
3599                            Tooltip::with_meta_in(
3600                                tooltip,
3601                                Some(&git::Commit),
3602                                format!(
3603                                    "git commit{}{}",
3604                                    if amend { " --amend" } else { "" },
3605                                    if signoff { " --signoff" } else { "" }
3606                                ),
3607                                &handle.clone(),
3608                                window,
3609                                cx,
3610                            )
3611                        } else {
3612                            Tooltip::simple(tooltip, cx)
3613                        }
3614                    }
3615                }),
3616                self.render_git_commit_menu(
3617                    ElementId::Name(format!("split-button-right-{}", title).into()),
3618                    Some(commit_tooltip_focus_handle),
3619                    cx,
3620                )
3621                .into_any_element(),
3622            ))
3623    }
3624
3625    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3626        h_flex()
3627            .py_1p5()
3628            .px_2()
3629            .gap_1p5()
3630            .justify_between()
3631            .border_t_1()
3632            .border_color(cx.theme().colors().border.opacity(0.8))
3633            .child(
3634                div()
3635                    .flex_grow()
3636                    .overflow_hidden()
3637                    .max_w(relative(0.85))
3638                    .child(
3639                        Label::new("This will update your most recent commit.")
3640                            .size(LabelSize::Small)
3641                            .truncate(),
3642                    ),
3643            )
3644            .child(
3645                panel_button("Cancel")
3646                    .size(ButtonSize::Default)
3647                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3648            )
3649    }
3650
3651    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3652        let active_repository = self.active_repository.as_ref()?;
3653        let branch = active_repository.read(cx).branch.as_ref()?;
3654        let commit = branch.most_recent_commit.as_ref()?.clone();
3655        let workspace = self.workspace.clone();
3656        let this = cx.entity();
3657
3658        Some(
3659            h_flex()
3660                .py_1p5()
3661                .px_2()
3662                .gap_1p5()
3663                .justify_between()
3664                .border_t_1()
3665                .border_color(cx.theme().colors().border.opacity(0.8))
3666                .child(
3667                    div()
3668                        .flex_grow()
3669                        .overflow_hidden()
3670                        .max_w(relative(0.85))
3671                        .child(
3672                            Label::new(commit.subject.clone())
3673                                .size(LabelSize::Small)
3674                                .truncate(),
3675                        )
3676                        .id("commit-msg-hover")
3677                        .on_click({
3678                            let commit = commit.clone();
3679                            let repo = active_repository.downgrade();
3680                            move |_, window, cx| {
3681                                CommitView::open(
3682                                    commit.clone(),
3683                                    repo.clone(),
3684                                    workspace.clone(),
3685                                    window,
3686                                    cx,
3687                                );
3688                            }
3689                        })
3690                        .hoverable_tooltip({
3691                            let repo = active_repository.clone();
3692                            move |window, cx| {
3693                                GitPanelMessageTooltip::new(
3694                                    this.clone(),
3695                                    commit.sha.clone(),
3696                                    repo.clone(),
3697                                    window,
3698                                    cx,
3699                                )
3700                                .into()
3701                            }
3702                        }),
3703                )
3704                .when(commit.has_parent, |this| {
3705                    let has_unstaged = self.has_unstaged_changes();
3706                    this.child(
3707                        panel_icon_button("undo", IconName::Undo)
3708                            .icon_size(IconSize::XSmall)
3709                            .icon_color(Color::Muted)
3710                            .tooltip(move |window, cx| {
3711                                Tooltip::with_meta(
3712                                    "Uncommit",
3713                                    Some(&git::Uncommit),
3714                                    if has_unstaged {
3715                                        "git reset HEAD^ --soft"
3716                                    } else {
3717                                        "git reset HEAD^"
3718                                    },
3719                                    window,
3720                                    cx,
3721                                )
3722                            })
3723                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3724                    )
3725                }),
3726        )
3727    }
3728
3729    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3730        h_flex().h_full().flex_grow().justify_center().child(
3731            v_flex()
3732                .gap_2()
3733                .child(h_flex().w_full().justify_around().child(
3734                    if self.active_repository.is_some() {
3735                        "No changes to commit"
3736                    } else {
3737                        "No Git repositories"
3738                    },
3739                ))
3740                .children({
3741                    let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3742                    (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3743                        h_flex().w_full().justify_around().child(
3744                            panel_filled_button("Initialize Repository")
3745                                .tooltip(Tooltip::for_action_title_in(
3746                                    "git init",
3747                                    &git::Init,
3748                                    &self.focus_handle,
3749                                ))
3750                                .on_click(move |_, _, cx| {
3751                                    cx.defer(move |cx| {
3752                                        cx.dispatch_action(&git::Init);
3753                                    })
3754                                }),
3755                        )
3756                    })
3757                })
3758                .text_ui_sm(cx)
3759                .mx_auto()
3760                .text_color(Color::Placeholder.color(cx)),
3761        )
3762    }
3763
3764    fn render_vertical_scrollbar(
3765        &self,
3766        show_horizontal_scrollbar_container: bool,
3767        cx: &mut Context<Self>,
3768    ) -> impl IntoElement {
3769        div()
3770            .id("git-panel-vertical-scroll")
3771            .occlude()
3772            .flex_none()
3773            .h_full()
3774            .cursor_default()
3775            .absolute()
3776            .right_0()
3777            .top_0()
3778            .bottom_0()
3779            .w(px(12.))
3780            .when(show_horizontal_scrollbar_container, |this| {
3781                this.pb_neg_3p5()
3782            })
3783            .on_mouse_move(cx.listener(|_, _, _, cx| {
3784                cx.notify();
3785                cx.stop_propagation()
3786            }))
3787            .on_hover(|_, _, cx| {
3788                cx.stop_propagation();
3789            })
3790            .on_any_mouse_down(|_, _, cx| {
3791                cx.stop_propagation();
3792            })
3793            .on_mouse_up(
3794                MouseButton::Left,
3795                cx.listener(|this, _, window, cx| {
3796                    if !this.vertical_scrollbar.state.is_dragging()
3797                        && !this.focus_handle.contains_focused(window, cx)
3798                    {
3799                        this.vertical_scrollbar.hide(window, cx);
3800                        cx.notify();
3801                    }
3802
3803                    cx.stop_propagation();
3804                }),
3805            )
3806            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3807                cx.notify();
3808            }))
3809            .children(Scrollbar::vertical(
3810                // percentage as f32..end_offset as f32,
3811                self.vertical_scrollbar.state.clone(),
3812            ))
3813    }
3814
3815    /// Renders the horizontal scrollbar.
3816    ///
3817    /// The right offset is used to determine how far to the right the
3818    /// scrollbar should extend to, useful for ensuring it doesn't collide
3819    /// with the vertical scrollbar when visible.
3820    fn render_horizontal_scrollbar(
3821        &self,
3822        right_offset: Pixels,
3823        cx: &mut Context<Self>,
3824    ) -> impl IntoElement {
3825        div()
3826            .id("git-panel-horizontal-scroll")
3827            .occlude()
3828            .flex_none()
3829            .w_full()
3830            .cursor_default()
3831            .absolute()
3832            .bottom_neg_px()
3833            .left_0()
3834            .right_0()
3835            .pr(right_offset)
3836            .on_mouse_move(cx.listener(|_, _, _, cx| {
3837                cx.notify();
3838                cx.stop_propagation()
3839            }))
3840            .on_hover(|_, _, cx| {
3841                cx.stop_propagation();
3842            })
3843            .on_any_mouse_down(|_, _, cx| {
3844                cx.stop_propagation();
3845            })
3846            .on_mouse_up(
3847                MouseButton::Left,
3848                cx.listener(|this, _, window, cx| {
3849                    if !this.horizontal_scrollbar.state.is_dragging()
3850                        && !this.focus_handle.contains_focused(window, cx)
3851                    {
3852                        this.horizontal_scrollbar.hide(window, cx);
3853                        cx.notify();
3854                    }
3855
3856                    cx.stop_propagation();
3857                }),
3858            )
3859            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3860                cx.notify();
3861            }))
3862            .children(Scrollbar::horizontal(
3863                // percentage as f32..end_offset as f32,
3864                self.horizontal_scrollbar.state.clone(),
3865            ))
3866    }
3867
3868    fn render_buffer_header_controls(
3869        &self,
3870        entity: &Entity<Self>,
3871        file: &Arc<dyn File>,
3872        _: &Window,
3873        cx: &App,
3874    ) -> Option<AnyElement> {
3875        let repo = self.active_repository.as_ref()?.read(cx);
3876        let project_path = (file.worktree_id(cx), file.path()).into();
3877        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3878        let ix = self.entry_by_path(&repo_path, cx)?;
3879        let entry = self.entries.get(ix)?;
3880
3881        let entry_staging = self.entry_staging(entry.status_entry()?);
3882
3883        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3884            .disabled(!self.has_write_access(cx))
3885            .fill()
3886            .elevation(ElevationIndex::Surface)
3887            .on_click({
3888                let entry = entry.clone();
3889                let git_panel = entity.downgrade();
3890                move |_, window, cx| {
3891                    git_panel
3892                        .update(cx, |this, cx| {
3893                            this.toggle_staged_for_entry(&entry, window, cx);
3894                            cx.stop_propagation();
3895                        })
3896                        .ok();
3897                }
3898            });
3899        Some(
3900            h_flex()
3901                .id("start-slot")
3902                .text_lg()
3903                .child(checkbox)
3904                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3905                    // prevent the list item active state triggering when toggling checkbox
3906                    cx.stop_propagation();
3907                })
3908                .into_any_element(),
3909        )
3910    }
3911
3912    fn render_entries(
3913        &self,
3914        has_write_access: bool,
3915        _: &Window,
3916        cx: &mut Context<Self>,
3917    ) -> impl IntoElement {
3918        let entry_count = self.entries.len();
3919
3920        let scroll_track_size = px(16.);
3921
3922        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3923            // magic number
3924            px(3.)
3925        } else {
3926            px(0.)
3927        };
3928
3929        v_flex()
3930            .flex_1()
3931            .size_full()
3932            .overflow_hidden()
3933            .relative()
3934            // Show a border on the top and bottom of the container when
3935            // the vertical scrollbar container is visible so we don't have a
3936            // floating left border in the panel.
3937            .when(self.vertical_scrollbar.show_track, |this| {
3938                this.border_t_1()
3939                    .border_b_1()
3940                    .border_color(cx.theme().colors().border)
3941            })
3942            .child(
3943                h_flex()
3944                    .flex_1()
3945                    .size_full()
3946                    .relative()
3947                    .overflow_hidden()
3948                    .child(
3949                        uniform_list(
3950                            "entries",
3951                            entry_count,
3952                            cx.processor(move |this, range: Range<usize>, window, cx| {
3953                                let mut items = Vec::with_capacity(range.end - range.start);
3954
3955                                for ix in range {
3956                                    match &this.entries.get(ix) {
3957                                        Some(GitListEntry::Status(entry)) => {
3958                                            items.push(this.render_entry(
3959                                                ix,
3960                                                entry,
3961                                                has_write_access,
3962                                                window,
3963                                                cx,
3964                                            ));
3965                                        }
3966                                        Some(GitListEntry::Header(header)) => {
3967                                            items.push(this.render_list_header(
3968                                                ix,
3969                                                header,
3970                                                has_write_access,
3971                                                window,
3972                                                cx,
3973                                            ));
3974                                        }
3975                                        None => {}
3976                                    }
3977                                }
3978
3979                                items
3980                            }),
3981                        )
3982                        .when(
3983                            !self.horizontal_scrollbar.show_track
3984                                && self.horizontal_scrollbar.show_scrollbar,
3985                            |this| {
3986                                // when not showing the horizontal scrollbar track, make sure we don't
3987                                // obscure the last entry
3988                                this.pb(scroll_track_size)
3989                            },
3990                        )
3991                        .size_full()
3992                        .flex_grow()
3993                        .with_sizing_behavior(ListSizingBehavior::Auto)
3994                        .with_horizontal_sizing_behavior(
3995                            ListHorizontalSizingBehavior::Unconstrained,
3996                        )
3997                        .with_width_from_item(self.max_width_item_index)
3998                        .track_scroll(self.scroll_handle.clone()),
3999                    )
4000                    .on_mouse_down(
4001                        MouseButton::Right,
4002                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4003                            this.deploy_panel_context_menu(event.position, window, cx)
4004                        }),
4005                    )
4006                    .when(self.vertical_scrollbar.show_track, |this| {
4007                        this.child(
4008                            v_flex()
4009                                .h_full()
4010                                .flex_none()
4011                                .w(scroll_track_size)
4012                                .bg(cx.theme().colors().panel_background)
4013                                .child(
4014                                    div()
4015                                        .size_full()
4016                                        .flex_1()
4017                                        .border_l_1()
4018                                        .border_color(cx.theme().colors().border),
4019                                ),
4020                        )
4021                    })
4022                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
4023                        this.child(
4024                            self.render_vertical_scrollbar(
4025                                self.horizontal_scrollbar.show_track,
4026                                cx,
4027                            ),
4028                        )
4029                    }),
4030            )
4031            .when(self.horizontal_scrollbar.show_track, |this| {
4032                this.child(
4033                    h_flex()
4034                        .w_full()
4035                        .h(scroll_track_size)
4036                        .flex_none()
4037                        .relative()
4038                        .child(
4039                            div()
4040                                .w_full()
4041                                .flex_1()
4042                                // for some reason the horizontal scrollbar is 1px
4043                                // taller than the vertical scrollbar??
4044                                .h(scroll_track_size - px(1.))
4045                                .bg(cx.theme().colors().panel_background)
4046                                .border_t_1()
4047                                .border_color(cx.theme().colors().border),
4048                        )
4049                        .when(self.vertical_scrollbar.show_track, |this| {
4050                            this.child(
4051                                div()
4052                                    .flex_none()
4053                                    // -1px prevents a missing pixel between the two container borders
4054                                    .w(scroll_track_size - px(1.))
4055                                    .h_full(),
4056                            )
4057                            .child(
4058                                // HACK: Fill the missing 1px 🥲
4059                                div()
4060                                    .absolute()
4061                                    .right(scroll_track_size - px(1.))
4062                                    .bottom(scroll_track_size - px(1.))
4063                                    .size_px()
4064                                    .bg(cx.theme().colors().border),
4065                            )
4066                        }),
4067                )
4068            })
4069            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
4070                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
4071            })
4072    }
4073
4074    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4075        Label::new(label.into()).color(color).single_line()
4076    }
4077
4078    fn list_item_height(&self) -> Rems {
4079        rems(1.75)
4080    }
4081
4082    fn render_list_header(
4083        &self,
4084        ix: usize,
4085        header: &GitHeaderEntry,
4086        _: bool,
4087        _: &Window,
4088        _: &Context<Self>,
4089    ) -> AnyElement {
4090        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4091
4092        h_flex()
4093            .id(id)
4094            .h(self.list_item_height())
4095            .w_full()
4096            .items_end()
4097            .px(rems(0.75)) // ~12px
4098            .pb(rems(0.3125)) // ~ 5px
4099            .child(
4100                Label::new(header.title())
4101                    .color(Color::Muted)
4102                    .size(LabelSize::Small)
4103                    .line_height_style(LineHeightStyle::UiLabel)
4104                    .single_line(),
4105            )
4106            .into_any_element()
4107    }
4108
4109    pub fn load_commit_details(
4110        &self,
4111        sha: String,
4112        cx: &mut Context<Self>,
4113    ) -> Task<anyhow::Result<CommitDetails>> {
4114        let Some(repo) = self.active_repository.clone() else {
4115            return Task::ready(Err(anyhow::anyhow!("no active repo")));
4116        };
4117        repo.update(cx, |repo, cx| {
4118            let show = repo.show(sha);
4119            cx.spawn(async move |_, _| show.await?)
4120        })
4121    }
4122
4123    fn deploy_entry_context_menu(
4124        &mut self,
4125        position: Point<Pixels>,
4126        ix: usize,
4127        window: &mut Window,
4128        cx: &mut Context<Self>,
4129    ) {
4130        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4131            return;
4132        };
4133        let stage_title = if entry.status.staging().is_fully_staged() {
4134            "Unstage File"
4135        } else {
4136            "Stage File"
4137        };
4138        let restore_title = if entry.status.is_created() {
4139            "Trash File"
4140        } else {
4141            "Restore File"
4142        };
4143        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4144            context_menu
4145                .context(self.focus_handle.clone())
4146                .action(stage_title, ToggleStaged.boxed_clone())
4147                .action(restore_title, git::RestoreFile::default().boxed_clone())
4148                .separator()
4149                .action("Open Diff", Confirm.boxed_clone())
4150                .action("Open File", SecondaryConfirm.boxed_clone())
4151        });
4152        self.selected_entry = Some(ix);
4153        self.set_context_menu(context_menu, position, window, cx);
4154    }
4155
4156    fn deploy_panel_context_menu(
4157        &mut self,
4158        position: Point<Pixels>,
4159        window: &mut Window,
4160        cx: &mut Context<Self>,
4161    ) {
4162        let context_menu = git_panel_context_menu(
4163            self.focus_handle.clone(),
4164            GitMenuState {
4165                has_tracked_changes: self.has_tracked_changes(),
4166                has_staged_changes: self.has_staged_changes(),
4167                has_unstaged_changes: self.has_unstaged_changes(),
4168                has_new_changes: self.new_count > 0,
4169                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4170            },
4171            window,
4172            cx,
4173        );
4174        self.set_context_menu(context_menu, position, window, cx);
4175    }
4176
4177    fn set_context_menu(
4178        &mut self,
4179        context_menu: Entity<ContextMenu>,
4180        position: Point<Pixels>,
4181        window: &Window,
4182        cx: &mut Context<Self>,
4183    ) {
4184        let subscription = cx.subscribe_in(
4185            &context_menu,
4186            window,
4187            |this, _, _: &DismissEvent, window, cx| {
4188                if this.context_menu.as_ref().is_some_and(|context_menu| {
4189                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
4190                }) {
4191                    cx.focus_self(window);
4192                }
4193                this.context_menu.take();
4194                cx.notify();
4195            },
4196        );
4197        self.context_menu = Some((context_menu, position, subscription));
4198        cx.notify();
4199    }
4200
4201    fn render_entry(
4202        &self,
4203        ix: usize,
4204        entry: &GitStatusEntry,
4205        has_write_access: bool,
4206        window: &Window,
4207        cx: &Context<Self>,
4208    ) -> AnyElement {
4209        let display_name = entry.display_name();
4210
4211        let selected = self.selected_entry == Some(ix);
4212        let marked = self.marked_entries.contains(&ix);
4213        let status_style = GitPanelSettings::get_global(cx).status_style;
4214        let status = entry.status;
4215
4216        let has_conflict = status.is_conflicted();
4217        let is_modified = status.is_modified();
4218        let is_deleted = status.is_deleted();
4219
4220        let label_color = if status_style == StatusStyle::LabelColor {
4221            if has_conflict {
4222                Color::VersionControlConflict
4223            } else if is_modified {
4224                Color::VersionControlModified
4225            } else if is_deleted {
4226                // We don't want a bunch of red labels in the list
4227                Color::Disabled
4228            } else {
4229                Color::VersionControlAdded
4230            }
4231        } else {
4232            Color::Default
4233        };
4234
4235        let path_color = if status.is_deleted() {
4236            Color::Disabled
4237        } else {
4238            Color::Muted
4239        };
4240
4241        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4242        let checkbox_wrapper_id: ElementId =
4243            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4244        let checkbox_id: ElementId =
4245            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4246
4247        let entry_staging = self.entry_staging(entry);
4248        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4249        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4250            is_staged = ToggleState::Selected;
4251        }
4252
4253        let handle = cx.weak_entity();
4254
4255        let selected_bg_alpha = 0.08;
4256        let marked_bg_alpha = 0.12;
4257        let state_opacity_step = 0.04;
4258
4259        let base_bg = match (selected, marked) {
4260            (true, true) => cx
4261                .theme()
4262                .status()
4263                .info
4264                .alpha(selected_bg_alpha + marked_bg_alpha),
4265            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4266            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4267            _ => cx.theme().colors().ghost_element_background,
4268        };
4269
4270        let hover_bg = if selected {
4271            cx.theme()
4272                .status()
4273                .info
4274                .alpha(selected_bg_alpha + state_opacity_step)
4275        } else {
4276            cx.theme().colors().ghost_element_hover
4277        };
4278
4279        let active_bg = if selected {
4280            cx.theme()
4281                .status()
4282                .info
4283                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4284        } else {
4285            cx.theme().colors().ghost_element_active
4286        };
4287
4288        h_flex()
4289            .id(id)
4290            .h(self.list_item_height())
4291            .w_full()
4292            .items_center()
4293            .border_1()
4294            .when(selected && self.focus_handle.is_focused(window), |el| {
4295                el.border_color(cx.theme().colors().border_focused)
4296            })
4297            .px(rems(0.75)) // ~12px
4298            .overflow_hidden()
4299            .flex_none()
4300            .gap_1p5()
4301            .bg(base_bg)
4302            .hover(|this| this.bg(hover_bg))
4303            .active(|this| this.bg(active_bg))
4304            .on_click({
4305                cx.listener(move |this, event: &ClickEvent, window, cx| {
4306                    this.selected_entry = Some(ix);
4307                    cx.notify();
4308                    if event.modifiers().secondary() {
4309                        this.open_file(&Default::default(), window, cx)
4310                    } else {
4311                        this.open_diff(&Default::default(), window, cx);
4312                        this.focus_handle.focus(window);
4313                    }
4314                })
4315            })
4316            .on_mouse_down(
4317                MouseButton::Right,
4318                move |event: &MouseDownEvent, window, cx| {
4319                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4320                    if event.button != MouseButton::Right {
4321                        return;
4322                    }
4323
4324                    let Some(this) = handle.upgrade() else {
4325                        return;
4326                    };
4327                    this.update(cx, |this, cx| {
4328                        this.deploy_entry_context_menu(event.position, ix, window, cx);
4329                    });
4330                    cx.stop_propagation();
4331                },
4332            )
4333            .child(
4334                div()
4335                    .id(checkbox_wrapper_id)
4336                    .flex_none()
4337                    .occlude()
4338                    .cursor_pointer()
4339                    .child(
4340                        Checkbox::new(checkbox_id, is_staged)
4341                            .disabled(!has_write_access)
4342                            .fill()
4343                            .elevation(ElevationIndex::Surface)
4344                            .on_click_ext({
4345                                let entry = entry.clone();
4346                                let this = cx.weak_entity();
4347                                move |_, click, window, cx| {
4348                                    this.update(cx, |this, cx| {
4349                                        if !has_write_access {
4350                                            return;
4351                                        }
4352                                        if click.modifiers().shift {
4353                                            this.stage_bulk(ix, cx);
4354                                        } else {
4355                                            this.toggle_staged_for_entry(
4356                                                &GitListEntry::Status(entry.clone()),
4357                                                window,
4358                                                cx,
4359                                            );
4360                                        }
4361                                        cx.stop_propagation();
4362                                    })
4363                                    .ok();
4364                                }
4365                            })
4366                            .tooltip(move |window, cx| {
4367                                let is_staged = entry_staging.is_fully_staged();
4368
4369                                let action = if is_staged { "Unstage" } else { "Stage" };
4370                                let tooltip_name = action.to_string();
4371
4372                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4373                            }),
4374                    ),
4375            )
4376            .child(git_status_icon(status))
4377            .child(
4378                h_flex()
4379                    .items_center()
4380                    .flex_1()
4381                    // .overflow_hidden()
4382                    .when_some(entry.parent_dir(), |this, parent| {
4383                        if !parent.is_empty() {
4384                            this.child(
4385                                self.entry_label(format!("{}/", parent), path_color)
4386                                    .when(status.is_deleted(), |this| this.strikethrough()),
4387                            )
4388                        } else {
4389                            this
4390                        }
4391                    })
4392                    .child(
4393                        self.entry_label(display_name, label_color)
4394                            .when(status.is_deleted(), |this| this.strikethrough()),
4395                    ),
4396            )
4397            .into_any_element()
4398    }
4399
4400    fn has_write_access(&self, cx: &App) -> bool {
4401        !self.project.read(cx).is_read_only(cx)
4402    }
4403
4404    pub fn amend_pending(&self) -> bool {
4405        self.amend_pending
4406    }
4407
4408    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4409        if value && !self.amend_pending {
4410            let current_message = self.commit_message_buffer(cx).read(cx).text();
4411            self.original_commit_message = if current_message.trim().is_empty() {
4412                None
4413            } else {
4414                Some(current_message)
4415            };
4416        } else if !value && self.amend_pending {
4417            let message = self.original_commit_message.take().unwrap_or_default();
4418            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4419                let start = buffer.anchor_before(0);
4420                let end = buffer.anchor_after(buffer.len());
4421                buffer.edit([(start..end, message)], None, cx);
4422            });
4423        }
4424
4425        self.amend_pending = value;
4426        self.serialize(cx);
4427        cx.notify();
4428    }
4429
4430    pub fn signoff_enabled(&self) -> bool {
4431        self.signoff_enabled
4432    }
4433
4434    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4435        self.signoff_enabled = value;
4436        self.serialize(cx);
4437        cx.notify();
4438    }
4439
4440    pub fn toggle_signoff_enabled(
4441        &mut self,
4442        _: &Signoff,
4443        _window: &mut Window,
4444        cx: &mut Context<Self>,
4445    ) {
4446        self.set_signoff_enabled(!self.signoff_enabled, cx);
4447    }
4448
4449    pub async fn load(
4450        workspace: WeakEntity<Workspace>,
4451        mut cx: AsyncWindowContext,
4452    ) -> anyhow::Result<Entity<Self>> {
4453        let serialized_panel = match workspace
4454            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4455            .ok()
4456            .flatten()
4457        {
4458            Some(serialization_key) => cx
4459                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4460                .await
4461                .context("loading git panel")
4462                .log_err()
4463                .flatten()
4464                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4465                .transpose()
4466                .log_err()
4467                .flatten(),
4468            None => None,
4469        };
4470
4471        workspace.update_in(&mut cx, |workspace, window, cx| {
4472            let panel = GitPanel::new(workspace, window, cx);
4473
4474            if let Some(serialized_panel) = serialized_panel {
4475                panel.update(cx, |panel, cx| {
4476                    panel.width = serialized_panel.width;
4477                    panel.amend_pending = serialized_panel.amend_pending;
4478                    panel.signoff_enabled = serialized_panel.signoff_enabled;
4479                    cx.notify();
4480                })
4481            }
4482
4483            panel
4484        })
4485    }
4486
4487    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4488        let Some(op) = self.bulk_staging.as_ref() else {
4489            return;
4490        };
4491        let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4492            return;
4493        };
4494        if let Some(entry) = self.entries.get(index)
4495            && let Some(entry) = entry.status_entry()
4496        {
4497            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4498        }
4499        if index < anchor_index {
4500            std::mem::swap(&mut index, &mut anchor_index);
4501        }
4502        let entries = self
4503            .entries
4504            .get(anchor_index..=index)
4505            .unwrap_or_default()
4506            .iter()
4507            .filter_map(|entry| entry.status_entry().cloned())
4508            .collect::<Vec<_>>();
4509        self.change_file_stage(true, entries, cx);
4510    }
4511
4512    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4513        let Some(repo) = self.active_repository.as_ref() else {
4514            return;
4515        };
4516        self.bulk_staging = Some(BulkStaging {
4517            repo_id: repo.read(cx).id,
4518            anchor: path,
4519        });
4520    }
4521
4522    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4523        self.set_amend_pending(!self.amend_pending, cx);
4524        if self.amend_pending {
4525            self.load_last_commit_message_if_empty(cx);
4526        }
4527    }
4528}
4529
4530impl Render for GitPanel {
4531    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4532        let project = self.project.read(cx);
4533        let has_entries = !self.entries.is_empty();
4534        let room = self
4535            .workspace
4536            .upgrade()
4537            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4538
4539        let has_write_access = self.has_write_access(cx);
4540
4541        let has_co_authors = room.is_some_and(|room| {
4542            self.load_local_committer(cx);
4543            let room = room.read(cx);
4544            room.remote_participants()
4545                .values()
4546                .any(|remote_participant| remote_participant.can_write())
4547        });
4548
4549        v_flex()
4550            .id("git_panel")
4551            .key_context(self.dispatch_context(window, cx))
4552            .track_focus(&self.focus_handle)
4553            .when(has_write_access && !project.is_read_only(cx), |this| {
4554                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4555                    .on_action(cx.listener(Self::stage_range))
4556                    .on_action(cx.listener(GitPanel::commit))
4557                    .on_action(cx.listener(GitPanel::amend))
4558                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4559                    .on_action(cx.listener(Self::stage_all))
4560                    .on_action(cx.listener(Self::unstage_all))
4561                    .on_action(cx.listener(Self::stage_selected))
4562                    .on_action(cx.listener(Self::unstage_selected))
4563                    .on_action(cx.listener(Self::restore_tracked_files))
4564                    .on_action(cx.listener(Self::revert_selected))
4565                    .on_action(cx.listener(Self::clean_all))
4566                    .on_action(cx.listener(Self::generate_commit_message_action))
4567                    .on_action(cx.listener(Self::stash_all))
4568                    .on_action(cx.listener(Self::stash_pop))
4569            })
4570            .on_action(cx.listener(Self::select_first))
4571            .on_action(cx.listener(Self::select_next))
4572            .on_action(cx.listener(Self::select_previous))
4573            .on_action(cx.listener(Self::select_last))
4574            .on_action(cx.listener(Self::close_panel))
4575            .on_action(cx.listener(Self::open_diff))
4576            .on_action(cx.listener(Self::open_file))
4577            .on_action(cx.listener(Self::focus_changes_list))
4578            .on_action(cx.listener(Self::focus_editor))
4579            .on_action(cx.listener(Self::expand_commit_editor))
4580            .when(has_write_access && has_co_authors, |git_panel| {
4581                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4582            })
4583            .on_action(cx.listener(Self::toggle_sort_by_path))
4584            .on_hover(cx.listener(move |this, hovered, window, cx| {
4585                if *hovered {
4586                    this.horizontal_scrollbar.show(cx);
4587                    this.vertical_scrollbar.show(cx);
4588                    cx.notify();
4589                } else if !this.focus_handle.contains_focused(window, cx) {
4590                    this.hide_scrollbars(window, cx);
4591                }
4592            }))
4593            .size_full()
4594            .overflow_hidden()
4595            .bg(cx.theme().colors().panel_background)
4596            .child(
4597                v_flex()
4598                    .size_full()
4599                    .children(self.render_panel_header(window, cx))
4600                    .map(|this| {
4601                        if has_entries {
4602                            this.child(self.render_entries(has_write_access, window, cx))
4603                        } else {
4604                            this.child(self.render_empty_state(cx).into_any_element())
4605                        }
4606                    })
4607                    .children(self.render_footer(window, cx))
4608                    .when(self.amend_pending, |this| {
4609                        this.child(self.render_pending_amend(cx))
4610                    })
4611                    .when(!self.amend_pending, |this| {
4612                        this.children(self.render_previous_commit(cx))
4613                    })
4614                    .into_any_element(),
4615            )
4616            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4617                deferred(
4618                    anchored()
4619                        .position(*position)
4620                        .anchor(Corner::TopLeft)
4621                        .child(menu.clone()),
4622                )
4623                .with_priority(1)
4624            }))
4625    }
4626}
4627
4628impl Focusable for GitPanel {
4629    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4630        if self.entries.is_empty() {
4631            self.commit_editor.focus_handle(cx)
4632        } else {
4633            self.focus_handle.clone()
4634        }
4635    }
4636}
4637
4638impl EventEmitter<Event> for GitPanel {}
4639
4640impl EventEmitter<PanelEvent> for GitPanel {}
4641
4642pub(crate) struct GitPanelAddon {
4643    pub(crate) workspace: WeakEntity<Workspace>,
4644}
4645
4646impl editor::Addon for GitPanelAddon {
4647    fn to_any(&self) -> &dyn std::any::Any {
4648        self
4649    }
4650
4651    fn render_buffer_header_controls(
4652        &self,
4653        excerpt_info: &ExcerptInfo,
4654        window: &Window,
4655        cx: &App,
4656    ) -> Option<AnyElement> {
4657        let file = excerpt_info.buffer.file()?;
4658        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4659
4660        git_panel
4661            .read(cx)
4662            .render_buffer_header_controls(&git_panel, file, window, cx)
4663    }
4664}
4665
4666impl Panel for GitPanel {
4667    fn persistent_name() -> &'static str {
4668        "GitPanel"
4669    }
4670
4671    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4672        GitPanelSettings::get_global(cx).dock
4673    }
4674
4675    fn position_is_valid(&self, position: DockPosition) -> bool {
4676        matches!(position, DockPosition::Left | DockPosition::Right)
4677    }
4678
4679    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4680        settings::update_settings_file::<GitPanelSettings>(
4681            self.fs.clone(),
4682            cx,
4683            move |settings, _| settings.dock = Some(position),
4684        );
4685    }
4686
4687    fn size(&self, _: &Window, cx: &App) -> Pixels {
4688        self.width
4689            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4690    }
4691
4692    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4693        self.width = size;
4694        self.serialize(cx);
4695        cx.notify();
4696    }
4697
4698    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4699        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4700    }
4701
4702    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4703        Some("Git Panel")
4704    }
4705
4706    fn toggle_action(&self) -> Box<dyn Action> {
4707        Box::new(ToggleFocus)
4708    }
4709
4710    fn activation_priority(&self) -> u32 {
4711        2
4712    }
4713}
4714
4715impl PanelHeader for GitPanel {}
4716
4717struct GitPanelMessageTooltip {
4718    commit_tooltip: Option<Entity<CommitTooltip>>,
4719}
4720
4721impl GitPanelMessageTooltip {
4722    fn new(
4723        git_panel: Entity<GitPanel>,
4724        sha: SharedString,
4725        repository: Entity<Repository>,
4726        window: &mut Window,
4727        cx: &mut App,
4728    ) -> Entity<Self> {
4729        cx.new(|cx| {
4730            cx.spawn_in(window, async move |this, cx| {
4731                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4732                    (
4733                        git_panel.load_commit_details(sha.to_string(), cx),
4734                        git_panel.workspace.clone(),
4735                    )
4736                })?;
4737                let details = details.await?;
4738
4739                let commit_details = crate::commit_tooltip::CommitDetails {
4740                    sha: details.sha.clone(),
4741                    author_name: details.author_name.clone(),
4742                    author_email: details.author_email.clone(),
4743                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4744                    message: Some(ParsedCommitMessage {
4745                        message: details.message,
4746                        ..Default::default()
4747                    }),
4748                };
4749
4750                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4751                    this.commit_tooltip = Some(cx.new(move |cx| {
4752                        CommitTooltip::new(commit_details, repository, workspace, cx)
4753                    }));
4754                    cx.notify();
4755                })
4756            })
4757            .detach();
4758
4759            Self {
4760                commit_tooltip: None,
4761            }
4762        })
4763    }
4764}
4765
4766impl Render for GitPanelMessageTooltip {
4767    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4768        if let Some(commit_tooltip) = &self.commit_tooltip {
4769            commit_tooltip.clone().into_any_element()
4770        } else {
4771            gpui::Empty.into_any_element()
4772        }
4773    }
4774}
4775
4776#[derive(IntoElement, RegisterComponent)]
4777pub struct PanelRepoFooter {
4778    active_repository: SharedString,
4779    branch: Option<Branch>,
4780    head_commit: Option<CommitDetails>,
4781
4782    // Getting a GitPanel in previews will be difficult.
4783    //
4784    // For now just take an option here, and we won't bind handlers to buttons in previews.
4785    git_panel: Option<Entity<GitPanel>>,
4786}
4787
4788impl PanelRepoFooter {
4789    pub fn new(
4790        active_repository: SharedString,
4791        branch: Option<Branch>,
4792        head_commit: Option<CommitDetails>,
4793        git_panel: Option<Entity<GitPanel>>,
4794    ) -> Self {
4795        Self {
4796            active_repository,
4797            branch,
4798            head_commit,
4799            git_panel,
4800        }
4801    }
4802
4803    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4804        Self {
4805            active_repository,
4806            branch,
4807            head_commit: None,
4808            git_panel: None,
4809        }
4810    }
4811}
4812
4813impl RenderOnce for PanelRepoFooter {
4814    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4815        let project = self
4816            .git_panel
4817            .as_ref()
4818            .map(|panel| panel.read(cx).project.clone());
4819
4820        let repo = self
4821            .git_panel
4822            .as_ref()
4823            .and_then(|panel| panel.read(cx).active_repository.clone());
4824
4825        let single_repo = project
4826            .as_ref()
4827            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4828            .unwrap_or(true);
4829
4830        const MAX_BRANCH_LEN: usize = 16;
4831        const MAX_REPO_LEN: usize = 16;
4832        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4833        const MAX_SHORT_SHA_LEN: usize = 8;
4834
4835        let branch_name = self
4836            .branch
4837            .as_ref()
4838            .map(|branch| branch.name().to_owned())
4839            .or_else(|| {
4840                self.head_commit.as_ref().map(|commit| {
4841                    commit
4842                        .sha
4843                        .chars()
4844                        .take(MAX_SHORT_SHA_LEN)
4845                        .collect::<String>()
4846                })
4847            })
4848            .unwrap_or_else(|| " (no branch)".to_owned());
4849        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4850
4851        let active_repo_name = self.active_repository.clone();
4852
4853        let branch_actual_len = branch_name.len();
4854        let repo_actual_len = active_repo_name.len();
4855
4856        // ideally, show the whole branch and repo names but
4857        // when we can't, use a budget to allocate space between the two
4858        let (repo_display_len, branch_display_len) =
4859            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4860                (repo_actual_len, branch_actual_len)
4861            } else if branch_actual_len <= MAX_BRANCH_LEN {
4862                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4863                (repo_space, branch_actual_len)
4864            } else if repo_actual_len <= MAX_REPO_LEN {
4865                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4866                (repo_actual_len, branch_space)
4867            } else {
4868                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4869            };
4870
4871        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4872            active_repo_name.to_string()
4873        } else {
4874            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4875        };
4876
4877        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4878            branch_name
4879        } else {
4880            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4881        };
4882
4883        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4884            .style(ButtonStyle::Transparent)
4885            .size(ButtonSize::None)
4886            .label_size(LabelSize::Small)
4887            .color(Color::Muted);
4888
4889        let repo_selector = PopoverMenu::new("repository-switcher")
4890            .menu({
4891                let project = project;
4892                move |window, cx| {
4893                    let project = project.clone()?;
4894                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4895                }
4896            })
4897            .trigger_with_tooltip(
4898                repo_selector_trigger.disabled(single_repo).truncate(true),
4899                Tooltip::text("Switch Active Repository"),
4900            )
4901            .anchor(Corner::BottomLeft)
4902            .into_any_element();
4903
4904        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4905            .style(ButtonStyle::Transparent)
4906            .size(ButtonSize::None)
4907            .label_size(LabelSize::Small)
4908            .truncate(true)
4909            .tooltip(Tooltip::for_action_title(
4910                "Switch Branch",
4911                &zed_actions::git::Switch,
4912            ))
4913            .on_click(|_, window, cx| {
4914                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4915            });
4916
4917        let branch_selector = PopoverMenu::new("popover-button")
4918            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4919            .trigger_with_tooltip(
4920                branch_selector_button,
4921                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4922            )
4923            .anchor(Corner::BottomLeft)
4924            .offset(gpui::Point {
4925                x: px(0.0),
4926                y: px(-2.0),
4927            });
4928
4929        h_flex()
4930            .w_full()
4931            .px_2()
4932            .h(px(36.))
4933            .items_center()
4934            .justify_between()
4935            .gap_1()
4936            .child(
4937                h_flex()
4938                    .flex_1()
4939                    .overflow_hidden()
4940                    .items_center()
4941                    .child(
4942                        div().child(
4943                            Icon::new(IconName::GitBranchAlt)
4944                                .size(IconSize::Small)
4945                                .color(if single_repo {
4946                                    Color::Disabled
4947                                } else {
4948                                    Color::Muted
4949                                }),
4950                        ),
4951                    )
4952                    .child(repo_selector)
4953                    .when(show_separator, |this| {
4954                        this.child(
4955                            div()
4956                                .text_color(cx.theme().colors().text_muted)
4957                                .text_sm()
4958                                .child("/"),
4959                        )
4960                    })
4961                    .child(branch_selector),
4962            )
4963            .children(if let Some(git_panel) = self.git_panel {
4964                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4965            } else {
4966                None
4967            })
4968    }
4969}
4970
4971impl Component for PanelRepoFooter {
4972    fn scope() -> ComponentScope {
4973        ComponentScope::VersionControl
4974    }
4975
4976    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4977        let unknown_upstream = None;
4978        let no_remote_upstream = Some(UpstreamTracking::Gone);
4979        let ahead_of_upstream = Some(
4980            UpstreamTrackingStatus {
4981                ahead: 2,
4982                behind: 0,
4983            }
4984            .into(),
4985        );
4986        let behind_upstream = Some(
4987            UpstreamTrackingStatus {
4988                ahead: 0,
4989                behind: 2,
4990            }
4991            .into(),
4992        );
4993        let ahead_and_behind_upstream = Some(
4994            UpstreamTrackingStatus {
4995                ahead: 3,
4996                behind: 1,
4997            }
4998            .into(),
4999        );
5000
5001        let not_ahead_or_behind_upstream = Some(
5002            UpstreamTrackingStatus {
5003                ahead: 0,
5004                behind: 0,
5005            }
5006            .into(),
5007        );
5008
5009        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
5010            Branch {
5011                is_head: true,
5012                ref_name: "some-branch".into(),
5013                upstream: upstream.map(|tracking| Upstream {
5014                    ref_name: "origin/some-branch".into(),
5015                    tracking,
5016                }),
5017                most_recent_commit: Some(CommitSummary {
5018                    sha: "abc123".into(),
5019                    subject: "Modify stuff".into(),
5020                    commit_timestamp: 1710932954,
5021                    author_name: "John Doe".into(),
5022                    has_parent: true,
5023                }),
5024            }
5025        }
5026
5027        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
5028            Branch {
5029                is_head: true,
5030                ref_name: branch_name.to_string().into(),
5031                upstream: upstream.map(|tracking| Upstream {
5032                    ref_name: format!("zed/{}", branch_name).into(),
5033                    tracking,
5034                }),
5035                most_recent_commit: Some(CommitSummary {
5036                    sha: "abc123".into(),
5037                    subject: "Modify stuff".into(),
5038                    commit_timestamp: 1710932954,
5039                    author_name: "John Doe".into(),
5040                    has_parent: true,
5041                }),
5042            }
5043        }
5044
5045        fn active_repository(id: usize) -> SharedString {
5046            format!("repo-{}", id).into()
5047        }
5048
5049        let example_width = px(340.);
5050        Some(
5051            v_flex()
5052                .gap_6()
5053                .w_full()
5054                .flex_none()
5055                .children(vec![
5056                    example_group_with_title(
5057                        "Action Button States",
5058                        vec![
5059                            single_example(
5060                                "No Branch",
5061                                div()
5062                                    .w(example_width)
5063                                    .overflow_hidden()
5064                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
5065                                    .into_any_element(),
5066                            ),
5067                            single_example(
5068                                "Remote status unknown",
5069                                div()
5070                                    .w(example_width)
5071                                    .overflow_hidden()
5072                                    .child(PanelRepoFooter::new_preview(
5073                                        active_repository(2),
5074                                        Some(branch(unknown_upstream)),
5075                                    ))
5076                                    .into_any_element(),
5077                            ),
5078                            single_example(
5079                                "No Remote Upstream",
5080                                div()
5081                                    .w(example_width)
5082                                    .overflow_hidden()
5083                                    .child(PanelRepoFooter::new_preview(
5084                                        active_repository(3),
5085                                        Some(branch(no_remote_upstream)),
5086                                    ))
5087                                    .into_any_element(),
5088                            ),
5089                            single_example(
5090                                "Not Ahead or Behind",
5091                                div()
5092                                    .w(example_width)
5093                                    .overflow_hidden()
5094                                    .child(PanelRepoFooter::new_preview(
5095                                        active_repository(4),
5096                                        Some(branch(not_ahead_or_behind_upstream)),
5097                                    ))
5098                                    .into_any_element(),
5099                            ),
5100                            single_example(
5101                                "Behind remote",
5102                                div()
5103                                    .w(example_width)
5104                                    .overflow_hidden()
5105                                    .child(PanelRepoFooter::new_preview(
5106                                        active_repository(5),
5107                                        Some(branch(behind_upstream)),
5108                                    ))
5109                                    .into_any_element(),
5110                            ),
5111                            single_example(
5112                                "Ahead of remote",
5113                                div()
5114                                    .w(example_width)
5115                                    .overflow_hidden()
5116                                    .child(PanelRepoFooter::new_preview(
5117                                        active_repository(6),
5118                                        Some(branch(ahead_of_upstream)),
5119                                    ))
5120                                    .into_any_element(),
5121                            ),
5122                            single_example(
5123                                "Ahead and behind remote",
5124                                div()
5125                                    .w(example_width)
5126                                    .overflow_hidden()
5127                                    .child(PanelRepoFooter::new_preview(
5128                                        active_repository(7),
5129                                        Some(branch(ahead_and_behind_upstream)),
5130                                    ))
5131                                    .into_any_element(),
5132                            ),
5133                        ],
5134                    )
5135                    .grow()
5136                    .vertical(),
5137                ])
5138                .children(vec![
5139                    example_group_with_title(
5140                        "Labels",
5141                        vec![
5142                            single_example(
5143                                "Short Branch & Repo",
5144                                div()
5145                                    .w(example_width)
5146                                    .overflow_hidden()
5147                                    .child(PanelRepoFooter::new_preview(
5148                                        SharedString::from("zed"),
5149                                        Some(custom("main", behind_upstream)),
5150                                    ))
5151                                    .into_any_element(),
5152                            ),
5153                            single_example(
5154                                "Long Branch",
5155                                div()
5156                                    .w(example_width)
5157                                    .overflow_hidden()
5158                                    .child(PanelRepoFooter::new_preview(
5159                                        SharedString::from("zed"),
5160                                        Some(custom(
5161                                            "redesign-and-update-git-ui-list-entry-style",
5162                                            behind_upstream,
5163                                        )),
5164                                    ))
5165                                    .into_any_element(),
5166                            ),
5167                            single_example(
5168                                "Long Repo",
5169                                div()
5170                                    .w(example_width)
5171                                    .overflow_hidden()
5172                                    .child(PanelRepoFooter::new_preview(
5173                                        SharedString::from("zed-industries-community-examples"),
5174                                        Some(custom("gpui", ahead_of_upstream)),
5175                                    ))
5176                                    .into_any_element(),
5177                            ),
5178                            single_example(
5179                                "Long Repo & Branch",
5180                                div()
5181                                    .w(example_width)
5182                                    .overflow_hidden()
5183                                    .child(PanelRepoFooter::new_preview(
5184                                        SharedString::from("zed-industries-community-examples"),
5185                                        Some(custom(
5186                                            "redesign-and-update-git-ui-list-entry-style",
5187                                            behind_upstream,
5188                                        )),
5189                                    ))
5190                                    .into_any_element(),
5191                            ),
5192                            single_example(
5193                                "Uppercase Repo",
5194                                div()
5195                                    .w(example_width)
5196                                    .overflow_hidden()
5197                                    .child(PanelRepoFooter::new_preview(
5198                                        SharedString::from("LICENSES"),
5199                                        Some(custom("main", ahead_of_upstream)),
5200                                    ))
5201                                    .into_any_element(),
5202                            ),
5203                            single_example(
5204                                "Uppercase Branch",
5205                                div()
5206                                    .w(example_width)
5207                                    .overflow_hidden()
5208                                    .child(PanelRepoFooter::new_preview(
5209                                        SharedString::from("zed"),
5210                                        Some(custom("update-README", behind_upstream)),
5211                                    ))
5212                                    .into_any_element(),
5213                            ),
5214                        ],
5215                    )
5216                    .grow()
5217                    .vertical(),
5218                ])
5219                .into_any_element(),
5220        )
5221    }
5222}
5223
5224#[cfg(test)]
5225mod tests {
5226    use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
5227    use gpui::{TestAppContext, VisualTestContext};
5228    use project::{FakeFs, WorktreeSettings};
5229    use serde_json::json;
5230    use settings::SettingsStore;
5231    use theme::LoadThemes;
5232    use util::path;
5233
5234    use super::*;
5235
5236    fn init_test(cx: &mut gpui::TestAppContext) {
5237        zlog::init_test();
5238
5239        cx.update(|cx| {
5240            let settings_store = SettingsStore::test(cx);
5241            cx.set_global(settings_store);
5242            AgentSettings::register(cx);
5243            WorktreeSettings::register(cx);
5244            workspace::init_settings(cx);
5245            theme::init(LoadThemes::JustBase, cx);
5246            language::init(cx);
5247            editor::init(cx);
5248            Project::init_settings(cx);
5249            crate::init(cx);
5250        });
5251    }
5252
5253    #[gpui::test]
5254    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5255        init_test(cx);
5256        let fs = FakeFs::new(cx.background_executor.clone());
5257        fs.insert_tree(
5258            "/root",
5259            json!({
5260                "zed": {
5261                    ".git": {},
5262                    "crates": {
5263                        "gpui": {
5264                            "gpui.rs": "fn main() {}"
5265                        },
5266                        "util": {
5267                            "util.rs": "fn do_it() {}"
5268                        }
5269                    }
5270                },
5271            }),
5272        )
5273        .await;
5274
5275        fs.set_status_for_repo(
5276            Path::new(path!("/root/zed/.git")),
5277            &[
5278                (
5279                    Path::new("crates/gpui/gpui.rs"),
5280                    StatusCode::Modified.worktree(),
5281                ),
5282                (
5283                    Path::new("crates/util/util.rs"),
5284                    StatusCode::Modified.worktree(),
5285                ),
5286            ],
5287        );
5288
5289        let project =
5290            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5291        let workspace =
5292            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5293        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5294
5295        cx.read(|cx| {
5296            project
5297                .read(cx)
5298                .worktrees(cx)
5299                .next()
5300                .unwrap()
5301                .read(cx)
5302                .as_local()
5303                .unwrap()
5304                .scan_complete()
5305        })
5306        .await;
5307
5308        cx.executor().run_until_parked();
5309
5310        let panel = workspace.update(cx, GitPanel::new).unwrap();
5311
5312        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5313            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5314        });
5315        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5316        handle.await;
5317
5318        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5319        pretty_assertions::assert_eq!(
5320            entries,
5321            [
5322                GitListEntry::Header(GitHeaderEntry {
5323                    header: Section::Tracked
5324                }),
5325                GitListEntry::Status(GitStatusEntry {
5326                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5327                    repo_path: "crates/gpui/gpui.rs".into(),
5328                    status: StatusCode::Modified.worktree(),
5329                    staging: StageStatus::Unstaged,
5330                }),
5331                GitListEntry::Status(GitStatusEntry {
5332                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5333                    repo_path: "crates/util/util.rs".into(),
5334                    status: StatusCode::Modified.worktree(),
5335                    staging: StageStatus::Unstaged,
5336                },),
5337            ],
5338        );
5339
5340        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5341            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5342        });
5343        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5344        handle.await;
5345        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5346        pretty_assertions::assert_eq!(
5347            entries,
5348            [
5349                GitListEntry::Header(GitHeaderEntry {
5350                    header: Section::Tracked
5351                }),
5352                GitListEntry::Status(GitStatusEntry {
5353                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5354                    repo_path: "crates/gpui/gpui.rs".into(),
5355                    status: StatusCode::Modified.worktree(),
5356                    staging: StageStatus::Unstaged,
5357                }),
5358                GitListEntry::Status(GitStatusEntry {
5359                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5360                    repo_path: "crates/util/util.rs".into(),
5361                    status: StatusCode::Modified.worktree(),
5362                    staging: StageStatus::Unstaged,
5363                },),
5364            ],
5365        );
5366    }
5367
5368    #[gpui::test]
5369    async fn test_bulk_staging(cx: &mut TestAppContext) {
5370        use GitListEntry::*;
5371
5372        init_test(cx);
5373        let fs = FakeFs::new(cx.background_executor.clone());
5374        fs.insert_tree(
5375            "/root",
5376            json!({
5377                "project": {
5378                    ".git": {},
5379                    "src": {
5380                        "main.rs": "fn main() {}",
5381                        "lib.rs": "pub fn hello() {}",
5382                        "utils.rs": "pub fn util() {}"
5383                    },
5384                    "tests": {
5385                        "test.rs": "fn test() {}"
5386                    },
5387                    "new_file.txt": "new content",
5388                    "another_new.rs": "// new file",
5389                    "conflict.txt": "conflicted content"
5390                }
5391            }),
5392        )
5393        .await;
5394
5395        fs.set_status_for_repo(
5396            Path::new(path!("/root/project/.git")),
5397            &[
5398                (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5399                (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5400                (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5401                (Path::new("new_file.txt"), FileStatus::Untracked),
5402                (Path::new("another_new.rs"), FileStatus::Untracked),
5403                (Path::new("src/utils.rs"), FileStatus::Untracked),
5404                (
5405                    Path::new("conflict.txt"),
5406                    UnmergedStatus {
5407                        first_head: UnmergedStatusCode::Updated,
5408                        second_head: UnmergedStatusCode::Updated,
5409                    }
5410                    .into(),
5411                ),
5412            ],
5413        );
5414
5415        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5416        let workspace =
5417            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5418        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5419
5420        cx.read(|cx| {
5421            project
5422                .read(cx)
5423                .worktrees(cx)
5424                .next()
5425                .unwrap()
5426                .read(cx)
5427                .as_local()
5428                .unwrap()
5429                .scan_complete()
5430        })
5431        .await;
5432
5433        cx.executor().run_until_parked();
5434
5435        let panel = workspace.update(cx, GitPanel::new).unwrap();
5436
5437        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5438            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5439        });
5440        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5441        handle.await;
5442
5443        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5444        #[rustfmt::skip]
5445        pretty_assertions::assert_matches!(
5446            entries.as_slice(),
5447            &[
5448                Header(GitHeaderEntry { header: Section::Conflict }),
5449                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5450                Header(GitHeaderEntry { header: Section::Tracked }),
5451                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5452                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5453                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5454                Header(GitHeaderEntry { header: Section::New }),
5455                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5456                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5457                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5458            ],
5459        );
5460
5461        let second_status_entry = entries[3].clone();
5462        panel.update_in(cx, |panel, window, cx| {
5463            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5464        });
5465
5466        panel.update_in(cx, |panel, window, cx| {
5467            panel.selected_entry = Some(7);
5468            panel.stage_range(&git::StageRange, window, cx);
5469        });
5470
5471        cx.read(|cx| {
5472            project
5473                .read(cx)
5474                .worktrees(cx)
5475                .next()
5476                .unwrap()
5477                .read(cx)
5478                .as_local()
5479                .unwrap()
5480                .scan_complete()
5481        })
5482        .await;
5483
5484        cx.executor().run_until_parked();
5485
5486        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5487            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5488        });
5489        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5490        handle.await;
5491
5492        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5493        #[rustfmt::skip]
5494        pretty_assertions::assert_matches!(
5495            entries.as_slice(),
5496            &[
5497                Header(GitHeaderEntry { header: Section::Conflict }),
5498                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5499                Header(GitHeaderEntry { header: Section::Tracked }),
5500                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5501                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5502                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5503                Header(GitHeaderEntry { header: Section::New }),
5504                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5505                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5506                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5507            ],
5508        );
5509
5510        let third_status_entry = entries[4].clone();
5511        panel.update_in(cx, |panel, window, cx| {
5512            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5513        });
5514
5515        panel.update_in(cx, |panel, window, cx| {
5516            panel.selected_entry = Some(9);
5517            panel.stage_range(&git::StageRange, window, cx);
5518        });
5519
5520        cx.read(|cx| {
5521            project
5522                .read(cx)
5523                .worktrees(cx)
5524                .next()
5525                .unwrap()
5526                .read(cx)
5527                .as_local()
5528                .unwrap()
5529                .scan_complete()
5530        })
5531        .await;
5532
5533        cx.executor().run_until_parked();
5534
5535        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5536            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5537        });
5538        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5539        handle.await;
5540
5541        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5542        #[rustfmt::skip]
5543        pretty_assertions::assert_matches!(
5544            entries.as_slice(),
5545            &[
5546                Header(GitHeaderEntry { header: Section::Conflict }),
5547                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5548                Header(GitHeaderEntry { header: Section::Tracked }),
5549                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5550                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5551                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5552                Header(GitHeaderEntry { header: Section::New }),
5553                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5554                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5555                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5556            ],
5557        );
5558    }
5559
5560    #[gpui::test]
5561    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5562        init_test(cx);
5563        let fs = FakeFs::new(cx.background_executor.clone());
5564        fs.insert_tree(
5565            "/root",
5566            json!({
5567                "project": {
5568                    ".git": {},
5569                    "src": {
5570                        "main.rs": "fn main() {}"
5571                    }
5572                }
5573            }),
5574        )
5575        .await;
5576
5577        fs.set_status_for_repo(
5578            Path::new(path!("/root/project/.git")),
5579            &[(Path::new("src/main.rs"), StatusCode::Modified.worktree())],
5580        );
5581
5582        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5583        let workspace =
5584            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5585        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5586
5587        let panel = workspace.update(cx, GitPanel::new).unwrap();
5588
5589        // Test: User has commit message, enables amend (saves message), then disables (restores message)
5590        panel.update(cx, |panel, cx| {
5591            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5592                let start = buffer.anchor_before(0);
5593                let end = buffer.anchor_after(buffer.len());
5594                buffer.edit([(start..end, "Initial commit message")], None, cx);
5595            });
5596
5597            panel.set_amend_pending(true, cx);
5598            assert!(panel.original_commit_message.is_some());
5599
5600            panel.set_amend_pending(false, cx);
5601            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5602            assert_eq!(current_message, "Initial commit message");
5603            assert!(panel.original_commit_message.is_none());
5604        });
5605
5606        // Test: User has empty commit message, enables amend, then disables (clears message)
5607        panel.update(cx, |panel, cx| {
5608            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5609                let start = buffer.anchor_before(0);
5610                let end = buffer.anchor_after(buffer.len());
5611                buffer.edit([(start..end, "")], None, cx);
5612            });
5613
5614            panel.set_amend_pending(true, cx);
5615            assert!(panel.original_commit_message.is_none());
5616
5617            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5618                let start = buffer.anchor_before(0);
5619                let end = buffer.anchor_after(buffer.len());
5620                buffer.edit([(start..end, "Previous commit message")], None, cx);
5621            });
5622
5623            panel.set_amend_pending(false, cx);
5624            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5625            assert_eq!(current_message, "");
5626        });
5627    }
5628}