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        false,
 362        window,
 363        cx,
 364    );
 365    commit_editor.set_collaboration_hub(Box::new(project));
 366    commit_editor.set_use_autoclose(false);
 367    commit_editor.set_show_gutter(false, cx);
 368    commit_editor.set_show_wrap_guides(false, cx);
 369    commit_editor.set_show_indent_guides(false, 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", 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| repo.reset("HEAD^", ResetMode::Soft, cx))?
1512                        .await??;
1513
1514                    Ok(Some(prior_head))
1515                } else {
1516                    Ok(None)
1517                }
1518            })
1519            .await;
1520
1521            this.update_in(&mut cx, |this, window, cx| {
1522                this.pending_commit.take();
1523                match result {
1524                    Ok(None) => {}
1525                    Ok(Some(prior_commit)) => {
1526                        this.commit_editor.update(cx, |editor, cx| {
1527                            editor.set_text(prior_commit.message, window, cx)
1528                        });
1529                    }
1530                    Err(e) => this.show_error_toast("reset", e, cx),
1531                }
1532            })
1533            .ok();
1534        });
1535
1536        self.pending_commit = Some(task);
1537    }
1538
1539    fn check_for_pushed_commits(
1540        &mut self,
1541        window: &mut Window,
1542        cx: &mut Context<Self>,
1543    ) -> impl Future<Output = Result<bool, anyhow::Error>> {
1544        let repo = self.active_repository.clone();
1545        let mut cx = window.to_async(cx);
1546
1547        async move {
1548            let Some(repo) = repo else {
1549                return Err(anyhow::anyhow!("No active repository"));
1550            };
1551
1552            let pushed_to: Vec<SharedString> = repo
1553                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1554                .await??;
1555
1556            if pushed_to.is_empty() {
1557                Ok(true)
1558            } else {
1559                #[derive(strum::EnumIter, strum::VariantNames)]
1560                #[strum(serialize_all = "title_case")]
1561                enum CancelUncommit {
1562                    Uncommit,
1563                    Cancel,
1564                }
1565                let detail = format!(
1566                    "This commit was already pushed to {}.",
1567                    pushed_to.into_iter().join(", ")
1568                );
1569                let result = cx
1570                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1571                    .await?;
1572
1573                match result {
1574                    CancelUncommit::Cancel => Ok(false),
1575                    CancelUncommit::Uncommit => Ok(true),
1576                }
1577            }
1578        }
1579    }
1580
1581    /// Suggests a commit message based on the changed files and their statuses
1582    pub fn suggest_commit_message(&self) -> Option<String> {
1583        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1584            Some(staged_entry)
1585        } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1586            Some(single_tracked_entry)
1587        } else {
1588            None
1589        }?;
1590
1591        let action_text = if git_status_entry.status.is_deleted() {
1592            Some("Delete")
1593        } else if git_status_entry.status.is_created() {
1594            Some("Create")
1595        } else if git_status_entry.status.is_modified() {
1596            Some("Update")
1597        } else {
1598            None
1599        }?;
1600
1601        let file_name = git_status_entry
1602            .repo_path
1603            .file_name()
1604            .unwrap_or_default()
1605            .to_string_lossy();
1606
1607        Some(format!("{} {}", action_text, file_name))
1608    }
1609
1610    fn generate_commit_message_action(
1611        &mut self,
1612        _: &git::GenerateCommitMessage,
1613        _window: &mut Window,
1614        cx: &mut Context<Self>,
1615    ) {
1616        self.generate_commit_message(cx);
1617    }
1618
1619    /// Generates a commit message using an LLM.
1620    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1621        if !self.can_commit() {
1622            return;
1623        }
1624
1625        let model = match current_language_model(cx) {
1626            Some(value) => value,
1627            None => return,
1628        };
1629
1630        let Some(repo) = self.active_repository.as_ref() else {
1631            return;
1632        };
1633
1634        telemetry::event!("Git Commit Message Generated");
1635
1636        let diff = repo.update(cx, |repo, cx| {
1637            if self.has_staged_changes() {
1638                repo.diff(DiffType::HeadToIndex, cx)
1639            } else {
1640                repo.diff(DiffType::HeadToWorktree, cx)
1641            }
1642        });
1643
1644        self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1645            async move {
1646                let _defer = util::defer({
1647                    let mut cx = cx.clone();
1648                    let this = this.clone();
1649                    move || {
1650                        this.update(&mut cx, |this, _cx| {
1651                            this.generate_commit_message_task.take();
1652                        })
1653                        .ok();
1654                    }
1655                });
1656
1657                let mut diff_text = diff.await??;
1658
1659                const ONE_MB: usize = 1_000_000;
1660                if diff_text.len() > ONE_MB {
1661                    diff_text = diff_text.chars().take(ONE_MB).collect()
1662                }
1663
1664                let subject = this.update(&mut cx, |this, cx| {
1665                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1666                })?;
1667
1668                let text_empty = subject.trim().is_empty();
1669
1670                let content = if text_empty {
1671                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1672                } else {
1673                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1674                };
1675
1676                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1677
1678                let request = LanguageModelRequest {
1679                    messages: vec![LanguageModelRequestMessage {
1680                        role: Role::User,
1681                        content: vec![content.into()],
1682                        cache: false,
1683                    }],
1684                    tools: Vec::new(),
1685                    stop: Vec::new(),
1686                    temperature: None,
1687                };
1688
1689                let stream = model.stream_completion_text(request, &cx);
1690                let mut messages = stream.await?;
1691
1692                if !text_empty {
1693                    this.update(&mut cx, |this, cx| {
1694                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1695                            let insert_position = buffer.anchor_before(buffer.len());
1696                            buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1697                        });
1698                    })?;
1699                }
1700
1701                while let Some(message) = messages.stream.next().await {
1702                    let text = message?;
1703
1704                    this.update(&mut cx, |this, cx| {
1705                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1706                            let insert_position = buffer.anchor_before(buffer.len());
1707                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1708                        });
1709                    })?;
1710                }
1711
1712                anyhow::Ok(())
1713            }
1714            .log_err()
1715        }));
1716    }
1717
1718    fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1719        let suggested_commit_message = self.suggest_commit_message();
1720        let placeholder_text = suggested_commit_message
1721            .as_deref()
1722            .unwrap_or("Enter commit message");
1723
1724        self.commit_editor.update(cx, |editor, cx| {
1725            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1726        });
1727
1728        cx.notify();
1729    }
1730
1731    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1732        if !self.can_push_and_pull(cx) {
1733            return;
1734        }
1735
1736        let Some(repo) = self.active_repository.clone() else {
1737            return;
1738        };
1739        telemetry::event!("Git Fetched");
1740        let guard = self.start_remote_operation();
1741        let askpass = self.askpass_delegate("git fetch", window, cx);
1742        let this = cx.weak_entity();
1743        window
1744            .spawn(cx, |mut cx| async move {
1745                let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1746
1747                let remote_message = fetch.await?;
1748                drop(guard);
1749                this.update(&mut cx, |this, cx| {
1750                    let action = RemoteAction::Fetch;
1751                    match remote_message {
1752                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1753                        Err(e) => {
1754                            log::error!("Error while fetching {:?}", e);
1755                            this.show_error_toast(action.name(), e, cx)
1756                        }
1757                    }
1758
1759                    anyhow::Ok(())
1760                })
1761                .ok();
1762                anyhow::Ok(())
1763            })
1764            .detach_and_log_err(cx);
1765    }
1766
1767    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1768        let worktrees = self
1769            .project
1770            .read(cx)
1771            .visible_worktrees(cx)
1772            .collect::<Vec<_>>();
1773
1774        let worktree = if worktrees.len() == 1 {
1775            Task::ready(Some(worktrees.first().unwrap().clone()))
1776        } else if worktrees.len() == 0 {
1777            let result = window.prompt(
1778                PromptLevel::Warning,
1779                "Unable to initialize a git repository",
1780                Some("Open a directory first"),
1781                &["Ok"],
1782                cx,
1783            );
1784            cx.background_executor()
1785                .spawn(async move {
1786                    result.await.ok();
1787                })
1788                .detach();
1789            return;
1790        } else {
1791            let worktree_directories = worktrees
1792                .iter()
1793                .map(|worktree| worktree.read(cx).abs_path())
1794                .map(|worktree_abs_path| {
1795                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1796                        Path::new("~")
1797                            .join(path)
1798                            .to_string_lossy()
1799                            .to_string()
1800                            .into()
1801                    } else {
1802                        worktree_abs_path.to_string_lossy().to_string().into()
1803                    }
1804                })
1805                .collect_vec();
1806            let prompt = picker_prompt::prompt(
1807                "Where would you like to initialize this git repository?",
1808                worktree_directories,
1809                self.workspace.clone(),
1810                window,
1811                cx,
1812            );
1813
1814            cx.spawn(|_, _| async move { prompt.await.map(|ix| worktrees[ix].clone()) })
1815        };
1816
1817        cx.spawn_in(window, |this, mut cx| async move {
1818            let worktree = match worktree.await {
1819                Some(worktree) => worktree,
1820                None => {
1821                    return;
1822                }
1823            };
1824
1825            let Ok(result) = this.update(&mut cx, |this, cx| {
1826                let fallback_branch_name = GitPanelSettings::get_global(cx)
1827                    .fallback_branch_name
1828                    .clone();
1829                this.project.read(cx).git_init(
1830                    worktree.read(cx).abs_path(),
1831                    fallback_branch_name,
1832                    cx,
1833                )
1834            }) else {
1835                return;
1836            };
1837
1838            let result = result.await;
1839
1840            this.update_in(&mut cx, |this, _, cx| match result {
1841                Ok(()) => {}
1842                Err(e) => this.show_error_toast("init", e, cx),
1843            })
1844            .ok();
1845        })
1846        .detach();
1847    }
1848
1849    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1850        if !self.can_push_and_pull(cx) {
1851            return;
1852        }
1853        let Some(repo) = self.active_repository.clone() else {
1854            return;
1855        };
1856        let Some(branch) = repo.read(cx).current_branch() else {
1857            return;
1858        };
1859        telemetry::event!("Git Pulled");
1860        let branch = branch.clone();
1861        let remote = self.get_current_remote(window, cx);
1862        cx.spawn_in(window, move |this, mut cx| async move {
1863            let remote = match remote.await {
1864                Ok(Some(remote)) => remote,
1865                Ok(None) => {
1866                    return Ok(());
1867                }
1868                Err(e) => {
1869                    log::error!("Failed to get current remote: {}", e);
1870                    this.update(&mut cx, |this, cx| this.show_error_toast("pull", e, cx))
1871                        .ok();
1872                    return Ok(());
1873                }
1874            };
1875
1876            let askpass = this.update_in(&mut cx, |this, window, cx| {
1877                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1878            })?;
1879
1880            let guard = this
1881                .update(&mut cx, |this, _| this.start_remote_operation())
1882                .ok();
1883
1884            let pull = repo.update(&mut cx, |repo, cx| {
1885                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1886            })?;
1887
1888            let remote_message = pull.await?;
1889            drop(guard);
1890
1891            let action = RemoteAction::Pull(remote);
1892            this.update(&mut cx, |this, cx| match remote_message {
1893                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1894                Err(e) => {
1895                    log::error!("Error while pulling {:?}", e);
1896                    this.show_error_toast(action.name(), e, cx)
1897                }
1898            })
1899            .ok();
1900
1901            anyhow::Ok(())
1902        })
1903        .detach_and_log_err(cx);
1904    }
1905
1906    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1907        if !self.can_push_and_pull(cx) {
1908            return;
1909        }
1910        let Some(repo) = self.active_repository.clone() else {
1911            return;
1912        };
1913        let Some(branch) = repo.read(cx).current_branch() else {
1914            return;
1915        };
1916        telemetry::event!("Git Pushed");
1917        let branch = branch.clone();
1918
1919        let options = if force_push {
1920            Some(PushOptions::Force)
1921        } else {
1922            match branch.upstream {
1923                Some(Upstream {
1924                    tracking: UpstreamTracking::Gone,
1925                    ..
1926                })
1927                | None => Some(PushOptions::SetUpstream),
1928                _ => None,
1929            }
1930        };
1931        let remote = self.get_current_remote(window, cx);
1932
1933        cx.spawn_in(window, move |this, mut cx| async move {
1934            let remote = match remote.await {
1935                Ok(Some(remote)) => remote,
1936                Ok(None) => {
1937                    return Ok(());
1938                }
1939                Err(e) => {
1940                    log::error!("Failed to get current remote: {}", e);
1941                    this.update(&mut cx, |this, cx| this.show_error_toast("push", e, cx))
1942                        .ok();
1943                    return Ok(());
1944                }
1945            };
1946
1947            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1948                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1949            })?;
1950
1951            let guard = this
1952                .update(&mut cx, |this, _| this.start_remote_operation())
1953                .ok();
1954
1955            let push = repo.update(&mut cx, |repo, cx| {
1956                repo.push(
1957                    branch.name.clone(),
1958                    remote.name.clone(),
1959                    options,
1960                    askpass_delegate,
1961                    cx,
1962                )
1963            })?;
1964
1965            let remote_output = push.await?;
1966            drop(guard);
1967
1968            let action = RemoteAction::Push(branch.name, remote);
1969            this.update(&mut cx, |this, cx| match remote_output {
1970                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1971                Err(e) => {
1972                    log::error!("Error while pushing {:?}", e);
1973                    this.show_error_toast(action.name(), e, cx)
1974                }
1975            })?;
1976
1977            anyhow::Ok(())
1978        })
1979        .detach_and_log_err(cx);
1980    }
1981
1982    fn askpass_delegate(
1983        &self,
1984        operation: impl Into<SharedString>,
1985        window: &mut Window,
1986        cx: &mut Context<Self>,
1987    ) -> AskPassDelegate {
1988        let this = cx.weak_entity();
1989        let operation = operation.into();
1990        let window = window.window_handle();
1991        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1992            window
1993                .update(cx, |_, window, cx| {
1994                    this.update(cx, |this, cx| {
1995                        this.workspace.update(cx, |workspace, cx| {
1996                            workspace.toggle_modal(window, cx, |window, cx| {
1997                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1998                            });
1999                        })
2000                    })
2001                })
2002                .ok();
2003        })
2004    }
2005
2006    fn can_push_and_pull(&self, cx: &App) -> bool {
2007        crate::can_push_and_pull(&self.project, cx)
2008    }
2009
2010    fn get_current_remote(
2011        &mut self,
2012        window: &mut Window,
2013        cx: &mut Context<Self>,
2014    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
2015        let repo = self.active_repository.clone();
2016        let workspace = self.workspace.clone();
2017        let mut cx = window.to_async(cx);
2018
2019        async move {
2020            let Some(repo) = repo else {
2021                return Err(anyhow::anyhow!("No active repository"));
2022            };
2023
2024            let mut current_remotes: Vec<Remote> = repo
2025                .update(&mut cx, |repo, _| {
2026                    let Some(current_branch) = repo.current_branch() else {
2027                        return Err(anyhow::anyhow!("No active branch"));
2028                    };
2029
2030                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
2031                })??
2032                .await??;
2033
2034            if current_remotes.len() == 0 {
2035                return Err(anyhow::anyhow!("No active remote"));
2036            } else if current_remotes.len() == 1 {
2037                return Ok(Some(current_remotes.pop().unwrap()));
2038            } else {
2039                let current_remotes: Vec<_> = current_remotes
2040                    .into_iter()
2041                    .map(|remotes| remotes.name)
2042                    .collect();
2043                let selection = cx
2044                    .update(|window, cx| {
2045                        picker_prompt::prompt(
2046                            "Pick which remote to push to",
2047                            current_remotes.clone(),
2048                            workspace,
2049                            window,
2050                            cx,
2051                        )
2052                    })?
2053                    .await;
2054
2055                Ok(selection.map(|selection| Remote {
2056                    name: current_remotes[selection].clone(),
2057                }))
2058            }
2059        }
2060    }
2061
2062    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2063        let mut new_co_authors = Vec::new();
2064        let project = self.project.read(cx);
2065
2066        let Some(room) = self
2067            .workspace
2068            .upgrade()
2069            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2070        else {
2071            return Vec::default();
2072        };
2073
2074        let room = room.read(cx);
2075
2076        for (peer_id, collaborator) in project.collaborators() {
2077            if collaborator.is_host {
2078                continue;
2079            }
2080
2081            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2082                continue;
2083            };
2084            if participant.can_write() && participant.user.email.is_some() {
2085                let email = participant.user.email.clone().unwrap();
2086
2087                new_co_authors.push((
2088                    participant
2089                        .user
2090                        .name
2091                        .clone()
2092                        .unwrap_or_else(|| participant.user.github_login.clone()),
2093                    email,
2094                ))
2095            }
2096        }
2097        if !project.is_local() && !project.is_read_only(cx) {
2098            if let Some(user) = room.local_participant_user(cx) {
2099                if let Some(email) = user.email.clone() {
2100                    new_co_authors.push((
2101                        user.name
2102                            .clone()
2103                            .unwrap_or_else(|| user.github_login.clone()),
2104                        email.clone(),
2105                    ))
2106                }
2107            }
2108        }
2109        new_co_authors
2110    }
2111
2112    fn toggle_fill_co_authors(
2113        &mut self,
2114        _: &ToggleFillCoAuthors,
2115        _: &mut Window,
2116        cx: &mut Context<Self>,
2117    ) {
2118        self.add_coauthors = !self.add_coauthors;
2119        cx.notify();
2120    }
2121
2122    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2123        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2124
2125        let existing_text = message.to_ascii_lowercase();
2126        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2127        let mut ends_with_co_authors = false;
2128        let existing_co_authors = existing_text
2129            .lines()
2130            .filter_map(|line| {
2131                let line = line.trim();
2132                if line.starts_with(&lowercase_co_author_prefix) {
2133                    ends_with_co_authors = true;
2134                    Some(line)
2135                } else {
2136                    ends_with_co_authors = false;
2137                    None
2138                }
2139            })
2140            .collect::<HashSet<_>>();
2141
2142        let new_co_authors = self
2143            .potential_co_authors(cx)
2144            .into_iter()
2145            .filter(|(_, email)| {
2146                !existing_co_authors
2147                    .iter()
2148                    .any(|existing| existing.contains(email.as_str()))
2149            })
2150            .collect::<Vec<_>>();
2151
2152        if new_co_authors.is_empty() {
2153            return;
2154        }
2155
2156        if !ends_with_co_authors {
2157            message.push('\n');
2158        }
2159        for (name, email) in new_co_authors {
2160            message.push('\n');
2161            message.push_str(CO_AUTHOR_PREFIX);
2162            message.push_str(&name);
2163            message.push_str(" <");
2164            message.push_str(&email);
2165            message.push('>');
2166        }
2167        message.push('\n');
2168    }
2169
2170    fn schedule_update(
2171        &mut self,
2172        clear_pending: bool,
2173        window: &mut Window,
2174        cx: &mut Context<Self>,
2175    ) {
2176        let handle = cx.entity().downgrade();
2177        self.reopen_commit_buffer(window, cx);
2178        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
2179            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2180            if let Some(git_panel) = handle.upgrade() {
2181                git_panel
2182                    .update_in(&mut cx, |git_panel, window, cx| {
2183                        if clear_pending {
2184                            git_panel.clear_pending();
2185                        }
2186                        git_panel.update_visible_entries(cx);
2187                        git_panel.update_editor_placeholder(cx);
2188                        git_panel.update_scrollbar_properties(window, cx);
2189                    })
2190                    .ok();
2191            }
2192        });
2193    }
2194
2195    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2196        let Some(active_repo) = self.active_repository.as_ref() else {
2197            return;
2198        };
2199        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2200            let project = self.project.read(cx);
2201            active_repo.open_commit_buffer(
2202                Some(project.languages().clone()),
2203                project.buffer_store().clone(),
2204                cx,
2205            )
2206        });
2207
2208        cx.spawn_in(window, |git_panel, mut cx| async move {
2209            let buffer = load_buffer.await?;
2210            git_panel.update_in(&mut cx, |git_panel, window, cx| {
2211                if git_panel
2212                    .commit_editor
2213                    .read(cx)
2214                    .buffer()
2215                    .read(cx)
2216                    .as_singleton()
2217                    .as_ref()
2218                    != Some(&buffer)
2219                {
2220                    git_panel.commit_editor = cx.new(|cx| {
2221                        commit_message_editor(
2222                            buffer,
2223                            git_panel.suggest_commit_message().as_deref(),
2224                            git_panel.project.clone(),
2225                            true,
2226                            window,
2227                            cx,
2228                        )
2229                    });
2230                }
2231            })
2232        })
2233        .detach_and_log_err(cx);
2234    }
2235
2236    fn clear_pending(&mut self) {
2237        self.pending.retain(|v| !v.finished)
2238    }
2239
2240    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2241        self.entries.clear();
2242        self.single_staged_entry.take();
2243        self.single_staged_entry.take();
2244        let mut changed_entries = Vec::new();
2245        let mut new_entries = Vec::new();
2246        let mut conflict_entries = Vec::new();
2247        let mut last_staged = None;
2248        let mut staged_count = 0;
2249        let mut max_width_item: Option<(RepoPath, usize)> = None;
2250
2251        let Some(repo) = self.active_repository.as_ref() else {
2252            // Just clear entries if no repository is active.
2253            cx.notify();
2254            return;
2255        };
2256
2257        let repo = repo.read(cx);
2258
2259        for entry in repo.status() {
2260            let is_conflict = repo.has_conflict(&entry.repo_path);
2261            let is_new = entry.status.is_created();
2262            let staging = entry.status.staging();
2263
2264            if self.pending.iter().any(|pending| {
2265                pending.target_status == TargetStatus::Reverted
2266                    && !pending.finished
2267                    && pending
2268                        .entries
2269                        .iter()
2270                        .any(|pending| pending.repo_path == entry.repo_path)
2271            }) {
2272                continue;
2273            }
2274
2275            // dot_git_abs path always has at least one component, namely .git.
2276            let abs_path = repo
2277                .dot_git_abs_path
2278                .parent()
2279                .unwrap()
2280                .join(&entry.repo_path);
2281            let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2282            let entry = GitStatusEntry {
2283                repo_path: entry.repo_path.clone(),
2284                worktree_path,
2285                abs_path,
2286                status: entry.status,
2287                staging,
2288            };
2289
2290            if staging.has_staged() {
2291                staged_count += 1;
2292                last_staged = Some(entry.clone());
2293            }
2294
2295            let width_estimate = Self::item_width_estimate(
2296                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2297                entry.display_name().len(),
2298            );
2299
2300            match max_width_item.as_mut() {
2301                Some((repo_path, estimate)) => {
2302                    if width_estimate > *estimate {
2303                        *repo_path = entry.repo_path.clone();
2304                        *estimate = width_estimate;
2305                    }
2306                }
2307                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2308            }
2309
2310            if is_conflict {
2311                conflict_entries.push(entry);
2312            } else if is_new {
2313                new_entries.push(entry);
2314            } else {
2315                changed_entries.push(entry);
2316            }
2317        }
2318
2319        let mut pending_staged_count = 0;
2320        let mut last_pending_staged = None;
2321        let mut pending_status_for_last_staged = None;
2322        for pending in self.pending.iter() {
2323            if pending.target_status == TargetStatus::Staged {
2324                pending_staged_count += pending.entries.len();
2325                last_pending_staged = pending.entries.iter().next().cloned();
2326            }
2327            if let Some(last_staged) = &last_staged {
2328                if pending
2329                    .entries
2330                    .iter()
2331                    .any(|entry| entry.repo_path == last_staged.repo_path)
2332                {
2333                    pending_status_for_last_staged = Some(pending.target_status);
2334                }
2335            }
2336        }
2337
2338        if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2339            match pending_status_for_last_staged {
2340                Some(TargetStatus::Staged) | None => {
2341                    self.single_staged_entry = last_staged;
2342                }
2343                _ => {}
2344            }
2345        } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2346            self.single_staged_entry = last_pending_staged;
2347        }
2348
2349        if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2350            self.single_tracked_entry = changed_entries.first().cloned();
2351        }
2352
2353        if conflict_entries.len() > 0 {
2354            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2355                header: Section::Conflict,
2356            }));
2357            self.entries.extend(
2358                conflict_entries
2359                    .into_iter()
2360                    .map(GitListEntry::GitStatusEntry),
2361            );
2362        }
2363
2364        if changed_entries.len() > 0 {
2365            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2366                header: Section::Tracked,
2367            }));
2368            self.entries.extend(
2369                changed_entries
2370                    .into_iter()
2371                    .map(GitListEntry::GitStatusEntry),
2372            );
2373        }
2374        if new_entries.len() > 0 {
2375            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2376                header: Section::New,
2377            }));
2378            self.entries
2379                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2380        }
2381
2382        if let Some((repo_path, _)) = max_width_item {
2383            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2384                GitListEntry::GitStatusEntry(git_status_entry) => {
2385                    git_status_entry.repo_path == repo_path
2386                }
2387                GitListEntry::Header(_) => false,
2388            });
2389        }
2390
2391        self.update_counts(repo);
2392
2393        self.select_first_entry_if_none(cx);
2394
2395        cx.notify();
2396    }
2397
2398    fn header_state(&self, header_type: Section) -> ToggleState {
2399        let (staged_count, count) = match header_type {
2400            Section::New => (self.new_staged_count, self.new_count),
2401            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2402            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2403        };
2404        if staged_count == 0 {
2405            ToggleState::Unselected
2406        } else if count == staged_count {
2407            ToggleState::Selected
2408        } else {
2409            ToggleState::Indeterminate
2410        }
2411    }
2412
2413    fn update_counts(&mut self, repo: &Repository) {
2414        self.conflicted_count = 0;
2415        self.conflicted_staged_count = 0;
2416        self.new_count = 0;
2417        self.tracked_count = 0;
2418        self.new_staged_count = 0;
2419        self.tracked_staged_count = 0;
2420        self.entry_count = 0;
2421        for entry in &self.entries {
2422            let Some(status_entry) = entry.status_entry() else {
2423                continue;
2424            };
2425            self.entry_count += 1;
2426            if repo.has_conflict(&status_entry.repo_path) {
2427                self.conflicted_count += 1;
2428                if self.entry_staging(status_entry).has_staged() {
2429                    self.conflicted_staged_count += 1;
2430                }
2431            } else if status_entry.status.is_created() {
2432                self.new_count += 1;
2433                if self.entry_staging(status_entry).has_staged() {
2434                    self.new_staged_count += 1;
2435                }
2436            } else {
2437                self.tracked_count += 1;
2438                if self.entry_staging(status_entry).has_staged() {
2439                    self.tracked_staged_count += 1;
2440                }
2441            }
2442        }
2443    }
2444
2445    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2446        for pending in self.pending.iter().rev() {
2447            if pending
2448                .entries
2449                .iter()
2450                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2451            {
2452                match pending.target_status {
2453                    TargetStatus::Staged => return StageStatus::Staged,
2454                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2455                    TargetStatus::Reverted => continue,
2456                    TargetStatus::Unchanged => continue,
2457                }
2458            }
2459        }
2460        entry.staging
2461    }
2462
2463    pub(crate) fn has_staged_changes(&self) -> bool {
2464        self.tracked_staged_count > 0
2465            || self.new_staged_count > 0
2466            || self.conflicted_staged_count > 0
2467    }
2468
2469    pub(crate) fn has_unstaged_changes(&self) -> bool {
2470        self.tracked_count > self.tracked_staged_count
2471            || self.new_count > self.new_staged_count
2472            || self.conflicted_count > self.conflicted_staged_count
2473    }
2474
2475    fn has_conflicts(&self) -> bool {
2476        self.conflicted_count > 0
2477    }
2478
2479    fn has_tracked_changes(&self) -> bool {
2480        self.tracked_count > 0
2481    }
2482
2483    pub fn has_unstaged_conflicts(&self) -> bool {
2484        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2485    }
2486
2487    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2488        let action = action.into();
2489        let Some(workspace) = self.workspace.upgrade() else {
2490            return;
2491        };
2492
2493        let message = e.to_string().trim().to_string();
2494        if message
2495            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2496            .next()
2497            .is_some()
2498        {
2499            return; // Hide the cancelled by user message
2500        } else {
2501            let project = self.project.clone();
2502            workspace.update(cx, |workspace, cx| {
2503                let workspace_weak = cx.weak_entity();
2504                let toast =
2505                    StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2506                        this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2507                            .action("View Log", move |window, cx| {
2508                                let message = message.clone();
2509                                let project = project.clone();
2510                                let action = action.clone();
2511                                workspace_weak
2512                                    .update(cx, move |workspace, cx| {
2513                                        Self::open_output(
2514                                            project, action, workspace, &message, window, cx,
2515                                        )
2516                                    })
2517                                    .ok();
2518                            })
2519                    });
2520                workspace.toggle_status_toast(toast, cx)
2521            });
2522        }
2523    }
2524
2525    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2526        let Some(workspace) = self.workspace.upgrade() else {
2527            return;
2528        };
2529
2530        workspace.update(cx, |workspace, cx| {
2531            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2532            let workspace_weak = cx.weak_entity();
2533            let operation = action.name();
2534
2535            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2536                use remote_output::SuccessStyle::*;
2537                let project = self.project.clone();
2538                match style {
2539                    Toast { .. } => this,
2540                    ToastWithLog { output } => this
2541                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2542                        .action("View Log", move |window, cx| {
2543                            let output = output.clone();
2544                            let project = project.clone();
2545                            let output =
2546                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2547                            workspace_weak
2548                                .update(cx, move |workspace, cx| {
2549                                    Self::open_output(
2550                                        project, operation, workspace, &output, window, cx,
2551                                    )
2552                                })
2553                                .ok();
2554                        }),
2555                    PushPrLink { link } => this
2556                        .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2557                        .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2558                }
2559            });
2560            workspace.toggle_status_toast(status_toast, cx)
2561        });
2562    }
2563
2564    fn open_output(
2565        project: Entity<Project>,
2566        operation: impl Into<SharedString>,
2567        workspace: &mut Workspace,
2568        output: &str,
2569        window: &mut Window,
2570        cx: &mut Context<Workspace>,
2571    ) {
2572        let operation = operation.into();
2573        let buffer = cx.new(|cx| Buffer::local(output, cx));
2574        let editor = cx.new(|cx| {
2575            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2576            editor.buffer().update(cx, |buffer, cx| {
2577                buffer.set_title(format!("Output from git {operation}"), cx);
2578            });
2579            editor.set_read_only(true);
2580            editor
2581        });
2582
2583        workspace.add_item_to_center(Box::new(editor), window, cx);
2584    }
2585
2586    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2587        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2588            Icon::new(IconName::ArrowCircle)
2589                .size(IconSize::XSmall)
2590                .color(Color::Info)
2591                .with_animation(
2592                    "arrow-circle",
2593                    Animation::new(Duration::from_secs(2)).repeat(),
2594                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2595                )
2596                .into_any_element()
2597        })
2598    }
2599
2600    pub fn can_commit(&self) -> bool {
2601        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2602    }
2603
2604    pub fn can_stage_all(&self) -> bool {
2605        self.has_unstaged_changes()
2606    }
2607
2608    pub fn can_unstage_all(&self) -> bool {
2609        self.has_staged_changes()
2610    }
2611
2612    // eventually we'll need to take depth into account here
2613    // if we add a tree view
2614    fn item_width_estimate(path: usize, file_name: usize) -> usize {
2615        path + file_name
2616    }
2617
2618    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2619        let focus_handle = self.focus_handle.clone();
2620        PopoverMenu::new(id.into())
2621            .trigger(
2622                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2623                    .icon_size(IconSize::Small)
2624                    .icon_color(Color::Muted),
2625            )
2626            .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
2627            .anchor(Corner::TopRight)
2628    }
2629
2630    pub(crate) fn render_generate_commit_message_button(
2631        &self,
2632        cx: &Context<Self>,
2633    ) -> Option<AnyElement> {
2634        current_language_model(cx).is_some().then(|| {
2635            if self.generate_commit_message_task.is_some() {
2636                return h_flex()
2637                    .gap_1()
2638                    .child(
2639                        Icon::new(IconName::ArrowCircle)
2640                            .size(IconSize::XSmall)
2641                            .color(Color::Info)
2642                            .with_animation(
2643                                "arrow-circle",
2644                                Animation::new(Duration::from_secs(2)).repeat(),
2645                                |icon, delta| {
2646                                    icon.transform(Transformation::rotate(percentage(delta)))
2647                                },
2648                            ),
2649                    )
2650                    .child(
2651                        Label::new("Generating Commit...")
2652                            .size(LabelSize::Small)
2653                            .color(Color::Muted),
2654                    )
2655                    .into_any_element();
2656            }
2657
2658            let can_commit = self.can_commit();
2659            let editor_focus_handle = self.commit_editor.focus_handle(cx);
2660            IconButton::new("generate-commit-message", IconName::AiEdit)
2661                .shape(ui::IconButtonShape::Square)
2662                .icon_color(Color::Muted)
2663                .tooltip(move |window, cx| {
2664                    if can_commit {
2665                        Tooltip::for_action_in(
2666                            "Generate Commit Message",
2667                            &git::GenerateCommitMessage,
2668                            &editor_focus_handle,
2669                            window,
2670                            cx,
2671                        )
2672                    } else {
2673                        Tooltip::simple("No changes to commit", cx)
2674                    }
2675                })
2676                .disabled(!can_commit)
2677                .on_click(cx.listener(move |this, _event, _window, cx| {
2678                    this.generate_commit_message(cx);
2679                }))
2680                .into_any_element()
2681        })
2682    }
2683
2684    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2685        let potential_co_authors = self.potential_co_authors(cx);
2686        if potential_co_authors.is_empty() {
2687            None
2688        } else {
2689            Some(
2690                IconButton::new("co-authors", IconName::Person)
2691                    .shape(ui::IconButtonShape::Square)
2692                    .icon_color(Color::Disabled)
2693                    .selected_icon_color(Color::Selected)
2694                    .toggle_state(self.add_coauthors)
2695                    .tooltip(move |_, cx| {
2696                        let title = format!(
2697                            "Add co-authored-by:{}{}",
2698                            if potential_co_authors.len() == 1 {
2699                                ""
2700                            } else {
2701                                "\n"
2702                            },
2703                            potential_co_authors
2704                                .iter()
2705                                .map(|(name, email)| format!(" {} <{}>", name, email))
2706                                .join("\n")
2707                        );
2708                        Tooltip::simple(title, cx)
2709                    })
2710                    .on_click(cx.listener(|this, _, _, cx| {
2711                        this.add_coauthors = !this.add_coauthors;
2712                        cx.notify();
2713                    }))
2714                    .into_any_element(),
2715            )
2716        }
2717    }
2718
2719    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2720        if self.has_unstaged_conflicts() {
2721            (false, "You must resolve conflicts before committing")
2722        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2723            (false, "No changes to commit")
2724        } else if self.pending_commit.is_some() {
2725            (false, "Commit in progress")
2726        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2727            (false, "No commit message")
2728        } else if !self.has_write_access(cx) {
2729            (false, "You do not have write access to this project")
2730        } else {
2731            (true, self.commit_button_title())
2732        }
2733    }
2734
2735    pub fn commit_button_title(&self) -> &'static str {
2736        if self.has_staged_changes() {
2737            "Commit"
2738        } else {
2739            "Commit Tracked"
2740        }
2741    }
2742
2743    fn expand_commit_editor(
2744        &mut self,
2745        _: &git::ExpandCommitEditor,
2746        window: &mut Window,
2747        cx: &mut Context<Self>,
2748    ) {
2749        let workspace = self.workspace.clone();
2750        window.defer(cx, move |window, cx| {
2751            workspace
2752                .update(cx, |workspace, cx| {
2753                    CommitModal::toggle(workspace, window, cx)
2754                })
2755                .ok();
2756        })
2757    }
2758
2759    fn render_panel_header(
2760        &self,
2761        window: &mut Window,
2762        cx: &mut Context<Self>,
2763    ) -> Option<impl IntoElement> {
2764        self.active_repository.as_ref()?;
2765
2766        let text;
2767        let action;
2768        let tooltip;
2769        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2770            text = "Unstage All";
2771            action = git::UnstageAll.boxed_clone();
2772            tooltip = "git reset";
2773        } else {
2774            text = "Stage All";
2775            action = git::StageAll.boxed_clone();
2776            tooltip = "git add --all ."
2777        }
2778
2779        let change_string = match self.entry_count {
2780            0 => "No Changes".to_string(),
2781            1 => "1 Change".to_string(),
2782            _ => format!("{} Changes", self.entry_count),
2783        };
2784
2785        Some(
2786            self.panel_header_container(window, cx)
2787                .px_2()
2788                .child(
2789                    panel_button(change_string)
2790                        .color(Color::Muted)
2791                        .tooltip(Tooltip::for_action_title_in(
2792                            "Open diff",
2793                            &Diff,
2794                            &self.focus_handle,
2795                        ))
2796                        .on_click(|_, _, cx| {
2797                            cx.defer(|cx| {
2798                                cx.dispatch_action(&Diff);
2799                            })
2800                        }),
2801                )
2802                .child(div().flex_grow()) // spacer
2803                .child(self.render_overflow_menu("overflow_menu"))
2804                .child(div().w_2()) // another spacer
2805                .child(
2806                    panel_filled_button(text)
2807                        .tooltip(Tooltip::for_action_title_in(
2808                            tooltip,
2809                            action.as_ref(),
2810                            &self.focus_handle,
2811                        ))
2812                        .disabled(self.entry_count == 0)
2813                        .on_click(move |_, _, cx| {
2814                            let action = action.boxed_clone();
2815                            cx.defer(move |cx| {
2816                                cx.dispatch_action(action.as_ref());
2817                            })
2818                        }),
2819                ),
2820        )
2821    }
2822
2823    pub fn render_footer(
2824        &self,
2825        window: &mut Window,
2826        cx: &mut Context<Self>,
2827    ) -> Option<impl IntoElement> {
2828        let active_repository = self.active_repository.clone()?;
2829        let (can_commit, tooltip) = self.configure_commit_button(cx);
2830        let project = self.project.clone().read(cx);
2831        let panel_editor_style = panel_editor_style(true, window, cx);
2832
2833        let enable_coauthors = self.render_co_authors(cx);
2834        let title = self.commit_button_title();
2835
2836        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2837        let commit_tooltip_focus_handle = editor_focus_handle.clone();
2838        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2839
2840        let branch = active_repository.read(cx).current_branch().cloned();
2841
2842        let footer_size = px(32.);
2843        let gap = px(9.0);
2844        let max_height = panel_editor_style
2845            .text
2846            .line_height_in_pixels(window.rem_size())
2847            * MAX_PANEL_EDITOR_LINES
2848            + gap;
2849
2850        let git_panel = cx.entity().clone();
2851        let display_name = SharedString::from(Arc::from(
2852            active_repository
2853                .read(cx)
2854                .display_name(project, cx)
2855                .trim_end_matches("/"),
2856        ));
2857        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2858            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
2859        });
2860
2861        let footer = v_flex()
2862            .child(PanelRepoFooter::new(
2863                "footer-button",
2864                display_name,
2865                branch,
2866                Some(git_panel),
2867            ))
2868            .child(
2869                panel_editor_container(window, cx)
2870                    .id("commit-editor-container")
2871                    .relative()
2872                    .w_full()
2873                    .h(max_height + footer_size)
2874                    .border_t_1()
2875                    .border_color(cx.theme().colors().border_variant)
2876                    .cursor_text()
2877                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2878                        window.focus(&this.commit_editor.focus_handle(cx));
2879                    }))
2880                    .child(
2881                        h_flex()
2882                            .id("commit-footer")
2883                            .border_t_1()
2884                            .when(editor_is_long, |el| {
2885                                el.border_color(cx.theme().colors().border_variant)
2886                            })
2887                            .absolute()
2888                            .bottom_0()
2889                            .left_0()
2890                            .w_full()
2891                            .px_2()
2892                            .h(footer_size)
2893                            .flex_none()
2894                            .justify_between()
2895                            .child(
2896                                self.render_generate_commit_message_button(cx)
2897                                    .unwrap_or_else(|| div().into_any_element()),
2898                            )
2899                            .child(
2900                                h_flex().gap_0p5().children(enable_coauthors).child(
2901                                    panel_filled_button(title)
2902                                        .tooltip(move |window, cx| {
2903                                            if can_commit {
2904                                                Tooltip::for_action_in(
2905                                                    tooltip,
2906                                                    &Commit,
2907                                                    &commit_tooltip_focus_handle,
2908                                                    window,
2909                                                    cx,
2910                                                )
2911                                            } else {
2912                                                Tooltip::simple(tooltip, cx)
2913                                            }
2914                                        })
2915                                        .disabled(!can_commit || self.modal_open)
2916                                        .on_click({
2917                                            cx.listener(move |this, _: &ClickEvent, window, cx| {
2918                                                this.commit_changes(window, cx)
2919                                            })
2920                                        }),
2921                                ),
2922                            ),
2923                    )
2924                    .child(
2925                        div()
2926                            .pr_2p5()
2927                            .on_action(|&editor::actions::MoveUp, _, cx| {
2928                                cx.stop_propagation();
2929                            })
2930                            .on_action(|&editor::actions::MoveDown, _, cx| {
2931                                cx.stop_propagation();
2932                            })
2933                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2934                    )
2935                    .child(
2936                        h_flex()
2937                            .absolute()
2938                            .top_2()
2939                            .right_2()
2940                            .opacity(0.5)
2941                            .hover(|this| this.opacity(1.0))
2942                            .child(
2943                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2944                                    .icon_size(IconSize::Small)
2945                                    .size(ui::ButtonSize::Default)
2946                                    .tooltip(move |window, cx| {
2947                                        Tooltip::for_action_in(
2948                                            "Open Commit Modal",
2949                                            &git::ExpandCommitEditor,
2950                                            &expand_tooltip_focus_handle,
2951                                            window,
2952                                            cx,
2953                                        )
2954                                    })
2955                                    .on_click(cx.listener({
2956                                        move |_, _, window, cx| {
2957                                            window.dispatch_action(
2958                                                git::ExpandCommitEditor.boxed_clone(),
2959                                                cx,
2960                                            )
2961                                        }
2962                                    })),
2963                            ),
2964                    ),
2965            );
2966
2967        Some(footer)
2968    }
2969
2970    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2971        let active_repository = self.active_repository.as_ref()?;
2972        let branch = active_repository.read(cx).current_branch()?;
2973        let commit = branch.most_recent_commit.as_ref()?.clone();
2974
2975        let this = cx.entity();
2976        Some(
2977            h_flex()
2978                .items_center()
2979                .py_2()
2980                .px(px(8.))
2981                .border_color(cx.theme().colors().border)
2982                .gap_1p5()
2983                .child(
2984                    div()
2985                        .flex_grow()
2986                        .overflow_hidden()
2987                        .items_center()
2988                        .max_w(relative(0.85))
2989                        .h_full()
2990                        .child(
2991                            Label::new(commit.subject.clone())
2992                                .size(LabelSize::Small)
2993                                .truncate(),
2994                        )
2995                        .id("commit-msg-hover")
2996                        .hoverable_tooltip(move |window, cx| {
2997                            GitPanelMessageTooltip::new(
2998                                this.clone(),
2999                                commit.sha.clone(),
3000                                window,
3001                                cx,
3002                            )
3003                            .into()
3004                        }),
3005                )
3006                .child(div().flex_1())
3007                .when(commit.has_parent, |this| {
3008                    let has_unstaged = self.has_unstaged_changes();
3009                    this.child(
3010                        panel_icon_button("undo", IconName::Undo)
3011                            .icon_size(IconSize::Small)
3012                            .icon_color(Color::Muted)
3013                            .tooltip(move |window, cx| {
3014                                Tooltip::with_meta(
3015                                    "Uncommit",
3016                                    Some(&git::Uncommit),
3017                                    if has_unstaged {
3018                                        "git reset HEAD^ --soft"
3019                                    } else {
3020                                        "git reset HEAD^"
3021                                    },
3022                                    window,
3023                                    cx,
3024                                )
3025                            })
3026                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3027                    )
3028                }),
3029        )
3030    }
3031
3032    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3033        h_flex()
3034            .h_full()
3035            .flex_grow()
3036            .justify_center()
3037            .items_center()
3038            .child(
3039                v_flex()
3040                    .gap_2()
3041                    .child(h_flex().w_full().justify_around().child(
3042                        if self.active_repository.is_some() {
3043                            "No changes to commit"
3044                        } else {
3045                            "No Git repositories"
3046                        },
3047                    ))
3048                    .children(self.active_repository.is_none().then(|| {
3049                        h_flex().w_full().justify_around().child(
3050                            panel_filled_button("Initialize Repository")
3051                                .tooltip(Tooltip::for_action_title_in(
3052                                    "git init",
3053                                    &git::Init,
3054                                    &self.focus_handle,
3055                                ))
3056                                .on_click(move |_, _, cx| {
3057                                    cx.defer(move |cx| {
3058                                        cx.dispatch_action(&git::Init);
3059                                    })
3060                                }),
3061                        )
3062                    }))
3063                    .text_ui_sm(cx)
3064                    .mx_auto()
3065                    .text_color(Color::Placeholder.color(cx)),
3066            )
3067    }
3068
3069    fn render_vertical_scrollbar(
3070        &self,
3071        show_horizontal_scrollbar_container: bool,
3072        cx: &mut Context<Self>,
3073    ) -> impl IntoElement {
3074        div()
3075            .id("git-panel-vertical-scroll")
3076            .occlude()
3077            .flex_none()
3078            .h_full()
3079            .cursor_default()
3080            .absolute()
3081            .right_0()
3082            .top_0()
3083            .bottom_0()
3084            .w(px(12.))
3085            .when(show_horizontal_scrollbar_container, |this| {
3086                this.pb_neg_3p5()
3087            })
3088            .on_mouse_move(cx.listener(|_, _, _, cx| {
3089                cx.notify();
3090                cx.stop_propagation()
3091            }))
3092            .on_hover(|_, _, cx| {
3093                cx.stop_propagation();
3094            })
3095            .on_any_mouse_down(|_, _, cx| {
3096                cx.stop_propagation();
3097            })
3098            .on_mouse_up(
3099                MouseButton::Left,
3100                cx.listener(|this, _, window, cx| {
3101                    if !this.vertical_scrollbar.state.is_dragging()
3102                        && !this.focus_handle.contains_focused(window, cx)
3103                    {
3104                        this.vertical_scrollbar.hide(window, cx);
3105                        cx.notify();
3106                    }
3107
3108                    cx.stop_propagation();
3109                }),
3110            )
3111            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3112                cx.notify();
3113            }))
3114            .children(Scrollbar::vertical(
3115                // percentage as f32..end_offset as f32,
3116                self.vertical_scrollbar.state.clone(),
3117            ))
3118    }
3119
3120    /// Renders the horizontal scrollbar.
3121    ///
3122    /// The right offset is used to determine how far to the right the
3123    /// scrollbar should extend to, useful for ensuring it doesn't collide
3124    /// with the vertical scrollbar when visible.
3125    fn render_horizontal_scrollbar(
3126        &self,
3127        right_offset: Pixels,
3128        cx: &mut Context<Self>,
3129    ) -> impl IntoElement {
3130        div()
3131            .id("git-panel-horizontal-scroll")
3132            .occlude()
3133            .flex_none()
3134            .w_full()
3135            .cursor_default()
3136            .absolute()
3137            .bottom_neg_px()
3138            .left_0()
3139            .right_0()
3140            .pr(right_offset)
3141            .on_mouse_move(cx.listener(|_, _, _, cx| {
3142                cx.notify();
3143                cx.stop_propagation()
3144            }))
3145            .on_hover(|_, _, cx| {
3146                cx.stop_propagation();
3147            })
3148            .on_any_mouse_down(|_, _, cx| {
3149                cx.stop_propagation();
3150            })
3151            .on_mouse_up(
3152                MouseButton::Left,
3153                cx.listener(|this, _, window, cx| {
3154                    if !this.horizontal_scrollbar.state.is_dragging()
3155                        && !this.focus_handle.contains_focused(window, cx)
3156                    {
3157                        this.horizontal_scrollbar.hide(window, cx);
3158                        cx.notify();
3159                    }
3160
3161                    cx.stop_propagation();
3162                }),
3163            )
3164            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3165                cx.notify();
3166            }))
3167            .children(Scrollbar::horizontal(
3168                // percentage as f32..end_offset as f32,
3169                self.horizontal_scrollbar.state.clone(),
3170            ))
3171    }
3172
3173    fn render_buffer_header_controls(
3174        &self,
3175        entity: &Entity<Self>,
3176        file: &Arc<dyn File>,
3177        _: &Window,
3178        cx: &App,
3179    ) -> Option<AnyElement> {
3180        let repo = self.active_repository.as_ref()?.read(cx);
3181        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
3182        let ix = self.entry_by_path(&repo_path)?;
3183        let entry = self.entries.get(ix)?;
3184
3185        let entry_staging = self.entry_staging(entry.status_entry()?);
3186
3187        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3188            .disabled(!self.has_write_access(cx))
3189            .fill()
3190            .elevation(ElevationIndex::Surface)
3191            .on_click({
3192                let entry = entry.clone();
3193                let git_panel = entity.downgrade();
3194                move |_, window, cx| {
3195                    git_panel
3196                        .update(cx, |this, cx| {
3197                            this.toggle_staged_for_entry(&entry, window, cx);
3198                            cx.stop_propagation();
3199                        })
3200                        .ok();
3201                }
3202            });
3203        Some(
3204            h_flex()
3205                .id("start-slot")
3206                .text_lg()
3207                .child(checkbox)
3208                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3209                    // prevent the list item active state triggering when toggling checkbox
3210                    cx.stop_propagation();
3211                })
3212                .into_any_element(),
3213        )
3214    }
3215
3216    fn render_entries(
3217        &self,
3218        has_write_access: bool,
3219        _: &Window,
3220        cx: &mut Context<Self>,
3221    ) -> impl IntoElement {
3222        let entry_count = self.entries.len();
3223
3224        let scroll_track_size = px(16.);
3225
3226        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3227            // magic number
3228            px(3.)
3229        } else {
3230            px(0.)
3231        };
3232
3233        v_flex()
3234            .flex_1()
3235            .size_full()
3236            .overflow_hidden()
3237            .relative()
3238            // Show a border on the top and bottom of the container when
3239            // the vertical scrollbar container is visible so we don't have a
3240            // floating left border in the panel.
3241            .when(self.vertical_scrollbar.show_track, |this| {
3242                this.border_t_1()
3243                    .border_b_1()
3244                    .border_color(cx.theme().colors().border)
3245            })
3246            .child(
3247                h_flex()
3248                    .flex_1()
3249                    .size_full()
3250                    .relative()
3251                    .overflow_hidden()
3252                    .child(
3253                        uniform_list(cx.entity().clone(), "entries", entry_count, {
3254                            move |this, range, window, cx| {
3255                                let mut items = Vec::with_capacity(range.end - range.start);
3256
3257                                for ix in range {
3258                                    match &this.entries.get(ix) {
3259                                        Some(GitListEntry::GitStatusEntry(entry)) => {
3260                                            items.push(this.render_entry(
3261                                                ix,
3262                                                entry,
3263                                                has_write_access,
3264                                                window,
3265                                                cx,
3266                                            ));
3267                                        }
3268                                        Some(GitListEntry::Header(header)) => {
3269                                            items.push(this.render_list_header(
3270                                                ix,
3271                                                header,
3272                                                has_write_access,
3273                                                window,
3274                                                cx,
3275                                            ));
3276                                        }
3277                                        None => {}
3278                                    }
3279                                }
3280
3281                                items
3282                            }
3283                        })
3284                        .size_full()
3285                        .flex_grow()
3286                        .with_sizing_behavior(ListSizingBehavior::Auto)
3287                        .with_horizontal_sizing_behavior(
3288                            ListHorizontalSizingBehavior::Unconstrained,
3289                        )
3290                        .with_width_from_item(self.max_width_item_index)
3291                        .track_scroll(self.scroll_handle.clone()),
3292                    )
3293                    .on_mouse_down(
3294                        MouseButton::Right,
3295                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3296                            this.deploy_panel_context_menu(event.position, window, cx)
3297                        }),
3298                    )
3299                    .when(self.vertical_scrollbar.show_track, |this| {
3300                        this.child(
3301                            v_flex()
3302                                .h_full()
3303                                .flex_none()
3304                                .w(scroll_track_size)
3305                                .bg(cx.theme().colors().panel_background)
3306                                .child(
3307                                    div()
3308                                        .size_full()
3309                                        .flex_1()
3310                                        .border_l_1()
3311                                        .border_color(cx.theme().colors().border),
3312                                ),
3313                        )
3314                    })
3315                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
3316                        this.child(
3317                            self.render_vertical_scrollbar(
3318                                self.horizontal_scrollbar.show_track,
3319                                cx,
3320                            ),
3321                        )
3322                    }),
3323            )
3324            .when(self.horizontal_scrollbar.show_track, |this| {
3325                this.child(
3326                    h_flex()
3327                        .w_full()
3328                        .h(scroll_track_size)
3329                        .flex_none()
3330                        .relative()
3331                        .child(
3332                            div()
3333                                .w_full()
3334                                .flex_1()
3335                                // for some reason the horizontal scrollbar is 1px
3336                                // taller than the vertical scrollbar??
3337                                .h(scroll_track_size - px(1.))
3338                                .bg(cx.theme().colors().panel_background)
3339                                .border_t_1()
3340                                .border_color(cx.theme().colors().border),
3341                        )
3342                        .when(self.vertical_scrollbar.show_track, |this| {
3343                            this.child(
3344                                div()
3345                                    .flex_none()
3346                                    // -1px prevents a missing pixel between the two container borders
3347                                    .w(scroll_track_size - px(1.))
3348                                    .h_full(),
3349                            )
3350                            .child(
3351                                // HACK: Fill the missing 1px 🥲
3352                                div()
3353                                    .absolute()
3354                                    .right(scroll_track_size - px(1.))
3355                                    .bottom(scroll_track_size - px(1.))
3356                                    .size_px()
3357                                    .bg(cx.theme().colors().border),
3358                            )
3359                        }),
3360                )
3361            })
3362            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3363                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3364            })
3365    }
3366
3367    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3368        Label::new(label.into()).color(color).single_line()
3369    }
3370
3371    fn list_item_height(&self) -> Rems {
3372        rems(1.75)
3373    }
3374
3375    fn render_list_header(
3376        &self,
3377        ix: usize,
3378        header: &GitHeaderEntry,
3379        _: bool,
3380        _: &Window,
3381        _: &Context<Self>,
3382    ) -> AnyElement {
3383        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3384
3385        h_flex()
3386            .id(id)
3387            .h(self.list_item_height())
3388            .w_full()
3389            .items_end()
3390            .px(rems(0.75)) // ~12px
3391            .pb(rems(0.3125)) // ~ 5px
3392            .child(
3393                Label::new(header.title())
3394                    .color(Color::Muted)
3395                    .size(LabelSize::Small)
3396                    .line_height_style(LineHeightStyle::UiLabel)
3397                    .single_line(),
3398            )
3399            .into_any_element()
3400    }
3401
3402    fn load_commit_details(
3403        &self,
3404        sha: &str,
3405        cx: &mut Context<Self>,
3406    ) -> Task<anyhow::Result<CommitDetails>> {
3407        let Some(repo) = self.active_repository.clone() else {
3408            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3409        };
3410        repo.update(cx, |repo, cx| {
3411            let show = repo.show(sha);
3412            cx.spawn(|_, _| async move { show.await? })
3413        })
3414    }
3415
3416    fn deploy_entry_context_menu(
3417        &mut self,
3418        position: Point<Pixels>,
3419        ix: usize,
3420        window: &mut Window,
3421        cx: &mut Context<Self>,
3422    ) {
3423        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3424            return;
3425        };
3426        let stage_title = if entry.status.staging().is_fully_staged() {
3427            "Unstage File"
3428        } else {
3429            "Stage File"
3430        };
3431        let restore_title = if entry.status.is_created() {
3432            "Trash File"
3433        } else {
3434            "Restore File"
3435        };
3436        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3437            context_menu
3438                .context(self.focus_handle.clone())
3439                .action(stage_title, ToggleStaged.boxed_clone())
3440                .action(restore_title, git::RestoreFile.boxed_clone())
3441                .separator()
3442                .action("Open Diff", Confirm.boxed_clone())
3443                .action("Open File", SecondaryConfirm.boxed_clone())
3444        });
3445        self.selected_entry = Some(ix);
3446        self.set_context_menu(context_menu, position, window, cx);
3447    }
3448
3449    fn deploy_panel_context_menu(
3450        &mut self,
3451        position: Point<Pixels>,
3452        window: &mut Window,
3453        cx: &mut Context<Self>,
3454    ) {
3455        let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3456        self.set_context_menu(context_menu, position, window, cx);
3457    }
3458
3459    fn set_context_menu(
3460        &mut self,
3461        context_menu: Entity<ContextMenu>,
3462        position: Point<Pixels>,
3463        window: &Window,
3464        cx: &mut Context<Self>,
3465    ) {
3466        let subscription = cx.subscribe_in(
3467            &context_menu,
3468            window,
3469            |this, _, _: &DismissEvent, window, cx| {
3470                if this.context_menu.as_ref().is_some_and(|context_menu| {
3471                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3472                }) {
3473                    cx.focus_self(window);
3474                }
3475                this.context_menu.take();
3476                cx.notify();
3477            },
3478        );
3479        self.context_menu = Some((context_menu, position, subscription));
3480        cx.notify();
3481    }
3482
3483    fn render_entry(
3484        &self,
3485        ix: usize,
3486        entry: &GitStatusEntry,
3487        has_write_access: bool,
3488        window: &Window,
3489        cx: &Context<Self>,
3490    ) -> AnyElement {
3491        let display_name = entry.display_name();
3492
3493        let selected = self.selected_entry == Some(ix);
3494        let marked = self.marked_entries.contains(&ix);
3495        let status_style = GitPanelSettings::get_global(cx).status_style;
3496        let status = entry.status;
3497        let modifiers = self.current_modifiers;
3498        let shift_held = modifiers.shift;
3499
3500        let has_conflict = status.is_conflicted();
3501        let is_modified = status.is_modified();
3502        let is_deleted = status.is_deleted();
3503
3504        let label_color = if status_style == StatusStyle::LabelColor {
3505            if has_conflict {
3506                Color::Conflict
3507            } else if is_modified {
3508                Color::Modified
3509            } else if is_deleted {
3510                // We don't want a bunch of red labels in the list
3511                Color::Disabled
3512            } else {
3513                Color::Created
3514            }
3515        } else {
3516            Color::Default
3517        };
3518
3519        let path_color = if status.is_deleted() {
3520            Color::Disabled
3521        } else {
3522            Color::Muted
3523        };
3524
3525        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3526        let checkbox_wrapper_id: ElementId =
3527            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3528        let checkbox_id: ElementId =
3529            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3530
3531        let entry_staging = self.entry_staging(entry);
3532        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3533
3534        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3535            is_staged = ToggleState::Selected;
3536        }
3537
3538        let handle = cx.weak_entity();
3539
3540        let selected_bg_alpha = 0.08;
3541        let marked_bg_alpha = 0.12;
3542        let state_opacity_step = 0.04;
3543
3544        let base_bg = match (selected, marked) {
3545            (true, true) => cx
3546                .theme()
3547                .status()
3548                .info
3549                .alpha(selected_bg_alpha + marked_bg_alpha),
3550            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3551            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3552            _ => cx.theme().colors().ghost_element_background,
3553        };
3554
3555        let hover_bg = if selected {
3556            cx.theme()
3557                .status()
3558                .info
3559                .alpha(selected_bg_alpha + state_opacity_step)
3560        } else {
3561            cx.theme().colors().ghost_element_hover
3562        };
3563
3564        let active_bg = if selected {
3565            cx.theme()
3566                .status()
3567                .info
3568                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3569        } else {
3570            cx.theme().colors().ghost_element_active
3571        };
3572
3573        h_flex()
3574            .id(id)
3575            .h(self.list_item_height())
3576            .w_full()
3577            .items_center()
3578            .border_1()
3579            .when(selected && self.focus_handle.is_focused(window), |el| {
3580                el.border_color(cx.theme().colors().border_focused)
3581            })
3582            .px(rems(0.75)) // ~12px
3583            .overflow_hidden()
3584            .flex_none()
3585            .gap_1p5()
3586            .bg(base_bg)
3587            .hover(|this| this.bg(hover_bg))
3588            .active(|this| this.bg(active_bg))
3589            .on_click({
3590                cx.listener(move |this, event: &ClickEvent, window, cx| {
3591                    this.selected_entry = Some(ix);
3592                    cx.notify();
3593                    if event.modifiers().secondary() {
3594                        this.open_file(&Default::default(), window, cx)
3595                    } else {
3596                        this.open_diff(&Default::default(), window, cx);
3597                        this.focus_handle.focus(window);
3598                    }
3599                })
3600            })
3601            .on_mouse_down(
3602                MouseButton::Right,
3603                move |event: &MouseDownEvent, window, cx| {
3604                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3605                    if event.button != MouseButton::Right {
3606                        return;
3607                    }
3608
3609                    let Some(this) = handle.upgrade() else {
3610                        return;
3611                    };
3612                    this.update(cx, |this, cx| {
3613                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3614                    });
3615                    cx.stop_propagation();
3616                },
3617            )
3618            // .on_secondary_mouse_down(cx.listener(
3619            //     move |this, event: &MouseDownEvent, window, cx| {
3620            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3621            //         cx.stop_propagation();
3622            //     },
3623            // ))
3624            .child(
3625                div()
3626                    .id(checkbox_wrapper_id)
3627                    .flex_none()
3628                    .occlude()
3629                    .cursor_pointer()
3630                    .child(
3631                        Checkbox::new(checkbox_id, is_staged)
3632                            .disabled(!has_write_access)
3633                            .fill()
3634                            .placeholder(
3635                                !self.has_staged_changes()
3636                                    && !self.has_conflicts()
3637                                    && !entry.status.is_created(),
3638                            )
3639                            .elevation(ElevationIndex::Surface)
3640                            .on_click({
3641                                let entry = entry.clone();
3642                                cx.listener(move |this, _, window, cx| {
3643                                    if !has_write_access {
3644                                        return;
3645                                    }
3646                                    this.toggle_staged_for_entry(
3647                                        &GitListEntry::GitStatusEntry(entry.clone()),
3648                                        window,
3649                                        cx,
3650                                    );
3651                                    cx.stop_propagation();
3652                                })
3653                            })
3654                            .tooltip(move |window, cx| {
3655                                let is_staged = entry_staging.is_fully_staged();
3656
3657                                let action = if is_staged { "Unstage" } else { "Stage" };
3658                                let tooltip_name = if shift_held {
3659                                    format!("{} section", action)
3660                                } else {
3661                                    action.to_string()
3662                                };
3663
3664                                let meta = if shift_held {
3665                                    format!(
3666                                        "Release shift to {} single entry",
3667                                        action.to_lowercase()
3668                                    )
3669                                } else {
3670                                    format!("Shift click to {} section", action.to_lowercase())
3671                                };
3672
3673                                Tooltip::with_meta(
3674                                    tooltip_name,
3675                                    Some(&ToggleStaged),
3676                                    meta,
3677                                    window,
3678                                    cx,
3679                                )
3680                            }),
3681                    ),
3682            )
3683            .child(git_status_icon(status))
3684            .child(
3685                h_flex()
3686                    .items_center()
3687                    .flex_1()
3688                    // .overflow_hidden()
3689                    .when_some(entry.parent_dir(), |this, parent| {
3690                        if !parent.is_empty() {
3691                            this.child(
3692                                self.entry_label(format!("{}/", parent), path_color)
3693                                    .when(status.is_deleted(), |this| this.strikethrough()),
3694                            )
3695                        } else {
3696                            this
3697                        }
3698                    })
3699                    .child(
3700                        self.entry_label(display_name.clone(), label_color)
3701                            .when(status.is_deleted(), |this| this.strikethrough()),
3702                    ),
3703            )
3704            .into_any_element()
3705    }
3706
3707    fn has_write_access(&self, cx: &App) -> bool {
3708        !self.project.read(cx).is_read_only(cx)
3709    }
3710}
3711
3712fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3713    assistant_settings::AssistantSettings::get_global(cx)
3714        .enabled
3715        .then(|| {
3716            let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3717            let model = LanguageModelRegistry::read_global(cx).active_model()?;
3718            provider.is_authenticated(cx).then(|| model)
3719        })
3720        .flatten()
3721}
3722
3723impl Render for GitPanel {
3724    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3725        let project = self.project.read(cx);
3726        let has_entries = self.entries.len() > 0;
3727        let room = self
3728            .workspace
3729            .upgrade()
3730            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3731
3732        let has_write_access = self.has_write_access(cx);
3733
3734        let has_co_authors = room.map_or(false, |room| {
3735            room.read(cx)
3736                .remote_participants()
3737                .values()
3738                .any(|remote_participant| remote_participant.can_write())
3739        });
3740
3741        v_flex()
3742            .id("git_panel")
3743            .key_context(self.dispatch_context(window, cx))
3744            .track_focus(&self.focus_handle)
3745            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3746            .when(has_write_access && !project.is_read_only(cx), |this| {
3747                this.on_action(cx.listener(Self::toggle_staged_for_selected))
3748                    .on_action(cx.listener(GitPanel::commit))
3749                    .on_action(cx.listener(Self::stage_all))
3750                    .on_action(cx.listener(Self::unstage_all))
3751                    .on_action(cx.listener(Self::stage_selected))
3752                    .on_action(cx.listener(Self::unstage_selected))
3753                    .on_action(cx.listener(Self::restore_tracked_files))
3754                    .on_action(cx.listener(Self::revert_selected))
3755                    .on_action(cx.listener(Self::clean_all))
3756                    .on_action(cx.listener(Self::generate_commit_message_action))
3757            })
3758            .on_action(cx.listener(Self::select_first))
3759            .on_action(cx.listener(Self::select_next))
3760            .on_action(cx.listener(Self::select_previous))
3761            .on_action(cx.listener(Self::select_last))
3762            .on_action(cx.listener(Self::close_panel))
3763            .on_action(cx.listener(Self::open_diff))
3764            .on_action(cx.listener(Self::open_file))
3765            .on_action(cx.listener(Self::focus_changes_list))
3766            .on_action(cx.listener(Self::focus_editor))
3767            .on_action(cx.listener(Self::expand_commit_editor))
3768            .when(has_write_access && has_co_authors, |git_panel| {
3769                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3770            })
3771            .on_hover(cx.listener(move |this, hovered, window, cx| {
3772                if *hovered {
3773                    this.horizontal_scrollbar.show(cx);
3774                    this.vertical_scrollbar.show(cx);
3775                    cx.notify();
3776                } else if !this.focus_handle.contains_focused(window, cx) {
3777                    this.hide_scrollbars(window, cx);
3778                }
3779            }))
3780            .size_full()
3781            .overflow_hidden()
3782            .bg(ElevationIndex::Surface.bg(cx))
3783            .child(
3784                v_flex()
3785                    .size_full()
3786                    .children(self.render_panel_header(window, cx))
3787                    .map(|this| {
3788                        if has_entries {
3789                            this.child(self.render_entries(has_write_access, window, cx))
3790                        } else {
3791                            this.child(self.render_empty_state(cx).into_any_element())
3792                        }
3793                    })
3794                    .children(self.render_footer(window, cx))
3795                    .children(self.render_previous_commit(cx))
3796                    .into_any_element(),
3797            )
3798            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3799                deferred(
3800                    anchored()
3801                        .position(*position)
3802                        .anchor(gpui::Corner::TopLeft)
3803                        .child(menu.clone()),
3804                )
3805                .with_priority(1)
3806            }))
3807    }
3808}
3809
3810impl Focusable for GitPanel {
3811    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3812        if self.entries.is_empty() {
3813            self.commit_editor.focus_handle(cx)
3814        } else {
3815            self.focus_handle.clone()
3816        }
3817    }
3818}
3819
3820impl EventEmitter<Event> for GitPanel {}
3821
3822impl EventEmitter<PanelEvent> for GitPanel {}
3823
3824pub(crate) struct GitPanelAddon {
3825    pub(crate) workspace: WeakEntity<Workspace>,
3826}
3827
3828impl editor::Addon for GitPanelAddon {
3829    fn to_any(&self) -> &dyn std::any::Any {
3830        self
3831    }
3832
3833    fn render_buffer_header_controls(
3834        &self,
3835        excerpt_info: &ExcerptInfo,
3836        window: &Window,
3837        cx: &App,
3838    ) -> Option<AnyElement> {
3839        let file = excerpt_info.buffer.file()?;
3840        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3841
3842        git_panel
3843            .read(cx)
3844            .render_buffer_header_controls(&git_panel, &file, window, cx)
3845    }
3846}
3847
3848impl Panel for GitPanel {
3849    fn persistent_name() -> &'static str {
3850        "GitPanel"
3851    }
3852
3853    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3854        GitPanelSettings::get_global(cx).dock
3855    }
3856
3857    fn position_is_valid(&self, position: DockPosition) -> bool {
3858        matches!(position, DockPosition::Left | DockPosition::Right)
3859    }
3860
3861    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3862        settings::update_settings_file::<GitPanelSettings>(
3863            self.fs.clone(),
3864            cx,
3865            move |settings, _| settings.dock = Some(position),
3866        );
3867    }
3868
3869    fn size(&self, _: &Window, cx: &App) -> Pixels {
3870        self.width
3871            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3872    }
3873
3874    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3875        self.width = size;
3876        self.serialize(cx);
3877        cx.notify();
3878    }
3879
3880    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3881        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3882    }
3883
3884    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3885        Some("Git Panel")
3886    }
3887
3888    fn toggle_action(&self) -> Box<dyn Action> {
3889        Box::new(ToggleFocus)
3890    }
3891
3892    fn activation_priority(&self) -> u32 {
3893        2
3894    }
3895}
3896
3897impl PanelHeader for GitPanel {}
3898
3899struct GitPanelMessageTooltip {
3900    commit_tooltip: Option<Entity<CommitTooltip>>,
3901}
3902
3903impl GitPanelMessageTooltip {
3904    fn new(
3905        git_panel: Entity<GitPanel>,
3906        sha: SharedString,
3907        window: &mut Window,
3908        cx: &mut App,
3909    ) -> Entity<Self> {
3910        cx.new(|cx| {
3911            cx.spawn_in(window, |this, mut cx| async move {
3912                let details = git_panel
3913                    .update(&mut cx, |git_panel, cx| {
3914                        git_panel.load_commit_details(&sha, cx)
3915                    })?
3916                    .await?;
3917
3918                let commit_details = editor::commit_tooltip::CommitDetails {
3919                    sha: details.sha.clone(),
3920                    committer_name: details.committer_name.clone(),
3921                    committer_email: details.committer_email.clone(),
3922                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3923                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3924                        message: details.message.clone(),
3925                        ..Default::default()
3926                    }),
3927                };
3928
3929                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3930                    this.commit_tooltip =
3931                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3932                    cx.notify();
3933                })
3934            })
3935            .detach();
3936
3937            Self {
3938                commit_tooltip: None,
3939            }
3940        })
3941    }
3942}
3943
3944impl Render for GitPanelMessageTooltip {
3945    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3946        if let Some(commit_tooltip) = &self.commit_tooltip {
3947            commit_tooltip.clone().into_any_element()
3948        } else {
3949            gpui::Empty.into_any_element()
3950        }
3951    }
3952}
3953
3954#[derive(IntoElement, IntoComponent)]
3955#[component(scope = "Version Control")]
3956pub struct PanelRepoFooter {
3957    id: SharedString,
3958    active_repository: SharedString,
3959    branch: Option<Branch>,
3960    // Getting a GitPanel in previews will be difficult.
3961    //
3962    // For now just take an option here, and we won't bind handlers to buttons in previews.
3963    git_panel: Option<Entity<GitPanel>>,
3964}
3965
3966impl PanelRepoFooter {
3967    pub fn new(
3968        id: impl Into<SharedString>,
3969        active_repository: SharedString,
3970        branch: Option<Branch>,
3971        git_panel: Option<Entity<GitPanel>>,
3972    ) -> Self {
3973        Self {
3974            id: id.into(),
3975            active_repository,
3976            branch,
3977            git_panel,
3978        }
3979    }
3980
3981    pub fn new_preview(
3982        id: impl Into<SharedString>,
3983        active_repository: SharedString,
3984        branch: Option<Branch>,
3985    ) -> Self {
3986        Self {
3987            id: id.into(),
3988            active_repository,
3989            branch,
3990            git_panel: None,
3991        }
3992    }
3993}
3994
3995impl RenderOnce for PanelRepoFooter {
3996    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3997        let project = self
3998            .git_panel
3999            .as_ref()
4000            .map(|panel| panel.read(cx).project.clone());
4001
4002        let repo = self
4003            .git_panel
4004            .as_ref()
4005            .and_then(|panel| panel.read(cx).active_repository.clone());
4006
4007        let single_repo = project
4008            .as_ref()
4009            .map(|project| {
4010                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
4011            })
4012            .unwrap_or(true);
4013
4014        const MAX_BRANCH_LEN: usize = 16;
4015        const MAX_REPO_LEN: usize = 16;
4016        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4017
4018        let branch = self.branch.clone();
4019        let branch_name = branch
4020            .as_ref()
4021            .map_or(" (no branch)".into(), |branch| branch.name.clone());
4022        let active_repo_name = self.active_repository.clone();
4023
4024        let branch_actual_len = branch_name.len();
4025        let repo_actual_len = active_repo_name.len();
4026
4027        // ideally, show the whole branch and repo names but
4028        // when we can't, use a budget to allocate space between the two
4029        let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4030            <= LABEL_CHARACTER_BUDGET
4031        {
4032            (repo_actual_len, branch_actual_len)
4033        } else {
4034            if branch_actual_len <= MAX_BRANCH_LEN {
4035                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4036                (repo_space, branch_actual_len)
4037            } else if repo_actual_len <= MAX_REPO_LEN {
4038                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4039                (repo_actual_len, branch_space)
4040            } else {
4041                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4042            }
4043        };
4044
4045        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4046            active_repo_name.to_string()
4047        } else {
4048            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4049        };
4050
4051        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4052            branch_name.to_string()
4053        } else {
4054            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4055        };
4056
4057        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4058            .style(ButtonStyle::Transparent)
4059            .size(ButtonSize::None)
4060            .label_size(LabelSize::Small)
4061            .color(Color::Muted);
4062
4063        let repo_selector = PopoverMenu::new("repository-switcher")
4064            .menu({
4065                let project = project.clone();
4066                move |window, cx| {
4067                    let project = project.clone()?;
4068                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
4069                }
4070            })
4071            .trigger_with_tooltip(
4072                repo_selector_trigger.disabled(single_repo).truncate(true),
4073                Tooltip::text("Switch active repository"),
4074            )
4075            .attach(gpui::Corner::BottomLeft)
4076            .into_any_element();
4077
4078        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4079            .style(ButtonStyle::Transparent)
4080            .size(ButtonSize::None)
4081            .label_size(LabelSize::Small)
4082            .truncate(true)
4083            .tooltip(Tooltip::for_action_title(
4084                "Switch Branch",
4085                &zed_actions::git::Branch,
4086            ))
4087            .on_click(|_, window, cx| {
4088                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
4089            });
4090
4091        let branch_selector = PopoverMenu::new("popover-button")
4092            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4093            .trigger_with_tooltip(
4094                branch_selector_button,
4095                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
4096            )
4097            .anchor(Corner::TopLeft)
4098            .offset(gpui::Point {
4099                x: px(0.0),
4100                y: px(-2.0),
4101            });
4102
4103        let spinner = self
4104            .git_panel
4105            .as_ref()
4106            .and_then(|git_panel| git_panel.read(cx).render_spinner());
4107
4108        h_flex()
4109            .w_full()
4110            .px_2()
4111            .h(px(36.))
4112            .items_center()
4113            .justify_between()
4114            .gap_1()
4115            .child(
4116                h_flex()
4117                    .flex_1()
4118                    .overflow_hidden()
4119                    .items_center()
4120                    .child(
4121                        div().child(
4122                            Icon::new(IconName::GitBranchSmall)
4123                                .size(IconSize::Small)
4124                                .color(if single_repo {
4125                                    Color::Disabled
4126                                } else {
4127                                    Color::Muted
4128                                }),
4129                        ),
4130                    )
4131                    .child(repo_selector)
4132                    .when_some(branch.clone(), |this, _| {
4133                        this.child(
4134                            div()
4135                                .text_color(cx.theme().colors().text_muted)
4136                                .text_sm()
4137                                .child("/"),
4138                        )
4139                    })
4140                    .child(branch_selector),
4141            )
4142            .child(
4143                h_flex()
4144                    .gap_1()
4145                    .flex_shrink_0()
4146                    .children(spinner)
4147                    .when_some(branch, |this, branch| {
4148                        let mut focus_handle = None;
4149                        if let Some(git_panel) = self.git_panel.as_ref() {
4150                            if !git_panel.read(cx).can_push_and_pull(cx) {
4151                                return this;
4152                            }
4153                            focus_handle = Some(git_panel.focus_handle(cx));
4154                        }
4155
4156                        this.children(render_remote_button(
4157                            self.id.clone(),
4158                            &branch,
4159                            focus_handle,
4160                            true,
4161                        ))
4162                    }),
4163            )
4164    }
4165}
4166
4167impl ComponentPreview for PanelRepoFooter {
4168    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
4169        let unknown_upstream = None;
4170        let no_remote_upstream = Some(UpstreamTracking::Gone);
4171        let ahead_of_upstream = Some(
4172            UpstreamTrackingStatus {
4173                ahead: 2,
4174                behind: 0,
4175            }
4176            .into(),
4177        );
4178        let behind_upstream = Some(
4179            UpstreamTrackingStatus {
4180                ahead: 0,
4181                behind: 2,
4182            }
4183            .into(),
4184        );
4185        let ahead_and_behind_upstream = Some(
4186            UpstreamTrackingStatus {
4187                ahead: 3,
4188                behind: 1,
4189            }
4190            .into(),
4191        );
4192
4193        let not_ahead_or_behind_upstream = Some(
4194            UpstreamTrackingStatus {
4195                ahead: 0,
4196                behind: 0,
4197            }
4198            .into(),
4199        );
4200
4201        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4202            Branch {
4203                is_head: true,
4204                name: "some-branch".into(),
4205                upstream: upstream.map(|tracking| Upstream {
4206                    ref_name: "origin/some-branch".into(),
4207                    tracking,
4208                }),
4209                most_recent_commit: Some(CommitSummary {
4210                    sha: "abc123".into(),
4211                    subject: "Modify stuff".into(),
4212                    commit_timestamp: 1710932954,
4213                    has_parent: true,
4214                }),
4215            }
4216        }
4217
4218        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4219            Branch {
4220                is_head: true,
4221                name: branch_name.to_string().into(),
4222                upstream: upstream.map(|tracking| Upstream {
4223                    ref_name: format!("zed/{}", branch_name).into(),
4224                    tracking,
4225                }),
4226                most_recent_commit: Some(CommitSummary {
4227                    sha: "abc123".into(),
4228                    subject: "Modify stuff".into(),
4229                    commit_timestamp: 1710932954,
4230                    has_parent: true,
4231                }),
4232            }
4233        }
4234
4235        fn active_repository(id: usize) -> SharedString {
4236            format!("repo-{}", id).into()
4237        }
4238
4239        let example_width = px(340.);
4240
4241        v_flex()
4242            .gap_6()
4243            .w_full()
4244            .flex_none()
4245            .children(vec![example_group_with_title(
4246                "Action Button States",
4247                vec![
4248                    single_example(
4249                        "No Branch",
4250                        div()
4251                            .w(example_width)
4252                            .overflow_hidden()
4253                            .child(PanelRepoFooter::new_preview(
4254                                "no-branch",
4255                                active_repository(1).clone(),
4256                                None,
4257                            ))
4258                            .into_any_element(),
4259                    )
4260                    .grow(),
4261                    single_example(
4262                        "Remote status unknown",
4263                        div()
4264                            .w(example_width)
4265                            .overflow_hidden()
4266                            .child(PanelRepoFooter::new_preview(
4267                                "unknown-upstream",
4268                                active_repository(2).clone(),
4269                                Some(branch(unknown_upstream)),
4270                            ))
4271                            .into_any_element(),
4272                    )
4273                    .grow(),
4274                    single_example(
4275                        "No Remote Upstream",
4276                        div()
4277                            .w(example_width)
4278                            .overflow_hidden()
4279                            .child(PanelRepoFooter::new_preview(
4280                                "no-remote-upstream",
4281                                active_repository(3).clone(),
4282                                Some(branch(no_remote_upstream)),
4283                            ))
4284                            .into_any_element(),
4285                    )
4286                    .grow(),
4287                    single_example(
4288                        "Not Ahead or Behind",
4289                        div()
4290                            .w(example_width)
4291                            .overflow_hidden()
4292                            .child(PanelRepoFooter::new_preview(
4293                                "not-ahead-or-behind",
4294                                active_repository(4).clone(),
4295                                Some(branch(not_ahead_or_behind_upstream)),
4296                            ))
4297                            .into_any_element(),
4298                    )
4299                    .grow(),
4300                    single_example(
4301                        "Behind remote",
4302                        div()
4303                            .w(example_width)
4304                            .overflow_hidden()
4305                            .child(PanelRepoFooter::new_preview(
4306                                "behind-remote",
4307                                active_repository(5).clone(),
4308                                Some(branch(behind_upstream)),
4309                            ))
4310                            .into_any_element(),
4311                    )
4312                    .grow(),
4313                    single_example(
4314                        "Ahead of remote",
4315                        div()
4316                            .w(example_width)
4317                            .overflow_hidden()
4318                            .child(PanelRepoFooter::new_preview(
4319                                "ahead-of-remote",
4320                                active_repository(6).clone(),
4321                                Some(branch(ahead_of_upstream)),
4322                            ))
4323                            .into_any_element(),
4324                    )
4325                    .grow(),
4326                    single_example(
4327                        "Ahead and behind remote",
4328                        div()
4329                            .w(example_width)
4330                            .overflow_hidden()
4331                            .child(PanelRepoFooter::new_preview(
4332                                "ahead-and-behind",
4333                                active_repository(7).clone(),
4334                                Some(branch(ahead_and_behind_upstream)),
4335                            ))
4336                            .into_any_element(),
4337                    )
4338                    .grow(),
4339                ],
4340            )
4341            .grow()
4342            .vertical()])
4343            .children(vec![example_group_with_title(
4344                "Labels",
4345                vec![
4346                    single_example(
4347                        "Short Branch & Repo",
4348                        div()
4349                            .w(example_width)
4350                            .overflow_hidden()
4351                            .child(PanelRepoFooter::new_preview(
4352                                "short-branch",
4353                                SharedString::from("zed"),
4354                                Some(custom("main", behind_upstream)),
4355                            ))
4356                            .into_any_element(),
4357                    )
4358                    .grow(),
4359                    single_example(
4360                        "Long Branch",
4361                        div()
4362                            .w(example_width)
4363                            .overflow_hidden()
4364                            .child(PanelRepoFooter::new_preview(
4365                                "long-branch",
4366                                SharedString::from("zed"),
4367                                Some(custom(
4368                                    "redesign-and-update-git-ui-list-entry-style",
4369                                    behind_upstream,
4370                                )),
4371                            ))
4372                            .into_any_element(),
4373                    )
4374                    .grow(),
4375                    single_example(
4376                        "Long Repo",
4377                        div()
4378                            .w(example_width)
4379                            .overflow_hidden()
4380                            .child(PanelRepoFooter::new_preview(
4381                                "long-repo",
4382                                SharedString::from("zed-industries-community-examples"),
4383                                Some(custom("gpui", ahead_of_upstream)),
4384                            ))
4385                            .into_any_element(),
4386                    )
4387                    .grow(),
4388                    single_example(
4389                        "Long Repo & Branch",
4390                        div()
4391                            .w(example_width)
4392                            .overflow_hidden()
4393                            .child(PanelRepoFooter::new_preview(
4394                                "long-repo-and-branch",
4395                                SharedString::from("zed-industries-community-examples"),
4396                                Some(custom(
4397                                    "redesign-and-update-git-ui-list-entry-style",
4398                                    behind_upstream,
4399                                )),
4400                            ))
4401                            .into_any_element(),
4402                    )
4403                    .grow(),
4404                    single_example(
4405                        "Uppercase Repo",
4406                        div()
4407                            .w(example_width)
4408                            .overflow_hidden()
4409                            .child(PanelRepoFooter::new_preview(
4410                                "uppercase-repo",
4411                                SharedString::from("LICENSES"),
4412                                Some(custom("main", ahead_of_upstream)),
4413                            ))
4414                            .into_any_element(),
4415                    )
4416                    .grow(),
4417                    single_example(
4418                        "Uppercase Branch",
4419                        div()
4420                            .w(example_width)
4421                            .overflow_hidden()
4422                            .child(PanelRepoFooter::new_preview(
4423                                "uppercase-branch",
4424                                SharedString::from("zed"),
4425                                Some(custom("update-README", behind_upstream)),
4426                            ))
4427                            .into_any_element(),
4428                    )
4429                    .grow(),
4430                ],
4431            )
4432            .grow()
4433            .vertical()])
4434            .into_any_element()
4435    }
4436}
4437
4438#[cfg(test)]
4439mod tests {
4440    use git::status::StatusCode;
4441    use gpui::TestAppContext;
4442    use project::{FakeFs, WorktreeSettings};
4443    use serde_json::json;
4444    use settings::SettingsStore;
4445    use theme::LoadThemes;
4446    use util::path;
4447
4448    use super::*;
4449
4450    fn init_test(cx: &mut gpui::TestAppContext) {
4451        if std::env::var("RUST_LOG").is_ok() {
4452            env_logger::try_init().ok();
4453        }
4454
4455        cx.update(|cx| {
4456            let settings_store = SettingsStore::test(cx);
4457            cx.set_global(settings_store);
4458            AssistantSettings::register(cx);
4459            WorktreeSettings::register(cx);
4460            workspace::init_settings(cx);
4461            theme::init(LoadThemes::JustBase, cx);
4462            language::init(cx);
4463            editor::init(cx);
4464            Project::init_settings(cx);
4465            crate::init(cx);
4466        });
4467    }
4468
4469    #[gpui::test]
4470    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4471        init_test(cx);
4472        let fs = FakeFs::new(cx.background_executor.clone());
4473        fs.insert_tree(
4474            "/root",
4475            json!({
4476                "zed": {
4477                    ".git": {},
4478                    "crates": {
4479                        "gpui": {
4480                            "gpui.rs": "fn main() {}"
4481                        },
4482                        "util": {
4483                            "util.rs": "fn do_it() {}"
4484                        }
4485                    }
4486                },
4487            }),
4488        )
4489        .await;
4490
4491        fs.set_status_for_repo_via_git_operation(
4492            Path::new(path!("/root/zed/.git")),
4493            &[
4494                (
4495                    Path::new("crates/gpui/gpui.rs"),
4496                    StatusCode::Modified.worktree(),
4497                ),
4498                (
4499                    Path::new("crates/util/util.rs"),
4500                    StatusCode::Modified.worktree(),
4501                ),
4502            ],
4503        );
4504
4505        let project =
4506            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4507        let (workspace, cx) =
4508            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4509
4510        cx.read(|cx| {
4511            project
4512                .read(cx)
4513                .worktrees(cx)
4514                .nth(0)
4515                .unwrap()
4516                .read(cx)
4517                .as_local()
4518                .unwrap()
4519                .scan_complete()
4520        })
4521        .await;
4522
4523        cx.executor().run_until_parked();
4524
4525        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4526        let panel = cx.new_window_entity(|window, cx| {
4527            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4528        });
4529
4530        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4531            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4532        });
4533        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4534        handle.await;
4535
4536        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4537        pretty_assertions::assert_eq!(
4538            entries,
4539            [
4540                GitListEntry::Header(GitHeaderEntry {
4541                    header: Section::Tracked
4542                }),
4543                GitListEntry::GitStatusEntry(GitStatusEntry {
4544                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4545                    repo_path: "crates/gpui/gpui.rs".into(),
4546                    worktree_path: Path::new("gpui.rs").into(),
4547                    status: StatusCode::Modified.worktree(),
4548                    staging: StageStatus::Unstaged,
4549                }),
4550                GitListEntry::GitStatusEntry(GitStatusEntry {
4551                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4552                    repo_path: "crates/util/util.rs".into(),
4553                    worktree_path: Path::new("../util/util.rs").into(),
4554                    status: StatusCode::Modified.worktree(),
4555                    staging: StageStatus::Unstaged,
4556                },),
4557            ],
4558        );
4559
4560        cx.update_window_entity(&panel, |panel, window, cx| {
4561            panel.select_last(&Default::default(), window, cx);
4562            assert_eq!(panel.selected_entry, Some(2));
4563            panel.open_diff(&Default::default(), window, cx);
4564        });
4565        cx.run_until_parked();
4566
4567        let worktree_roots = workspace.update(cx, |workspace, cx| {
4568            workspace
4569                .worktrees(cx)
4570                .map(|worktree| worktree.read(cx).abs_path())
4571                .collect::<Vec<_>>()
4572        });
4573        pretty_assertions::assert_eq!(
4574            worktree_roots,
4575            vec![
4576                Path::new(path!("/root/zed/crates/gpui")).into(),
4577                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4578            ]
4579        );
4580
4581        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4582            let git_store = project.git_store().read(cx);
4583            // The repo that comes from the single-file worktree can't be selected through the UI.
4584            let filtered_entries = filtered_repository_entries(git_store, cx)
4585                .iter()
4586                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4587                .collect::<Vec<_>>();
4588            assert_eq!(
4589                filtered_entries,
4590                [Path::new(path!("/root/zed/crates/gpui")).into()]
4591            );
4592            // But we can select it artificially here.
4593            git_store
4594                .all_repositories()
4595                .into_iter()
4596                .find(|repo| {
4597                    &*repo.read(cx).worktree_abs_path
4598                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4599                })
4600                .unwrap()
4601        });
4602
4603        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4604        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4605        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4606            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4607        });
4608        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4609        handle.await;
4610        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4611        pretty_assertions::assert_eq!(
4612            entries,
4613            [
4614                GitListEntry::Header(GitHeaderEntry {
4615                    header: Section::Tracked
4616                }),
4617                GitListEntry::GitStatusEntry(GitStatusEntry {
4618                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4619                    repo_path: "crates/gpui/gpui.rs".into(),
4620                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4621                    status: StatusCode::Modified.worktree(),
4622                    staging: StageStatus::Unstaged,
4623                }),
4624                GitListEntry::GitStatusEntry(GitStatusEntry {
4625                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4626                    repo_path: "crates/util/util.rs".into(),
4627                    worktree_path: Path::new("util.rs").into(),
4628                    status: StatusCode::Modified.worktree(),
4629                    staging: StageStatus::Unstaged,
4630                },),
4631            ],
4632        );
4633    }
4634}