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                                                this.commit_changes(window, cx)
2948                                            })
2949                                        }),
2950                                ),
2951                            ),
2952                    )
2953                    .child(
2954                        div()
2955                            .pr_2p5()
2956                            .on_action(|&editor::actions::MoveUp, _, cx| {
2957                                cx.stop_propagation();
2958                            })
2959                            .on_action(|&editor::actions::MoveDown, _, cx| {
2960                                cx.stop_propagation();
2961                            })
2962                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2963                    )
2964                    .child(
2965                        h_flex()
2966                            .absolute()
2967                            .top_2()
2968                            .right_2()
2969                            .opacity(0.5)
2970                            .hover(|this| this.opacity(1.0))
2971                            .child(
2972                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2973                                    .icon_size(IconSize::Small)
2974                                    .size(ui::ButtonSize::Default)
2975                                    .tooltip(move |window, cx| {
2976                                        Tooltip::for_action_in(
2977                                            "Open Commit Modal",
2978                                            &git::ExpandCommitEditor,
2979                                            &expand_tooltip_focus_handle,
2980                                            window,
2981                                            cx,
2982                                        )
2983                                    })
2984                                    .on_click(cx.listener({
2985                                        move |_, _, window, cx| {
2986                                            window.dispatch_action(
2987                                                git::ExpandCommitEditor.boxed_clone(),
2988                                                cx,
2989                                            )
2990                                        }
2991                                    })),
2992                            ),
2993                    ),
2994            );
2995
2996        Some(footer)
2997    }
2998
2999    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3000        let active_repository = self.active_repository.as_ref()?;
3001        let branch = active_repository.read(cx).current_branch()?;
3002        let commit = branch.most_recent_commit.as_ref()?.clone();
3003
3004        let this = cx.entity();
3005        Some(
3006            h_flex()
3007                .items_center()
3008                .py_2()
3009                .px(px(8.))
3010                .border_color(cx.theme().colors().border)
3011                .gap_1p5()
3012                .child(
3013                    div()
3014                        .flex_grow()
3015                        .overflow_hidden()
3016                        .items_center()
3017                        .max_w(relative(0.85))
3018                        .h_full()
3019                        .child(
3020                            Label::new(commit.subject.clone())
3021                                .size(LabelSize::Small)
3022                                .truncate(),
3023                        )
3024                        .id("commit-msg-hover")
3025                        .hoverable_tooltip(move |window, cx| {
3026                            GitPanelMessageTooltip::new(
3027                                this.clone(),
3028                                commit.sha.clone(),
3029                                window,
3030                                cx,
3031                            )
3032                            .into()
3033                        }),
3034                )
3035                .child(div().flex_1())
3036                .when(commit.has_parent, |this| {
3037                    let has_unstaged = self.has_unstaged_changes();
3038                    this.child(
3039                        panel_icon_button("undo", IconName::Undo)
3040                            .icon_size(IconSize::Small)
3041                            .icon_color(Color::Muted)
3042                            .tooltip(move |window, cx| {
3043                                Tooltip::with_meta(
3044                                    "Uncommit",
3045                                    Some(&git::Uncommit),
3046                                    if has_unstaged {
3047                                        "git reset HEAD^ --soft"
3048                                    } else {
3049                                        "git reset HEAD^"
3050                                    },
3051                                    window,
3052                                    cx,
3053                                )
3054                            })
3055                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3056                    )
3057                }),
3058        )
3059    }
3060
3061    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3062        h_flex()
3063            .h_full()
3064            .flex_grow()
3065            .justify_center()
3066            .items_center()
3067            .child(
3068                v_flex()
3069                    .gap_2()
3070                    .child(h_flex().w_full().justify_around().child(
3071                        if self.active_repository.is_some() {
3072                            "No changes to commit"
3073                        } else {
3074                            "No Git repositories"
3075                        },
3076                    ))
3077                    .children({
3078                        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3079                        (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3080                            h_flex().w_full().justify_around().child(
3081                                panel_filled_button("Initialize Repository")
3082                                    .tooltip(Tooltip::for_action_title_in(
3083                                        "git init",
3084                                        &git::Init,
3085                                        &self.focus_handle,
3086                                    ))
3087                                    .on_click(move |_, _, cx| {
3088                                        cx.defer(move |cx| {
3089                                            cx.dispatch_action(&git::Init);
3090                                        })
3091                                    }),
3092                            )
3093                        })
3094                    })
3095                    .text_ui_sm(cx)
3096                    .mx_auto()
3097                    .text_color(Color::Placeholder.color(cx)),
3098            )
3099    }
3100
3101    fn render_vertical_scrollbar(
3102        &self,
3103        show_horizontal_scrollbar_container: bool,
3104        cx: &mut Context<Self>,
3105    ) -> impl IntoElement {
3106        div()
3107            .id("git-panel-vertical-scroll")
3108            .occlude()
3109            .flex_none()
3110            .h_full()
3111            .cursor_default()
3112            .absolute()
3113            .right_0()
3114            .top_0()
3115            .bottom_0()
3116            .w(px(12.))
3117            .when(show_horizontal_scrollbar_container, |this| {
3118                this.pb_neg_3p5()
3119            })
3120            .on_mouse_move(cx.listener(|_, _, _, cx| {
3121                cx.notify();
3122                cx.stop_propagation()
3123            }))
3124            .on_hover(|_, _, cx| {
3125                cx.stop_propagation();
3126            })
3127            .on_any_mouse_down(|_, _, cx| {
3128                cx.stop_propagation();
3129            })
3130            .on_mouse_up(
3131                MouseButton::Left,
3132                cx.listener(|this, _, window, cx| {
3133                    if !this.vertical_scrollbar.state.is_dragging()
3134                        && !this.focus_handle.contains_focused(window, cx)
3135                    {
3136                        this.vertical_scrollbar.hide(window, cx);
3137                        cx.notify();
3138                    }
3139
3140                    cx.stop_propagation();
3141                }),
3142            )
3143            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3144                cx.notify();
3145            }))
3146            .children(Scrollbar::vertical(
3147                // percentage as f32..end_offset as f32,
3148                self.vertical_scrollbar.state.clone(),
3149            ))
3150    }
3151
3152    /// Renders the horizontal scrollbar.
3153    ///
3154    /// The right offset is used to determine how far to the right the
3155    /// scrollbar should extend to, useful for ensuring it doesn't collide
3156    /// with the vertical scrollbar when visible.
3157    fn render_horizontal_scrollbar(
3158        &self,
3159        right_offset: Pixels,
3160        cx: &mut Context<Self>,
3161    ) -> impl IntoElement {
3162        div()
3163            .id("git-panel-horizontal-scroll")
3164            .occlude()
3165            .flex_none()
3166            .w_full()
3167            .cursor_default()
3168            .absolute()
3169            .bottom_neg_px()
3170            .left_0()
3171            .right_0()
3172            .pr(right_offset)
3173            .on_mouse_move(cx.listener(|_, _, _, cx| {
3174                cx.notify();
3175                cx.stop_propagation()
3176            }))
3177            .on_hover(|_, _, cx| {
3178                cx.stop_propagation();
3179            })
3180            .on_any_mouse_down(|_, _, cx| {
3181                cx.stop_propagation();
3182            })
3183            .on_mouse_up(
3184                MouseButton::Left,
3185                cx.listener(|this, _, window, cx| {
3186                    if !this.horizontal_scrollbar.state.is_dragging()
3187                        && !this.focus_handle.contains_focused(window, cx)
3188                    {
3189                        this.horizontal_scrollbar.hide(window, cx);
3190                        cx.notify();
3191                    }
3192
3193                    cx.stop_propagation();
3194                }),
3195            )
3196            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3197                cx.notify();
3198            }))
3199            .children(Scrollbar::horizontal(
3200                // percentage as f32..end_offset as f32,
3201                self.horizontal_scrollbar.state.clone(),
3202            ))
3203    }
3204
3205    fn render_buffer_header_controls(
3206        &self,
3207        entity: &Entity<Self>,
3208        file: &Arc<dyn File>,
3209        _: &Window,
3210        cx: &App,
3211    ) -> Option<AnyElement> {
3212        let repo = self.active_repository.as_ref()?.read(cx);
3213        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
3214        let ix = self.entry_by_path(&repo_path)?;
3215        let entry = self.entries.get(ix)?;
3216
3217        let entry_staging = self.entry_staging(entry.status_entry()?);
3218
3219        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3220            .disabled(!self.has_write_access(cx))
3221            .fill()
3222            .elevation(ElevationIndex::Surface)
3223            .on_click({
3224                let entry = entry.clone();
3225                let git_panel = entity.downgrade();
3226                move |_, window, cx| {
3227                    git_panel
3228                        .update(cx, |this, cx| {
3229                            this.toggle_staged_for_entry(&entry, window, cx);
3230                            cx.stop_propagation();
3231                        })
3232                        .ok();
3233                }
3234            });
3235        Some(
3236            h_flex()
3237                .id("start-slot")
3238                .text_lg()
3239                .child(checkbox)
3240                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3241                    // prevent the list item active state triggering when toggling checkbox
3242                    cx.stop_propagation();
3243                })
3244                .into_any_element(),
3245        )
3246    }
3247
3248    fn render_entries(
3249        &self,
3250        has_write_access: bool,
3251        _: &Window,
3252        cx: &mut Context<Self>,
3253    ) -> impl IntoElement {
3254        let entry_count = self.entries.len();
3255
3256        let scroll_track_size = px(16.);
3257
3258        let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3259            // magic number
3260            px(3.)
3261        } else {
3262            px(0.)
3263        };
3264
3265        v_flex()
3266            .flex_1()
3267            .size_full()
3268            .overflow_hidden()
3269            .relative()
3270            // Show a border on the top and bottom of the container when
3271            // the vertical scrollbar container is visible so we don't have a
3272            // floating left border in the panel.
3273            .when(self.vertical_scrollbar.show_track, |this| {
3274                this.border_t_1()
3275                    .border_b_1()
3276                    .border_color(cx.theme().colors().border)
3277            })
3278            .child(
3279                h_flex()
3280                    .flex_1()
3281                    .size_full()
3282                    .relative()
3283                    .overflow_hidden()
3284                    .child(
3285                        uniform_list(cx.entity().clone(), "entries", entry_count, {
3286                            move |this, range, window, cx| {
3287                                let mut items = Vec::with_capacity(range.end - range.start);
3288
3289                                for ix in range {
3290                                    match &this.entries.get(ix) {
3291                                        Some(GitListEntry::GitStatusEntry(entry)) => {
3292                                            items.push(this.render_entry(
3293                                                ix,
3294                                                entry,
3295                                                has_write_access,
3296                                                window,
3297                                                cx,
3298                                            ));
3299                                        }
3300                                        Some(GitListEntry::Header(header)) => {
3301                                            items.push(this.render_list_header(
3302                                                ix,
3303                                                header,
3304                                                has_write_access,
3305                                                window,
3306                                                cx,
3307                                            ));
3308                                        }
3309                                        None => {}
3310                                    }
3311                                }
3312
3313                                items
3314                            }
3315                        })
3316                        .size_full()
3317                        .flex_grow()
3318                        .with_sizing_behavior(ListSizingBehavior::Auto)
3319                        .with_horizontal_sizing_behavior(
3320                            ListHorizontalSizingBehavior::Unconstrained,
3321                        )
3322                        .with_width_from_item(self.max_width_item_index)
3323                        .track_scroll(self.scroll_handle.clone()),
3324                    )
3325                    .on_mouse_down(
3326                        MouseButton::Right,
3327                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3328                            this.deploy_panel_context_menu(event.position, window, cx)
3329                        }),
3330                    )
3331                    .when(self.vertical_scrollbar.show_track, |this| {
3332                        this.child(
3333                            v_flex()
3334                                .h_full()
3335                                .flex_none()
3336                                .w(scroll_track_size)
3337                                .bg(cx.theme().colors().panel_background)
3338                                .child(
3339                                    div()
3340                                        .size_full()
3341                                        .flex_1()
3342                                        .border_l_1()
3343                                        .border_color(cx.theme().colors().border),
3344                                ),
3345                        )
3346                    })
3347                    .when(self.vertical_scrollbar.show_scrollbar, |this| {
3348                        this.child(
3349                            self.render_vertical_scrollbar(
3350                                self.horizontal_scrollbar.show_track,
3351                                cx,
3352                            ),
3353                        )
3354                    }),
3355            )
3356            .when(self.horizontal_scrollbar.show_track, |this| {
3357                this.child(
3358                    h_flex()
3359                        .w_full()
3360                        .h(scroll_track_size)
3361                        .flex_none()
3362                        .relative()
3363                        .child(
3364                            div()
3365                                .w_full()
3366                                .flex_1()
3367                                // for some reason the horizontal scrollbar is 1px
3368                                // taller than the vertical scrollbar??
3369                                .h(scroll_track_size - px(1.))
3370                                .bg(cx.theme().colors().panel_background)
3371                                .border_t_1()
3372                                .border_color(cx.theme().colors().border),
3373                        )
3374                        .when(self.vertical_scrollbar.show_track, |this| {
3375                            this.child(
3376                                div()
3377                                    .flex_none()
3378                                    // -1px prevents a missing pixel between the two container borders
3379                                    .w(scroll_track_size - px(1.))
3380                                    .h_full(),
3381                            )
3382                            .child(
3383                                // HACK: Fill the missing 1px 🥲
3384                                div()
3385                                    .absolute()
3386                                    .right(scroll_track_size - px(1.))
3387                                    .bottom(scroll_track_size - px(1.))
3388                                    .size_px()
3389                                    .bg(cx.theme().colors().border),
3390                            )
3391                        }),
3392                )
3393            })
3394            .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3395                this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3396            })
3397    }
3398
3399    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3400        Label::new(label.into()).color(color).single_line()
3401    }
3402
3403    fn list_item_height(&self) -> Rems {
3404        rems(1.75)
3405    }
3406
3407    fn render_list_header(
3408        &self,
3409        ix: usize,
3410        header: &GitHeaderEntry,
3411        _: bool,
3412        _: &Window,
3413        _: &Context<Self>,
3414    ) -> AnyElement {
3415        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3416
3417        h_flex()
3418            .id(id)
3419            .h(self.list_item_height())
3420            .w_full()
3421            .items_end()
3422            .px(rems(0.75)) // ~12px
3423            .pb(rems(0.3125)) // ~ 5px
3424            .child(
3425                Label::new(header.title())
3426                    .color(Color::Muted)
3427                    .size(LabelSize::Small)
3428                    .line_height_style(LineHeightStyle::UiLabel)
3429                    .single_line(),
3430            )
3431            .into_any_element()
3432    }
3433
3434    fn load_commit_details(
3435        &self,
3436        sha: String,
3437        cx: &mut Context<Self>,
3438    ) -> Task<anyhow::Result<CommitDetails>> {
3439        let Some(repo) = self.active_repository.clone() else {
3440            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3441        };
3442        repo.update(cx, |repo, cx| {
3443            let show = repo.show(sha);
3444            cx.spawn(|_, _| async move { show.await? })
3445        })
3446    }
3447
3448    fn deploy_entry_context_menu(
3449        &mut self,
3450        position: Point<Pixels>,
3451        ix: usize,
3452        window: &mut Window,
3453        cx: &mut Context<Self>,
3454    ) {
3455        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3456            return;
3457        };
3458        let stage_title = if entry.status.staging().is_fully_staged() {
3459            "Unstage File"
3460        } else {
3461            "Stage File"
3462        };
3463        let restore_title = if entry.status.is_created() {
3464            "Trash File"
3465        } else {
3466            "Restore File"
3467        };
3468        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3469            context_menu
3470                .context(self.focus_handle.clone())
3471                .action(stage_title, ToggleStaged.boxed_clone())
3472                .action(restore_title, git::RestoreFile.boxed_clone())
3473                .separator()
3474                .action("Open Diff", Confirm.boxed_clone())
3475                .action("Open File", SecondaryConfirm.boxed_clone())
3476        });
3477        self.selected_entry = Some(ix);
3478        self.set_context_menu(context_menu, position, window, cx);
3479    }
3480
3481    fn deploy_panel_context_menu(
3482        &mut self,
3483        position: Point<Pixels>,
3484        window: &mut Window,
3485        cx: &mut Context<Self>,
3486    ) {
3487        let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3488        self.set_context_menu(context_menu, position, window, cx);
3489    }
3490
3491    fn set_context_menu(
3492        &mut self,
3493        context_menu: Entity<ContextMenu>,
3494        position: Point<Pixels>,
3495        window: &Window,
3496        cx: &mut Context<Self>,
3497    ) {
3498        let subscription = cx.subscribe_in(
3499            &context_menu,
3500            window,
3501            |this, _, _: &DismissEvent, window, cx| {
3502                if this.context_menu.as_ref().is_some_and(|context_menu| {
3503                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3504                }) {
3505                    cx.focus_self(window);
3506                }
3507                this.context_menu.take();
3508                cx.notify();
3509            },
3510        );
3511        self.context_menu = Some((context_menu, position, subscription));
3512        cx.notify();
3513    }
3514
3515    fn render_entry(
3516        &self,
3517        ix: usize,
3518        entry: &GitStatusEntry,
3519        has_write_access: bool,
3520        window: &Window,
3521        cx: &Context<Self>,
3522    ) -> AnyElement {
3523        let display_name = entry.display_name();
3524
3525        let selected = self.selected_entry == Some(ix);
3526        let marked = self.marked_entries.contains(&ix);
3527        let status_style = GitPanelSettings::get_global(cx).status_style;
3528        let status = entry.status;
3529        let modifiers = self.current_modifiers;
3530        let shift_held = modifiers.shift;
3531
3532        let has_conflict = status.is_conflicted();
3533        let is_modified = status.is_modified();
3534        let is_deleted = status.is_deleted();
3535
3536        let label_color = if status_style == StatusStyle::LabelColor {
3537            if has_conflict {
3538                Color::Conflict
3539            } else if is_modified {
3540                Color::Modified
3541            } else if is_deleted {
3542                // We don't want a bunch of red labels in the list
3543                Color::Disabled
3544            } else {
3545                Color::Created
3546            }
3547        } else {
3548            Color::Default
3549        };
3550
3551        let path_color = if status.is_deleted() {
3552            Color::Disabled
3553        } else {
3554            Color::Muted
3555        };
3556
3557        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3558        let checkbox_wrapper_id: ElementId =
3559            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3560        let checkbox_id: ElementId =
3561            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3562
3563        let entry_staging = self.entry_staging(entry);
3564        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3565
3566        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3567            is_staged = ToggleState::Selected;
3568        }
3569
3570        let handle = cx.weak_entity();
3571
3572        let selected_bg_alpha = 0.08;
3573        let marked_bg_alpha = 0.12;
3574        let state_opacity_step = 0.04;
3575
3576        let base_bg = match (selected, marked) {
3577            (true, true) => cx
3578                .theme()
3579                .status()
3580                .info
3581                .alpha(selected_bg_alpha + marked_bg_alpha),
3582            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3583            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3584            _ => cx.theme().colors().ghost_element_background,
3585        };
3586
3587        let hover_bg = if selected {
3588            cx.theme()
3589                .status()
3590                .info
3591                .alpha(selected_bg_alpha + state_opacity_step)
3592        } else {
3593            cx.theme().colors().ghost_element_hover
3594        };
3595
3596        let active_bg = if selected {
3597            cx.theme()
3598                .status()
3599                .info
3600                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3601        } else {
3602            cx.theme().colors().ghost_element_active
3603        };
3604
3605        h_flex()
3606            .id(id)
3607            .h(self.list_item_height())
3608            .w_full()
3609            .items_center()
3610            .border_1()
3611            .when(selected && self.focus_handle.is_focused(window), |el| {
3612                el.border_color(cx.theme().colors().border_focused)
3613            })
3614            .px(rems(0.75)) // ~12px
3615            .overflow_hidden()
3616            .flex_none()
3617            .gap_1p5()
3618            .bg(base_bg)
3619            .hover(|this| this.bg(hover_bg))
3620            .active(|this| this.bg(active_bg))
3621            .on_click({
3622                cx.listener(move |this, event: &ClickEvent, window, cx| {
3623                    this.selected_entry = Some(ix);
3624                    cx.notify();
3625                    if event.modifiers().secondary() {
3626                        this.open_file(&Default::default(), window, cx)
3627                    } else {
3628                        this.open_diff(&Default::default(), window, cx);
3629                        this.focus_handle.focus(window);
3630                    }
3631                })
3632            })
3633            .on_mouse_down(
3634                MouseButton::Right,
3635                move |event: &MouseDownEvent, window, cx| {
3636                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3637                    if event.button != MouseButton::Right {
3638                        return;
3639                    }
3640
3641                    let Some(this) = handle.upgrade() else {
3642                        return;
3643                    };
3644                    this.update(cx, |this, cx| {
3645                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3646                    });
3647                    cx.stop_propagation();
3648                },
3649            )
3650            // .on_secondary_mouse_down(cx.listener(
3651            //     move |this, event: &MouseDownEvent, window, cx| {
3652            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3653            //         cx.stop_propagation();
3654            //     },
3655            // ))
3656            .child(
3657                div()
3658                    .id(checkbox_wrapper_id)
3659                    .flex_none()
3660                    .occlude()
3661                    .cursor_pointer()
3662                    .child(
3663                        Checkbox::new(checkbox_id, is_staged)
3664                            .disabled(!has_write_access)
3665                            .fill()
3666                            .placeholder(
3667                                !self.has_staged_changes()
3668                                    && !self.has_conflicts()
3669                                    && !entry.status.is_created(),
3670                            )
3671                            .elevation(ElevationIndex::Surface)
3672                            .on_click({
3673                                let entry = entry.clone();
3674                                cx.listener(move |this, _, window, cx| {
3675                                    if !has_write_access {
3676                                        return;
3677                                    }
3678                                    this.toggle_staged_for_entry(
3679                                        &GitListEntry::GitStatusEntry(entry.clone()),
3680                                        window,
3681                                        cx,
3682                                    );
3683                                    cx.stop_propagation();
3684                                })
3685                            })
3686                            .tooltip(move |window, cx| {
3687                                let is_staged = entry_staging.is_fully_staged();
3688
3689                                let action = if is_staged { "Unstage" } else { "Stage" };
3690                                let tooltip_name = if shift_held {
3691                                    format!("{} section", action)
3692                                } else {
3693                                    action.to_string()
3694                                };
3695
3696                                let meta = if shift_held {
3697                                    format!(
3698                                        "Release shift to {} single entry",
3699                                        action.to_lowercase()
3700                                    )
3701                                } else {
3702                                    format!("Shift click to {} section", action.to_lowercase())
3703                                };
3704
3705                                Tooltip::with_meta(
3706                                    tooltip_name,
3707                                    Some(&ToggleStaged),
3708                                    meta,
3709                                    window,
3710                                    cx,
3711                                )
3712                            }),
3713                    ),
3714            )
3715            .child(git_status_icon(status))
3716            .child(
3717                h_flex()
3718                    .items_center()
3719                    .flex_1()
3720                    // .overflow_hidden()
3721                    .when_some(entry.parent_dir(), |this, parent| {
3722                        if !parent.is_empty() {
3723                            this.child(
3724                                self.entry_label(format!("{}/", parent), path_color)
3725                                    .when(status.is_deleted(), |this| this.strikethrough()),
3726                            )
3727                        } else {
3728                            this
3729                        }
3730                    })
3731                    .child(
3732                        self.entry_label(display_name.clone(), label_color)
3733                            .when(status.is_deleted(), |this| this.strikethrough()),
3734                    ),
3735            )
3736            .into_any_element()
3737    }
3738
3739    fn has_write_access(&self, cx: &App) -> bool {
3740        !self.project.read(cx).is_read_only(cx)
3741    }
3742}
3743
3744fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3745    assistant_settings::AssistantSettings::get_global(cx)
3746        .enabled
3747        .then(|| {
3748            let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3749            let model = LanguageModelRegistry::read_global(cx).active_model()?;
3750            provider.is_authenticated(cx).then(|| model)
3751        })
3752        .flatten()
3753}
3754
3755impl Render for GitPanel {
3756    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3757        let project = self.project.read(cx);
3758        let has_entries = self.entries.len() > 0;
3759        let room = self
3760            .workspace
3761            .upgrade()
3762            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3763
3764        let has_write_access = self.has_write_access(cx);
3765
3766        let has_co_authors = room.map_or(false, |room| {
3767            room.read(cx)
3768                .remote_participants()
3769                .values()
3770                .any(|remote_participant| remote_participant.can_write())
3771        });
3772
3773        v_flex()
3774            .id("git_panel")
3775            .key_context(self.dispatch_context(window, cx))
3776            .track_focus(&self.focus_handle)
3777            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3778            .when(has_write_access && !project.is_read_only(cx), |this| {
3779                this.on_action(cx.listener(Self::toggle_staged_for_selected))
3780                    .on_action(cx.listener(GitPanel::commit))
3781                    .on_action(cx.listener(Self::stage_all))
3782                    .on_action(cx.listener(Self::unstage_all))
3783                    .on_action(cx.listener(Self::stage_selected))
3784                    .on_action(cx.listener(Self::unstage_selected))
3785                    .on_action(cx.listener(Self::restore_tracked_files))
3786                    .on_action(cx.listener(Self::revert_selected))
3787                    .on_action(cx.listener(Self::clean_all))
3788                    .on_action(cx.listener(Self::generate_commit_message_action))
3789            })
3790            .on_action(cx.listener(Self::select_first))
3791            .on_action(cx.listener(Self::select_next))
3792            .on_action(cx.listener(Self::select_previous))
3793            .on_action(cx.listener(Self::select_last))
3794            .on_action(cx.listener(Self::close_panel))
3795            .on_action(cx.listener(Self::open_diff))
3796            .on_action(cx.listener(Self::open_file))
3797            .on_action(cx.listener(Self::focus_changes_list))
3798            .on_action(cx.listener(Self::focus_editor))
3799            .on_action(cx.listener(Self::expand_commit_editor))
3800            .when(has_write_access && has_co_authors, |git_panel| {
3801                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3802            })
3803            .on_hover(cx.listener(move |this, hovered, window, cx| {
3804                if *hovered {
3805                    this.horizontal_scrollbar.show(cx);
3806                    this.vertical_scrollbar.show(cx);
3807                    cx.notify();
3808                } else if !this.focus_handle.contains_focused(window, cx) {
3809                    this.hide_scrollbars(window, cx);
3810                }
3811            }))
3812            .size_full()
3813            .overflow_hidden()
3814            .bg(ElevationIndex::Surface.bg(cx))
3815            .child(
3816                v_flex()
3817                    .size_full()
3818                    .children(self.render_panel_header(window, cx))
3819                    .map(|this| {
3820                        if has_entries {
3821                            this.child(self.render_entries(has_write_access, window, cx))
3822                        } else {
3823                            this.child(self.render_empty_state(cx).into_any_element())
3824                        }
3825                    })
3826                    .children(self.render_footer(window, cx))
3827                    .children(self.render_previous_commit(cx))
3828                    .into_any_element(),
3829            )
3830            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3831                deferred(
3832                    anchored()
3833                        .position(*position)
3834                        .anchor(Corner::TopLeft)
3835                        .child(menu.clone()),
3836                )
3837                .with_priority(1)
3838            }))
3839    }
3840}
3841
3842impl Focusable for GitPanel {
3843    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3844        if self.entries.is_empty() {
3845            self.commit_editor.focus_handle(cx)
3846        } else {
3847            self.focus_handle.clone()
3848        }
3849    }
3850}
3851
3852impl EventEmitter<Event> for GitPanel {}
3853
3854impl EventEmitter<PanelEvent> for GitPanel {}
3855
3856pub(crate) struct GitPanelAddon {
3857    pub(crate) workspace: WeakEntity<Workspace>,
3858}
3859
3860impl editor::Addon for GitPanelAddon {
3861    fn to_any(&self) -> &dyn std::any::Any {
3862        self
3863    }
3864
3865    fn render_buffer_header_controls(
3866        &self,
3867        excerpt_info: &ExcerptInfo,
3868        window: &Window,
3869        cx: &App,
3870    ) -> Option<AnyElement> {
3871        let file = excerpt_info.buffer.file()?;
3872        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3873
3874        git_panel
3875            .read(cx)
3876            .render_buffer_header_controls(&git_panel, &file, window, cx)
3877    }
3878}
3879
3880impl Panel for GitPanel {
3881    fn persistent_name() -> &'static str {
3882        "GitPanel"
3883    }
3884
3885    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3886        GitPanelSettings::get_global(cx).dock
3887    }
3888
3889    fn position_is_valid(&self, position: DockPosition) -> bool {
3890        matches!(position, DockPosition::Left | DockPosition::Right)
3891    }
3892
3893    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3894        settings::update_settings_file::<GitPanelSettings>(
3895            self.fs.clone(),
3896            cx,
3897            move |settings, _| settings.dock = Some(position),
3898        );
3899    }
3900
3901    fn size(&self, _: &Window, cx: &App) -> Pixels {
3902        self.width
3903            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3904    }
3905
3906    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3907        self.width = size;
3908        self.serialize(cx);
3909        cx.notify();
3910    }
3911
3912    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3913        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3914    }
3915
3916    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3917        Some("Git Panel")
3918    }
3919
3920    fn toggle_action(&self) -> Box<dyn Action> {
3921        Box::new(ToggleFocus)
3922    }
3923
3924    fn activation_priority(&self) -> u32 {
3925        2
3926    }
3927}
3928
3929impl PanelHeader for GitPanel {}
3930
3931struct GitPanelMessageTooltip {
3932    commit_tooltip: Option<Entity<CommitTooltip>>,
3933}
3934
3935impl GitPanelMessageTooltip {
3936    fn new(
3937        git_panel: Entity<GitPanel>,
3938        sha: SharedString,
3939        window: &mut Window,
3940        cx: &mut App,
3941    ) -> Entity<Self> {
3942        cx.new(|cx| {
3943            cx.spawn_in(window, |this, mut cx| async move {
3944                let details = git_panel
3945                    .update(&mut cx, |git_panel, cx| {
3946                        git_panel.load_commit_details(sha.to_string(), cx)
3947                    })?
3948                    .await?;
3949
3950                let commit_details = editor::commit_tooltip::CommitDetails {
3951                    sha: details.sha.clone(),
3952                    committer_name: details.committer_name.clone(),
3953                    committer_email: details.committer_email.clone(),
3954                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3955                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3956                        message: details.message.clone(),
3957                        ..Default::default()
3958                    }),
3959                };
3960
3961                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3962                    this.commit_tooltip =
3963                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3964                    cx.notify();
3965                })
3966            })
3967            .detach();
3968
3969            Self {
3970                commit_tooltip: None,
3971            }
3972        })
3973    }
3974}
3975
3976impl Render for GitPanelMessageTooltip {
3977    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3978        if let Some(commit_tooltip) = &self.commit_tooltip {
3979            commit_tooltip.clone().into_any_element()
3980        } else {
3981            gpui::Empty.into_any_element()
3982        }
3983    }
3984}
3985
3986#[derive(IntoElement, IntoComponent)]
3987#[component(scope = "Version Control")]
3988pub struct PanelRepoFooter {
3989    active_repository: SharedString,
3990    branch: Option<Branch>,
3991    // Getting a GitPanel in previews will be difficult.
3992    //
3993    // For now just take an option here, and we won't bind handlers to buttons in previews.
3994    git_panel: Option<Entity<GitPanel>>,
3995}
3996
3997impl PanelRepoFooter {
3998    pub fn new(
3999        active_repository: SharedString,
4000        branch: Option<Branch>,
4001        git_panel: Option<Entity<GitPanel>>,
4002    ) -> Self {
4003        Self {
4004            active_repository,
4005            branch,
4006            git_panel,
4007        }
4008    }
4009
4010    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4011        Self {
4012            active_repository,
4013            branch,
4014            git_panel: None,
4015        }
4016    }
4017}
4018
4019impl RenderOnce for PanelRepoFooter {
4020    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4021        let project = self
4022            .git_panel
4023            .as_ref()
4024            .map(|panel| panel.read(cx).project.clone());
4025
4026        let repo = self
4027            .git_panel
4028            .as_ref()
4029            .and_then(|panel| panel.read(cx).active_repository.clone());
4030
4031        let single_repo = project
4032            .as_ref()
4033            .map(|project| {
4034                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
4035            })
4036            .unwrap_or(true);
4037
4038        const MAX_BRANCH_LEN: usize = 16;
4039        const MAX_REPO_LEN: usize = 16;
4040        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4041
4042        let branch = self.branch.clone();
4043        let branch_name = branch
4044            .as_ref()
4045            .map_or(" (no branch)".into(), |branch| branch.name.clone());
4046        let active_repo_name = self.active_repository.clone();
4047
4048        let branch_actual_len = branch_name.len();
4049        let repo_actual_len = active_repo_name.len();
4050
4051        // ideally, show the whole branch and repo names but
4052        // when we can't, use a budget to allocate space between the two
4053        let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4054            <= LABEL_CHARACTER_BUDGET
4055        {
4056            (repo_actual_len, branch_actual_len)
4057        } else {
4058            if branch_actual_len <= MAX_BRANCH_LEN {
4059                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4060                (repo_space, branch_actual_len)
4061            } else if repo_actual_len <= MAX_REPO_LEN {
4062                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4063                (repo_actual_len, branch_space)
4064            } else {
4065                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4066            }
4067        };
4068
4069        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4070            active_repo_name.to_string()
4071        } else {
4072            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4073        };
4074
4075        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4076            branch_name.to_string()
4077        } else {
4078            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4079        };
4080
4081        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4082            .style(ButtonStyle::Transparent)
4083            .size(ButtonSize::None)
4084            .label_size(LabelSize::Small)
4085            .color(Color::Muted);
4086
4087        let repo_selector = PopoverMenu::new("repository-switcher")
4088            .menu({
4089                let project = project.clone();
4090                move |window, cx| {
4091                    let project = project.clone()?;
4092                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4093                }
4094            })
4095            .trigger_with_tooltip(
4096                repo_selector_trigger.disabled(single_repo).truncate(true),
4097                Tooltip::text("Switch active repository"),
4098            )
4099            .anchor(Corner::BottomLeft)
4100            .into_any_element();
4101
4102        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4103            .style(ButtonStyle::Transparent)
4104            .size(ButtonSize::None)
4105            .label_size(LabelSize::Small)
4106            .truncate(true)
4107            .tooltip(Tooltip::for_action_title(
4108                "Switch Branch",
4109                &zed_actions::git::Branch,
4110            ))
4111            .on_click(|_, window, cx| {
4112                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
4113            });
4114
4115        let branch_selector = PopoverMenu::new("popover-button")
4116            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4117            .trigger_with_tooltip(
4118                branch_selector_button,
4119                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
4120            )
4121            .anchor(Corner::BottomLeft)
4122            .offset(gpui::Point {
4123                x: px(0.0),
4124                y: px(-2.0),
4125            });
4126
4127        h_flex()
4128            .w_full()
4129            .px_2()
4130            .h(px(36.))
4131            .items_center()
4132            .justify_between()
4133            .gap_1()
4134            .child(
4135                h_flex()
4136                    .flex_1()
4137                    .overflow_hidden()
4138                    .items_center()
4139                    .child(
4140                        div().child(
4141                            Icon::new(IconName::GitBranchSmall)
4142                                .size(IconSize::Small)
4143                                .color(if single_repo {
4144                                    Color::Disabled
4145                                } else {
4146                                    Color::Muted
4147                                }),
4148                        ),
4149                    )
4150                    .child(repo_selector)
4151                    .when_some(branch.clone(), |this, _| {
4152                        this.child(
4153                            div()
4154                                .text_color(cx.theme().colors().text_muted)
4155                                .text_sm()
4156                                .child("/"),
4157                        )
4158                    })
4159                    .child(branch_selector),
4160            )
4161            .children(if let Some(git_panel) = self.git_panel {
4162                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4163            } else {
4164                None
4165            })
4166    }
4167}
4168
4169impl ComponentPreview for PanelRepoFooter {
4170    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
4171        let unknown_upstream = None;
4172        let no_remote_upstream = Some(UpstreamTracking::Gone);
4173        let ahead_of_upstream = Some(
4174            UpstreamTrackingStatus {
4175                ahead: 2,
4176                behind: 0,
4177            }
4178            .into(),
4179        );
4180        let behind_upstream = Some(
4181            UpstreamTrackingStatus {
4182                ahead: 0,
4183                behind: 2,
4184            }
4185            .into(),
4186        );
4187        let ahead_and_behind_upstream = Some(
4188            UpstreamTrackingStatus {
4189                ahead: 3,
4190                behind: 1,
4191            }
4192            .into(),
4193        );
4194
4195        let not_ahead_or_behind_upstream = Some(
4196            UpstreamTrackingStatus {
4197                ahead: 0,
4198                behind: 0,
4199            }
4200            .into(),
4201        );
4202
4203        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4204            Branch {
4205                is_head: true,
4206                name: "some-branch".into(),
4207                upstream: upstream.map(|tracking| Upstream {
4208                    ref_name: "origin/some-branch".into(),
4209                    tracking,
4210                }),
4211                most_recent_commit: Some(CommitSummary {
4212                    sha: "abc123".into(),
4213                    subject: "Modify stuff".into(),
4214                    commit_timestamp: 1710932954,
4215                    has_parent: true,
4216                }),
4217            }
4218        }
4219
4220        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4221            Branch {
4222                is_head: true,
4223                name: branch_name.to_string().into(),
4224                upstream: upstream.map(|tracking| Upstream {
4225                    ref_name: format!("zed/{}", branch_name).into(),
4226                    tracking,
4227                }),
4228                most_recent_commit: Some(CommitSummary {
4229                    sha: "abc123".into(),
4230                    subject: "Modify stuff".into(),
4231                    commit_timestamp: 1710932954,
4232                    has_parent: true,
4233                }),
4234            }
4235        }
4236
4237        fn active_repository(id: usize) -> SharedString {
4238            format!("repo-{}", id).into()
4239        }
4240
4241        let example_width = px(340.);
4242
4243        v_flex()
4244            .gap_6()
4245            .w_full()
4246            .flex_none()
4247            .children(vec![example_group_with_title(
4248                "Action Button States",
4249                vec![
4250                    single_example(
4251                        "No Branch",
4252                        div()
4253                            .w(example_width)
4254                            .overflow_hidden()
4255                            .child(PanelRepoFooter::new_preview(
4256                                active_repository(1).clone(),
4257                                None,
4258                            ))
4259                            .into_any_element(),
4260                    )
4261                    .grow(),
4262                    single_example(
4263                        "Remote status unknown",
4264                        div()
4265                            .w(example_width)
4266                            .overflow_hidden()
4267                            .child(PanelRepoFooter::new_preview(
4268                                active_repository(2).clone(),
4269                                Some(branch(unknown_upstream)),
4270                            ))
4271                            .into_any_element(),
4272                    )
4273                    .grow(),
4274                    single_example(
4275                        "No Remote Upstream",
4276                        div()
4277                            .w(example_width)
4278                            .overflow_hidden()
4279                            .child(PanelRepoFooter::new_preview(
4280                                active_repository(3).clone(),
4281                                Some(branch(no_remote_upstream)),
4282                            ))
4283                            .into_any_element(),
4284                    )
4285                    .grow(),
4286                    single_example(
4287                        "Not Ahead or Behind",
4288                        div()
4289                            .w(example_width)
4290                            .overflow_hidden()
4291                            .child(PanelRepoFooter::new_preview(
4292                                active_repository(4).clone(),
4293                                Some(branch(not_ahead_or_behind_upstream)),
4294                            ))
4295                            .into_any_element(),
4296                    )
4297                    .grow(),
4298                    single_example(
4299                        "Behind remote",
4300                        div()
4301                            .w(example_width)
4302                            .overflow_hidden()
4303                            .child(PanelRepoFooter::new_preview(
4304                                active_repository(5).clone(),
4305                                Some(branch(behind_upstream)),
4306                            ))
4307                            .into_any_element(),
4308                    )
4309                    .grow(),
4310                    single_example(
4311                        "Ahead of remote",
4312                        div()
4313                            .w(example_width)
4314                            .overflow_hidden()
4315                            .child(PanelRepoFooter::new_preview(
4316                                active_repository(6).clone(),
4317                                Some(branch(ahead_of_upstream)),
4318                            ))
4319                            .into_any_element(),
4320                    )
4321                    .grow(),
4322                    single_example(
4323                        "Ahead and behind remote",
4324                        div()
4325                            .w(example_width)
4326                            .overflow_hidden()
4327                            .child(PanelRepoFooter::new_preview(
4328                                active_repository(7).clone(),
4329                                Some(branch(ahead_and_behind_upstream)),
4330                            ))
4331                            .into_any_element(),
4332                    )
4333                    .grow(),
4334                ],
4335            )
4336            .grow()
4337            .vertical()])
4338            .children(vec![example_group_with_title(
4339                "Labels",
4340                vec![
4341                    single_example(
4342                        "Short Branch & Repo",
4343                        div()
4344                            .w(example_width)
4345                            .overflow_hidden()
4346                            .child(PanelRepoFooter::new_preview(
4347                                SharedString::from("zed"),
4348                                Some(custom("main", behind_upstream)),
4349                            ))
4350                            .into_any_element(),
4351                    )
4352                    .grow(),
4353                    single_example(
4354                        "Long Branch",
4355                        div()
4356                            .w(example_width)
4357                            .overflow_hidden()
4358                            .child(PanelRepoFooter::new_preview(
4359                                SharedString::from("zed"),
4360                                Some(custom(
4361                                    "redesign-and-update-git-ui-list-entry-style",
4362                                    behind_upstream,
4363                                )),
4364                            ))
4365                            .into_any_element(),
4366                    )
4367                    .grow(),
4368                    single_example(
4369                        "Long Repo",
4370                        div()
4371                            .w(example_width)
4372                            .overflow_hidden()
4373                            .child(PanelRepoFooter::new_preview(
4374                                SharedString::from("zed-industries-community-examples"),
4375                                Some(custom("gpui", ahead_of_upstream)),
4376                            ))
4377                            .into_any_element(),
4378                    )
4379                    .grow(),
4380                    single_example(
4381                        "Long Repo & Branch",
4382                        div()
4383                            .w(example_width)
4384                            .overflow_hidden()
4385                            .child(PanelRepoFooter::new_preview(
4386                                SharedString::from("zed-industries-community-examples"),
4387                                Some(custom(
4388                                    "redesign-and-update-git-ui-list-entry-style",
4389                                    behind_upstream,
4390                                )),
4391                            ))
4392                            .into_any_element(),
4393                    )
4394                    .grow(),
4395                    single_example(
4396                        "Uppercase Repo",
4397                        div()
4398                            .w(example_width)
4399                            .overflow_hidden()
4400                            .child(PanelRepoFooter::new_preview(
4401                                SharedString::from("LICENSES"),
4402                                Some(custom("main", ahead_of_upstream)),
4403                            ))
4404                            .into_any_element(),
4405                    )
4406                    .grow(),
4407                    single_example(
4408                        "Uppercase Branch",
4409                        div()
4410                            .w(example_width)
4411                            .overflow_hidden()
4412                            .child(PanelRepoFooter::new_preview(
4413                                SharedString::from("zed"),
4414                                Some(custom("update-README", behind_upstream)),
4415                            ))
4416                            .into_any_element(),
4417                    )
4418                    .grow(),
4419                ],
4420            )
4421            .grow()
4422            .vertical()])
4423            .into_any_element()
4424    }
4425}
4426
4427#[cfg(test)]
4428mod tests {
4429    use git::status::StatusCode;
4430    use gpui::TestAppContext;
4431    use project::{FakeFs, WorktreeSettings};
4432    use serde_json::json;
4433    use settings::SettingsStore;
4434    use theme::LoadThemes;
4435    use util::path;
4436
4437    use super::*;
4438
4439    fn init_test(cx: &mut gpui::TestAppContext) {
4440        if std::env::var("RUST_LOG").is_ok() {
4441            env_logger::try_init().ok();
4442        }
4443
4444        cx.update(|cx| {
4445            let settings_store = SettingsStore::test(cx);
4446            cx.set_global(settings_store);
4447            AssistantSettings::register(cx);
4448            WorktreeSettings::register(cx);
4449            workspace::init_settings(cx);
4450            theme::init(LoadThemes::JustBase, cx);
4451            language::init(cx);
4452            editor::init(cx);
4453            Project::init_settings(cx);
4454            crate::init(cx);
4455        });
4456    }
4457
4458    #[gpui::test]
4459    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4460        init_test(cx);
4461        let fs = FakeFs::new(cx.background_executor.clone());
4462        fs.insert_tree(
4463            "/root",
4464            json!({
4465                "zed": {
4466                    ".git": {},
4467                    "crates": {
4468                        "gpui": {
4469                            "gpui.rs": "fn main() {}"
4470                        },
4471                        "util": {
4472                            "util.rs": "fn do_it() {}"
4473                        }
4474                    }
4475                },
4476            }),
4477        )
4478        .await;
4479
4480        fs.set_status_for_repo_via_git_operation(
4481            Path::new(path!("/root/zed/.git")),
4482            &[
4483                (
4484                    Path::new("crates/gpui/gpui.rs"),
4485                    StatusCode::Modified.worktree(),
4486                ),
4487                (
4488                    Path::new("crates/util/util.rs"),
4489                    StatusCode::Modified.worktree(),
4490                ),
4491            ],
4492        );
4493
4494        let project =
4495            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4496        let (workspace, cx) =
4497            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4498
4499        cx.read(|cx| {
4500            project
4501                .read(cx)
4502                .worktrees(cx)
4503                .nth(0)
4504                .unwrap()
4505                .read(cx)
4506                .as_local()
4507                .unwrap()
4508                .scan_complete()
4509        })
4510        .await;
4511
4512        cx.executor().run_until_parked();
4513
4514        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4515        let panel = cx.new_window_entity(|window, cx| {
4516            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4517        });
4518
4519        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4520            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4521        });
4522        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4523        handle.await;
4524
4525        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4526        pretty_assertions::assert_eq!(
4527            entries,
4528            [
4529                GitListEntry::Header(GitHeaderEntry {
4530                    header: Section::Tracked
4531                }),
4532                GitListEntry::GitStatusEntry(GitStatusEntry {
4533                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4534                    repo_path: "crates/gpui/gpui.rs".into(),
4535                    worktree_path: Path::new("gpui.rs").into(),
4536                    status: StatusCode::Modified.worktree(),
4537                    staging: StageStatus::Unstaged,
4538                }),
4539                GitListEntry::GitStatusEntry(GitStatusEntry {
4540                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4541                    repo_path: "crates/util/util.rs".into(),
4542                    worktree_path: Path::new("../util/util.rs").into(),
4543                    status: StatusCode::Modified.worktree(),
4544                    staging: StageStatus::Unstaged,
4545                },),
4546            ],
4547        );
4548
4549        cx.update_window_entity(&panel, |panel, window, cx| {
4550            panel.select_last(&Default::default(), window, cx);
4551            assert_eq!(panel.selected_entry, Some(2));
4552            panel.open_diff(&Default::default(), window, cx);
4553        });
4554        cx.run_until_parked();
4555
4556        let worktree_roots = workspace.update(cx, |workspace, cx| {
4557            workspace
4558                .worktrees(cx)
4559                .map(|worktree| worktree.read(cx).abs_path())
4560                .collect::<Vec<_>>()
4561        });
4562        pretty_assertions::assert_eq!(
4563            worktree_roots,
4564            vec![
4565                Path::new(path!("/root/zed/crates/gpui")).into(),
4566                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4567            ]
4568        );
4569
4570        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4571            let git_store = project.git_store().read(cx);
4572            // The repo that comes from the single-file worktree can't be selected through the UI.
4573            let filtered_entries = filtered_repository_entries(git_store, cx)
4574                .iter()
4575                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4576                .collect::<Vec<_>>();
4577            assert_eq!(
4578                filtered_entries,
4579                [Path::new(path!("/root/zed/crates/gpui")).into()]
4580            );
4581            // But we can select it artificially here.
4582            git_store
4583                .all_repositories()
4584                .into_iter()
4585                .find(|repo| {
4586                    &*repo.read(cx).worktree_abs_path
4587                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4588                })
4589                .unwrap()
4590        });
4591
4592        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4593        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4594        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4595            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4596        });
4597        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4598        handle.await;
4599        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4600        pretty_assertions::assert_eq!(
4601            entries,
4602            [
4603                GitListEntry::Header(GitHeaderEntry {
4604                    header: Section::Tracked
4605                }),
4606                GitListEntry::GitStatusEntry(GitStatusEntry {
4607                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4608                    repo_path: "crates/gpui/gpui.rs".into(),
4609                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4610                    status: StatusCode::Modified.worktree(),
4611                    staging: StageStatus::Unstaged,
4612                }),
4613                GitListEntry::GitStatusEntry(GitStatusEntry {
4614                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4615                    repo_path: "crates/util/util.rs".into(),
4616                    worktree_path: Path::new("util.rs").into(),
4617                    status: StatusCode::Modified.worktree(),
4618                    staging: StageStatus::Unstaged,
4619                },),
4620            ],
4621        );
4622    }
4623}