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