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