git_panel.rs

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