git_panel.rs

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