git_panel.rs

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