git_panel.rs

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