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