git_panel.rs

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