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