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