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::<GitPanelSettings>(fs, move |settings, _cx| {
2443                    settings.sort_by_path = Some(!current_setting);
2444                });
2445            });
2446        }
2447    }
2448
2449    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2450        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2451
2452        let existing_text = message.to_ascii_lowercase();
2453        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2454        let mut ends_with_co_authors = false;
2455        let existing_co_authors = existing_text
2456            .lines()
2457            .filter_map(|line| {
2458                let line = line.trim();
2459                if line.starts_with(&lowercase_co_author_prefix) {
2460                    ends_with_co_authors = true;
2461                    Some(line)
2462                } else {
2463                    ends_with_co_authors = false;
2464                    None
2465                }
2466            })
2467            .collect::<HashSet<_>>();
2468
2469        let new_co_authors = self
2470            .potential_co_authors(cx)
2471            .into_iter()
2472            .filter(|(_, email)| {
2473                !existing_co_authors
2474                    .iter()
2475                    .any(|existing| existing.contains(email.as_str()))
2476            })
2477            .collect::<Vec<_>>();
2478
2479        if new_co_authors.is_empty() {
2480            return;
2481        }
2482
2483        if !ends_with_co_authors {
2484            message.push('\n');
2485        }
2486        for (name, email) in new_co_authors {
2487            message.push('\n');
2488            message.push_str(CO_AUTHOR_PREFIX);
2489            message.push_str(&name);
2490            message.push_str(" <");
2491            message.push_str(&email);
2492            message.push('>');
2493        }
2494        message.push('\n');
2495    }
2496
2497    fn schedule_update(
2498        &mut self,
2499        clear_pending: bool,
2500        window: &mut Window,
2501        cx: &mut Context<Self>,
2502    ) {
2503        let handle = cx.entity().downgrade();
2504        self.reopen_commit_buffer(window, cx);
2505        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2506            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2507            if let Some(git_panel) = handle.upgrade() {
2508                git_panel
2509                    .update_in(cx, |git_panel, window, cx| {
2510                        if clear_pending {
2511                            git_panel.clear_pending();
2512                        }
2513                        git_panel.update_visible_entries(window, cx);
2514                    })
2515                    .ok();
2516            }
2517        });
2518    }
2519
2520    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2521        let Some(active_repo) = self.active_repository.as_ref() else {
2522            return;
2523        };
2524        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2525            let project = self.project.read(cx);
2526            active_repo.open_commit_buffer(
2527                Some(project.languages().clone()),
2528                project.buffer_store().clone(),
2529                cx,
2530            )
2531        });
2532
2533        cx.spawn_in(window, async move |git_panel, cx| {
2534            let buffer = load_buffer.await?;
2535            git_panel.update_in(cx, |git_panel, window, cx| {
2536                if git_panel
2537                    .commit_editor
2538                    .read(cx)
2539                    .buffer()
2540                    .read(cx)
2541                    .as_singleton()
2542                    .as_ref()
2543                    != Some(&buffer)
2544                {
2545                    git_panel.commit_editor = cx.new(|cx| {
2546                        commit_message_editor(
2547                            buffer,
2548                            git_panel.suggest_commit_message(cx).map(SharedString::from),
2549                            git_panel.project.clone(),
2550                            true,
2551                            window,
2552                            cx,
2553                        )
2554                    });
2555                }
2556            })
2557        })
2558        .detach_and_log_err(cx);
2559    }
2560
2561    fn clear_pending(&mut self) {
2562        self.pending.retain(|v| !v.finished)
2563    }
2564
2565    fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2566        let bulk_staging = self.bulk_staging.take();
2567        let last_staged_path_prev_index = bulk_staging
2568            .as_ref()
2569            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2570
2571        self.entries.clear();
2572        self.single_staged_entry.take();
2573        self.single_tracked_entry.take();
2574        self.conflicted_count = 0;
2575        self.conflicted_staged_count = 0;
2576        self.new_count = 0;
2577        self.tracked_count = 0;
2578        self.new_staged_count = 0;
2579        self.tracked_staged_count = 0;
2580        self.entry_count = 0;
2581
2582        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2583
2584        let mut changed_entries = Vec::new();
2585        let mut new_entries = Vec::new();
2586        let mut conflict_entries = Vec::new();
2587        let mut single_staged_entry = None;
2588        let mut staged_count = 0;
2589        let mut max_width_item: Option<(RepoPath, usize)> = None;
2590
2591        let Some(repo) = self.active_repository.as_ref() else {
2592            // Just clear entries if no repository is active.
2593            cx.notify();
2594            return;
2595        };
2596
2597        let repo = repo.read(cx);
2598
2599        self.stash_entries = repo.cached_stash();
2600
2601        for entry in repo.cached_status() {
2602            let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2603            let is_new = entry.status.is_created();
2604            let staging = entry.status.staging();
2605
2606            if self.pending.iter().any(|pending| {
2607                pending.target_status == TargetStatus::Reverted
2608                    && !pending.finished
2609                    && pending
2610                        .entries
2611                        .iter()
2612                        .any(|pending| pending.repo_path == entry.repo_path)
2613            }) {
2614                continue;
2615            }
2616
2617            let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2618            let entry = GitStatusEntry {
2619                repo_path: entry.repo_path.clone(),
2620                abs_path,
2621                status: entry.status,
2622                staging,
2623            };
2624
2625            if staging.has_staged() {
2626                staged_count += 1;
2627                single_staged_entry = Some(entry.clone());
2628            }
2629
2630            let width_estimate = Self::item_width_estimate(
2631                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2632                entry.display_name().len(),
2633            );
2634
2635            match max_width_item.as_mut() {
2636                Some((repo_path, estimate)) => {
2637                    if width_estimate > *estimate {
2638                        *repo_path = entry.repo_path.clone();
2639                        *estimate = width_estimate;
2640                    }
2641                }
2642                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2643            }
2644
2645            if sort_by_path {
2646                changed_entries.push(entry);
2647            } else if is_conflict {
2648                conflict_entries.push(entry);
2649            } else if is_new {
2650                new_entries.push(entry);
2651            } else {
2652                changed_entries.push(entry);
2653            }
2654        }
2655
2656        let mut pending_staged_count = 0;
2657        let mut last_pending_staged = None;
2658        let mut pending_status_for_single_staged = None;
2659        for pending in self.pending.iter() {
2660            if pending.target_status == TargetStatus::Staged {
2661                pending_staged_count += pending.entries.len();
2662                last_pending_staged = pending.entries.first().cloned();
2663            }
2664            if let Some(single_staged) = &single_staged_entry
2665                && pending
2666                    .entries
2667                    .iter()
2668                    .any(|entry| entry.repo_path == single_staged.repo_path)
2669            {
2670                pending_status_for_single_staged = Some(pending.target_status);
2671            }
2672        }
2673
2674        if conflict_entries.is_empty() && staged_count == 1 && pending_staged_count == 0 {
2675            match pending_status_for_single_staged {
2676                Some(TargetStatus::Staged) | None => {
2677                    self.single_staged_entry = single_staged_entry;
2678                }
2679                _ => {}
2680            }
2681        } else if conflict_entries.is_empty() && pending_staged_count == 1 {
2682            self.single_staged_entry = last_pending_staged;
2683        }
2684
2685        if conflict_entries.is_empty() && changed_entries.len() == 1 {
2686            self.single_tracked_entry = changed_entries.first().cloned();
2687        }
2688
2689        if !conflict_entries.is_empty() {
2690            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2691                header: Section::Conflict,
2692            }));
2693            self.entries
2694                .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2695        }
2696
2697        if !changed_entries.is_empty() {
2698            if !sort_by_path {
2699                self.entries.push(GitListEntry::Header(GitHeaderEntry {
2700                    header: Section::Tracked,
2701                }));
2702            }
2703            self.entries
2704                .extend(changed_entries.into_iter().map(GitListEntry::Status));
2705        }
2706        if !new_entries.is_empty() {
2707            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2708                header: Section::New,
2709            }));
2710            self.entries
2711                .extend(new_entries.into_iter().map(GitListEntry::Status));
2712        }
2713
2714        if let Some((repo_path, _)) = max_width_item {
2715            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2716                GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2717                GitListEntry::Header(_) => false,
2718            });
2719        }
2720
2721        self.update_counts(repo);
2722
2723        let bulk_staging_anchor_new_index = bulk_staging
2724            .as_ref()
2725            .filter(|op| op.repo_id == repo.id)
2726            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2727        if bulk_staging_anchor_new_index == last_staged_path_prev_index
2728            && let Some(index) = bulk_staging_anchor_new_index
2729            && let Some(entry) = self.entries.get(index)
2730            && let Some(entry) = entry.status_entry()
2731            && self.entry_staging(entry) == StageStatus::Staged
2732        {
2733            self.bulk_staging = bulk_staging;
2734        }
2735
2736        self.select_first_entry_if_none(cx);
2737
2738        let suggested_commit_message = self.suggest_commit_message(cx);
2739        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2740
2741        self.commit_editor.update(cx, |editor, cx| {
2742            editor.set_placeholder_text(&placeholder_text, window, cx)
2743        });
2744
2745        cx.notify();
2746    }
2747
2748    fn header_state(&self, header_type: Section) -> ToggleState {
2749        let (staged_count, count) = match header_type {
2750            Section::New => (self.new_staged_count, self.new_count),
2751            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2752            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2753        };
2754        if staged_count == 0 {
2755            ToggleState::Unselected
2756        } else if count == staged_count {
2757            ToggleState::Selected
2758        } else {
2759            ToggleState::Indeterminate
2760        }
2761    }
2762
2763    fn update_counts(&mut self, repo: &Repository) {
2764        self.show_placeholders = false;
2765        self.conflicted_count = 0;
2766        self.conflicted_staged_count = 0;
2767        self.new_count = 0;
2768        self.tracked_count = 0;
2769        self.new_staged_count = 0;
2770        self.tracked_staged_count = 0;
2771        self.entry_count = 0;
2772        for entry in &self.entries {
2773            let Some(status_entry) = entry.status_entry() else {
2774                continue;
2775            };
2776            self.entry_count += 1;
2777            if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2778                self.conflicted_count += 1;
2779                if self.entry_staging(status_entry).has_staged() {
2780                    self.conflicted_staged_count += 1;
2781                }
2782            } else if status_entry.status.is_created() {
2783                self.new_count += 1;
2784                if self.entry_staging(status_entry).has_staged() {
2785                    self.new_staged_count += 1;
2786                }
2787            } else {
2788                self.tracked_count += 1;
2789                if self.entry_staging(status_entry).has_staged() {
2790                    self.tracked_staged_count += 1;
2791                }
2792            }
2793        }
2794    }
2795
2796    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2797        for pending in self.pending.iter().rev() {
2798            if pending
2799                .entries
2800                .iter()
2801                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2802            {
2803                match pending.target_status {
2804                    TargetStatus::Staged => return StageStatus::Staged,
2805                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2806                    TargetStatus::Reverted => continue,
2807                    TargetStatus::Unchanged => continue,
2808                }
2809            }
2810        }
2811        entry.staging
2812    }
2813
2814    pub(crate) fn has_staged_changes(&self) -> bool {
2815        self.tracked_staged_count > 0
2816            || self.new_staged_count > 0
2817            || self.conflicted_staged_count > 0
2818    }
2819
2820    pub(crate) fn has_unstaged_changes(&self) -> bool {
2821        self.tracked_count > self.tracked_staged_count
2822            || self.new_count > self.new_staged_count
2823            || self.conflicted_count > self.conflicted_staged_count
2824    }
2825
2826    fn has_tracked_changes(&self) -> bool {
2827        self.tracked_count > 0
2828    }
2829
2830    pub fn has_unstaged_conflicts(&self) -> bool {
2831        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2832    }
2833
2834    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2835        let action = action.into();
2836        let Some(workspace) = self.workspace.upgrade() else {
2837            return;
2838        };
2839
2840        let message = e.to_string().trim().to_string();
2841        if message
2842            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2843            .next()
2844            .is_some()
2845        { // Hide the cancelled by user message
2846        } else {
2847            workspace.update(cx, |workspace, cx| {
2848                let workspace_weak = cx.weak_entity();
2849                let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2850                    this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2851                        .action("View Log", move |window, cx| {
2852                            let message = message.clone();
2853                            let action = action.clone();
2854                            workspace_weak
2855                                .update(cx, move |workspace, cx| {
2856                                    Self::open_output(action, workspace, &message, window, cx)
2857                                })
2858                                .ok();
2859                        })
2860                });
2861                workspace.toggle_status_toast(toast, cx)
2862            });
2863        }
2864    }
2865
2866    fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
2867    where
2868        E: std::fmt::Debug + std::fmt::Display,
2869    {
2870        if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
2871            let _ = workspace.update(cx, |workspace, cx| {
2872                struct CommitMessageError;
2873                let notification_id = NotificationId::unique::<CommitMessageError>();
2874                workspace.show_notification(notification_id, cx, |cx| {
2875                    cx.new(|cx| {
2876                        ErrorMessagePrompt::new(
2877                            format!("Failed to generate commit message: {err}"),
2878                            cx,
2879                        )
2880                    })
2881                });
2882            });
2883        }
2884    }
2885
2886    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2887        let Some(workspace) = self.workspace.upgrade() else {
2888            return;
2889        };
2890
2891        workspace.update(cx, |workspace, cx| {
2892            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2893            let workspace_weak = cx.weak_entity();
2894            let operation = action.name();
2895
2896            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2897                use remote_output::SuccessStyle::*;
2898                match style {
2899                    Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
2900                    ToastWithLog { output } => this
2901                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2902                        .action("View Log", move |window, cx| {
2903                            let output = output.clone();
2904                            let output =
2905                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2906                            workspace_weak
2907                                .update(cx, move |workspace, cx| {
2908                                    Self::open_output(operation, workspace, &output, window, cx)
2909                                })
2910                                .ok();
2911                        }),
2912                    PushPrLink { text, link } => this
2913                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2914                        .action(text, move |_, cx| cx.open_url(&link)),
2915                }
2916            });
2917            workspace.toggle_status_toast(status_toast, cx)
2918        });
2919    }
2920
2921    fn open_output(
2922        operation: impl Into<SharedString>,
2923        workspace: &mut Workspace,
2924        output: &str,
2925        window: &mut Window,
2926        cx: &mut Context<Workspace>,
2927    ) {
2928        let operation = operation.into();
2929        let buffer = cx.new(|cx| Buffer::local(output, cx));
2930        buffer.update(cx, |buffer, cx| {
2931            buffer.set_capability(language::Capability::ReadOnly, cx);
2932        });
2933        let editor = cx.new(|cx| {
2934            let mut editor = Editor::for_buffer(buffer, None, window, cx);
2935            editor.buffer().update(cx, |buffer, cx| {
2936                buffer.set_title(format!("Output from git {operation}"), cx);
2937            });
2938            editor.set_read_only(true);
2939            editor
2940        });
2941
2942        workspace.add_item_to_center(Box::new(editor), window, cx);
2943    }
2944
2945    pub fn can_commit(&self) -> bool {
2946        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2947    }
2948
2949    pub fn can_stage_all(&self) -> bool {
2950        self.has_unstaged_changes()
2951    }
2952
2953    pub fn can_unstage_all(&self) -> bool {
2954        self.has_staged_changes()
2955    }
2956
2957    // eventually we'll need to take depth into account here
2958    // if we add a tree view
2959    fn item_width_estimate(path: usize, file_name: usize) -> usize {
2960        path + file_name
2961    }
2962
2963    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2964        let focus_handle = self.focus_handle.clone();
2965        let has_tracked_changes = self.has_tracked_changes();
2966        let has_staged_changes = self.has_staged_changes();
2967        let has_unstaged_changes = self.has_unstaged_changes();
2968        let has_new_changes = self.new_count > 0;
2969        let has_stash_items = self.stash_entries.entries.len() > 0;
2970
2971        PopoverMenu::new(id.into())
2972            .trigger(
2973                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
2974                    .icon_size(IconSize::Small)
2975                    .icon_color(Color::Muted),
2976            )
2977            .menu(move |window, cx| {
2978                Some(git_panel_context_menu(
2979                    focus_handle.clone(),
2980                    GitMenuState {
2981                        has_tracked_changes,
2982                        has_staged_changes,
2983                        has_unstaged_changes,
2984                        has_new_changes,
2985                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
2986                        has_stash_items,
2987                    },
2988                    window,
2989                    cx,
2990                ))
2991            })
2992            .anchor(Corner::TopRight)
2993    }
2994
2995    pub(crate) fn render_generate_commit_message_button(
2996        &self,
2997        cx: &Context<Self>,
2998    ) -> Option<AnyElement> {
2999        if !agent_settings::AgentSettings::get_global(cx).enabled
3000            || DisableAiSettings::get_global(cx).disable_ai
3001            || LanguageModelRegistry::read_global(cx)
3002                .commit_message_model()
3003                .is_none()
3004        {
3005            return None;
3006        }
3007
3008        if self.generate_commit_message_task.is_some() {
3009            return Some(
3010                h_flex()
3011                    .gap_1()
3012                    .child(
3013                        Icon::new(IconName::ArrowCircle)
3014                            .size(IconSize::XSmall)
3015                            .color(Color::Info)
3016                            .with_rotate_animation(2),
3017                    )
3018                    .child(
3019                        Label::new("Generating Commit...")
3020                            .size(LabelSize::Small)
3021                            .color(Color::Muted),
3022                    )
3023                    .into_any_element(),
3024            );
3025        }
3026
3027        let can_commit = self.can_commit();
3028        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3029        Some(
3030            IconButton::new("generate-commit-message", IconName::AiEdit)
3031                .shape(ui::IconButtonShape::Square)
3032                .icon_color(Color::Muted)
3033                .tooltip(move |window, cx| {
3034                    if can_commit {
3035                        Tooltip::for_action_in(
3036                            "Generate Commit Message",
3037                            &git::GenerateCommitMessage,
3038                            &editor_focus_handle,
3039                            window,
3040                            cx,
3041                        )
3042                    } else {
3043                        Tooltip::simple("No changes to commit", cx)
3044                    }
3045                })
3046                .disabled(!can_commit)
3047                .on_click(cx.listener(move |this, _event, _window, cx| {
3048                    this.generate_commit_message(cx);
3049                }))
3050                .into_any_element(),
3051        )
3052    }
3053
3054    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3055        let potential_co_authors = self.potential_co_authors(cx);
3056
3057        let (tooltip_label, icon) = if self.add_coauthors {
3058            ("Remove co-authored-by", IconName::Person)
3059        } else {
3060            ("Add co-authored-by", IconName::UserCheck)
3061        };
3062
3063        if potential_co_authors.is_empty() {
3064            None
3065        } else {
3066            Some(
3067                IconButton::new("co-authors", icon)
3068                    .shape(ui::IconButtonShape::Square)
3069                    .icon_color(Color::Disabled)
3070                    .selected_icon_color(Color::Selected)
3071                    .toggle_state(self.add_coauthors)
3072                    .tooltip(move |_, cx| {
3073                        let title = format!(
3074                            "{}:{}{}",
3075                            tooltip_label,
3076                            if potential_co_authors.len() == 1 {
3077                                ""
3078                            } else {
3079                                "\n"
3080                            },
3081                            potential_co_authors
3082                                .iter()
3083                                .map(|(name, email)| format!(" {} <{}>", name, email))
3084                                .join("\n")
3085                        );
3086                        Tooltip::simple(title, cx)
3087                    })
3088                    .on_click(cx.listener(|this, _, _, cx| {
3089                        this.add_coauthors = !this.add_coauthors;
3090                        cx.notify();
3091                    }))
3092                    .into_any_element(),
3093            )
3094        }
3095    }
3096
3097    fn render_git_commit_menu(
3098        &self,
3099        id: impl Into<ElementId>,
3100        keybinding_target: Option<FocusHandle>,
3101        cx: &mut Context<Self>,
3102    ) -> impl IntoElement {
3103        PopoverMenu::new(id.into())
3104            .trigger(
3105                ui::ButtonLike::new_rounded_right("commit-split-button-right")
3106                    .layer(ui::ElevationIndex::ModalSurface)
3107                    .size(ButtonSize::None)
3108                    .child(
3109                        h_flex()
3110                            .px_1()
3111                            .h_full()
3112                            .justify_center()
3113                            .border_l_1()
3114                            .border_color(cx.theme().colors().border)
3115                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3116                    ),
3117            )
3118            .menu({
3119                let git_panel = cx.entity();
3120                let has_previous_commit = self.head_commit(cx).is_some();
3121                let amend = self.amend_pending();
3122                let signoff = self.signoff_enabled;
3123
3124                move |window, cx| {
3125                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3126                        context_menu
3127                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
3128                                el.context(keybinding_target)
3129                            })
3130                            .when(has_previous_commit, |this| {
3131                                this.toggleable_entry(
3132                                    "Amend",
3133                                    amend,
3134                                    IconPosition::Start,
3135                                    Some(Box::new(Amend)),
3136                                    {
3137                                        let git_panel = git_panel.downgrade();
3138                                        move |_, cx| {
3139                                            git_panel
3140                                                .update(cx, |git_panel, cx| {
3141                                                    git_panel.toggle_amend_pending(cx);
3142                                                })
3143                                                .ok();
3144                                        }
3145                                    },
3146                                )
3147                            })
3148                            .toggleable_entry(
3149                                "Signoff",
3150                                signoff,
3151                                IconPosition::Start,
3152                                Some(Box::new(Signoff)),
3153                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3154                            )
3155                    }))
3156                }
3157            })
3158            .anchor(Corner::TopRight)
3159    }
3160
3161    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3162        if self.has_unstaged_conflicts() {
3163            (false, "You must resolve conflicts before committing")
3164        } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
3165            (false, "No changes to commit")
3166        } else if self.pending_commit.is_some() {
3167            (false, "Commit in progress")
3168        } else if !self.has_commit_message(cx) {
3169            (false, "No commit message")
3170        } else if !self.has_write_access(cx) {
3171            (false, "You do not have write access to this project")
3172        } else {
3173            (true, self.commit_button_title())
3174        }
3175    }
3176
3177    pub fn commit_button_title(&self) -> &'static str {
3178        if self.amend_pending {
3179            if self.has_staged_changes() {
3180                "Amend"
3181            } else if self.has_tracked_changes() {
3182                "Amend Tracked"
3183            } else {
3184                "Amend"
3185            }
3186        } else if self.has_staged_changes() {
3187            "Commit"
3188        } else {
3189            "Commit Tracked"
3190        }
3191    }
3192
3193    fn expand_commit_editor(
3194        &mut self,
3195        _: &git::ExpandCommitEditor,
3196        window: &mut Window,
3197        cx: &mut Context<Self>,
3198    ) {
3199        let workspace = self.workspace.clone();
3200        window.defer(cx, move |window, cx| {
3201            workspace
3202                .update(cx, |workspace, cx| {
3203                    CommitModal::toggle(workspace, None, window, cx)
3204                })
3205                .ok();
3206        })
3207    }
3208
3209    fn render_panel_header(
3210        &self,
3211        window: &mut Window,
3212        cx: &mut Context<Self>,
3213    ) -> Option<impl IntoElement> {
3214        self.active_repository.as_ref()?;
3215
3216        let text;
3217        let action;
3218        let tooltip;
3219        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3220            text = "Unstage All";
3221            action = git::UnstageAll.boxed_clone();
3222            tooltip = "git reset";
3223        } else {
3224            text = "Stage All";
3225            action = git::StageAll.boxed_clone();
3226            tooltip = "git add --all ."
3227        }
3228
3229        let change_string = match self.entry_count {
3230            0 => "No Changes".to_string(),
3231            1 => "1 Change".to_string(),
3232            _ => format!("{} Changes", self.entry_count),
3233        };
3234
3235        Some(
3236            self.panel_header_container(window, cx)
3237                .px_2()
3238                .justify_between()
3239                .child(
3240                    panel_button(change_string)
3241                        .color(Color::Muted)
3242                        .tooltip(Tooltip::for_action_title_in(
3243                            "Open Diff",
3244                            &Diff,
3245                            &self.focus_handle,
3246                        ))
3247                        .on_click(|_, _, cx| {
3248                            cx.defer(|cx| {
3249                                cx.dispatch_action(&Diff);
3250                            })
3251                        }),
3252                )
3253                .child(
3254                    h_flex()
3255                        .gap_1()
3256                        .child(self.render_overflow_menu("overflow_menu"))
3257                        .child(
3258                            panel_filled_button(text)
3259                                .tooltip(Tooltip::for_action_title_in(
3260                                    tooltip,
3261                                    action.as_ref(),
3262                                    &self.focus_handle,
3263                                ))
3264                                .disabled(self.entry_count == 0)
3265                                .on_click(move |_, _, cx| {
3266                                    let action = action.boxed_clone();
3267                                    cx.defer(move |cx| {
3268                                        cx.dispatch_action(action.as_ref());
3269                                    })
3270                                }),
3271                        ),
3272                ),
3273        )
3274    }
3275
3276    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3277        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3278        if !self.can_push_and_pull(cx) {
3279            return None;
3280        }
3281        Some(
3282            h_flex()
3283                .gap_1()
3284                .flex_shrink_0()
3285                .when_some(branch, |this, branch| {
3286                    let focus_handle = Some(self.focus_handle(cx));
3287
3288                    this.children(render_remote_button(
3289                        "remote-button",
3290                        &branch,
3291                        focus_handle,
3292                        true,
3293                    ))
3294                })
3295                .into_any_element(),
3296        )
3297    }
3298
3299    pub fn render_footer(
3300        &self,
3301        window: &mut Window,
3302        cx: &mut Context<Self>,
3303    ) -> Option<impl IntoElement> {
3304        let active_repository = self.active_repository.clone()?;
3305        let panel_editor_style = panel_editor_style(true, window, cx);
3306
3307        let enable_coauthors = self.render_co_authors(cx);
3308
3309        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3310        let expand_tooltip_focus_handle = editor_focus_handle;
3311
3312        let branch = active_repository.read(cx).branch.clone();
3313        let head_commit = active_repository.read(cx).head_commit.clone();
3314
3315        let footer_size = px(32.);
3316        let gap = px(9.0);
3317        let max_height = panel_editor_style
3318            .text
3319            .line_height_in_pixels(window.rem_size())
3320            * MAX_PANEL_EDITOR_LINES
3321            + gap;
3322
3323        let git_panel = cx.entity();
3324        let display_name = SharedString::from(Arc::from(
3325            active_repository
3326                .read(cx)
3327                .display_name()
3328                .trim_end_matches("/"),
3329        ));
3330        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3331            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3332        });
3333
3334        let footer = v_flex()
3335            .child(PanelRepoFooter::new(
3336                display_name,
3337                branch,
3338                head_commit,
3339                Some(git_panel),
3340            ))
3341            .child(
3342                panel_editor_container(window, cx)
3343                    .id("commit-editor-container")
3344                    .relative()
3345                    .w_full()
3346                    .h(max_height + footer_size)
3347                    .border_t_1()
3348                    .border_color(cx.theme().colors().border)
3349                    .cursor_text()
3350                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3351                        window.focus(&this.commit_editor.focus_handle(cx));
3352                    }))
3353                    .child(
3354                        h_flex()
3355                            .id("commit-footer")
3356                            .border_t_1()
3357                            .when(editor_is_long, |el| {
3358                                el.border_color(cx.theme().colors().border_variant)
3359                            })
3360                            .absolute()
3361                            .bottom_0()
3362                            .left_0()
3363                            .w_full()
3364                            .px_2()
3365                            .h(footer_size)
3366                            .flex_none()
3367                            .justify_between()
3368                            .child(
3369                                self.render_generate_commit_message_button(cx)
3370                                    .unwrap_or_else(|| div().into_any_element()),
3371                            )
3372                            .child(
3373                                h_flex()
3374                                    .gap_0p5()
3375                                    .children(enable_coauthors)
3376                                    .child(self.render_commit_button(cx)),
3377                            ),
3378                    )
3379                    .child(
3380                        div()
3381                            .pr_2p5()
3382                            .on_action(|&editor::actions::MoveUp, _, cx| {
3383                                cx.stop_propagation();
3384                            })
3385                            .on_action(|&editor::actions::MoveDown, _, cx| {
3386                                cx.stop_propagation();
3387                            })
3388                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3389                    )
3390                    .child(
3391                        h_flex()
3392                            .absolute()
3393                            .top_2()
3394                            .right_2()
3395                            .opacity(0.5)
3396                            .hover(|this| this.opacity(1.0))
3397                            .child(
3398                                panel_icon_button("expand-commit-editor", IconName::Maximize)
3399                                    .icon_size(IconSize::Small)
3400                                    .size(ui::ButtonSize::Default)
3401                                    .tooltip(move |window, cx| {
3402                                        Tooltip::for_action_in(
3403                                            "Open Commit Modal",
3404                                            &git::ExpandCommitEditor,
3405                                            &expand_tooltip_focus_handle,
3406                                            window,
3407                                            cx,
3408                                        )
3409                                    })
3410                                    .on_click(cx.listener({
3411                                        move |_, _, window, cx| {
3412                                            window.dispatch_action(
3413                                                git::ExpandCommitEditor.boxed_clone(),
3414                                                cx,
3415                                            )
3416                                        }
3417                                    })),
3418                            ),
3419                    ),
3420            );
3421
3422        Some(footer)
3423    }
3424
3425    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3426        let (can_commit, tooltip) = self.configure_commit_button(cx);
3427        let title = self.commit_button_title();
3428        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3429        let amend = self.amend_pending();
3430        let signoff = self.signoff_enabled;
3431
3432        div()
3433            .id("commit-wrapper")
3434            .on_hover(cx.listener(move |this, hovered, _, cx| {
3435                this.show_placeholders =
3436                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3437                cx.notify()
3438            }))
3439            .child(SplitButton::new(
3440                ui::ButtonLike::new_rounded_left(ElementId::Name(
3441                    format!("split-button-left-{}", title).into(),
3442                ))
3443                .layer(ui::ElevationIndex::ModalSurface)
3444                .size(ui::ButtonSize::Compact)
3445                .child(
3446                    div()
3447                        .child(Label::new(title).size(LabelSize::Small))
3448                        .mr_0p5(),
3449                )
3450                .on_click({
3451                    let git_panel = cx.weak_entity();
3452                    move |_, window, cx| {
3453                        telemetry::event!("Git Committed", source = "Git Panel");
3454                        git_panel
3455                            .update(cx, |git_panel, cx| {
3456                                git_panel.set_amend_pending(false, cx);
3457                                git_panel.commit_changes(
3458                                    CommitOptions { amend, signoff },
3459                                    window,
3460                                    cx,
3461                                );
3462                            })
3463                            .ok();
3464                    }
3465                })
3466                .disabled(!can_commit || self.modal_open)
3467                .tooltip({
3468                    let handle = commit_tooltip_focus_handle.clone();
3469                    move |window, cx| {
3470                        if can_commit {
3471                            Tooltip::with_meta_in(
3472                                tooltip,
3473                                Some(&git::Commit),
3474                                format!(
3475                                    "git commit{}{}",
3476                                    if amend { " --amend" } else { "" },
3477                                    if signoff { " --signoff" } else { "" }
3478                                ),
3479                                &handle.clone(),
3480                                window,
3481                                cx,
3482                            )
3483                        } else {
3484                            Tooltip::simple(tooltip, cx)
3485                        }
3486                    }
3487                }),
3488                self.render_git_commit_menu(
3489                    ElementId::Name(format!("split-button-right-{}", title).into()),
3490                    Some(commit_tooltip_focus_handle),
3491                    cx,
3492                )
3493                .into_any_element(),
3494            ))
3495    }
3496
3497    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3498        h_flex()
3499            .py_1p5()
3500            .px_2()
3501            .gap_1p5()
3502            .justify_between()
3503            .border_t_1()
3504            .border_color(cx.theme().colors().border.opacity(0.8))
3505            .child(
3506                div()
3507                    .flex_grow()
3508                    .overflow_hidden()
3509                    .max_w(relative(0.85))
3510                    .child(
3511                        Label::new("This will update your most recent commit.")
3512                            .size(LabelSize::Small)
3513                            .truncate(),
3514                    ),
3515            )
3516            .child(
3517                panel_button("Cancel")
3518                    .size(ButtonSize::Default)
3519                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3520            )
3521    }
3522
3523    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3524        let active_repository = self.active_repository.as_ref()?;
3525        let branch = active_repository.read(cx).branch.as_ref()?;
3526        let commit = branch.most_recent_commit.as_ref()?.clone();
3527        let workspace = self.workspace.clone();
3528        let this = cx.entity();
3529
3530        Some(
3531            h_flex()
3532                .py_1p5()
3533                .px_2()
3534                .gap_1p5()
3535                .justify_between()
3536                .border_t_1()
3537                .border_color(cx.theme().colors().border.opacity(0.8))
3538                .child(
3539                    div()
3540                        .flex_grow()
3541                        .overflow_hidden()
3542                        .max_w(relative(0.85))
3543                        .child(
3544                            Label::new(commit.subject.clone())
3545                                .size(LabelSize::Small)
3546                                .truncate(),
3547                        )
3548                        .id("commit-msg-hover")
3549                        .on_click({
3550                            let commit = commit.clone();
3551                            let repo = active_repository.downgrade();
3552                            move |_, window, cx| {
3553                                CommitView::open(
3554                                    commit.clone(),
3555                                    repo.clone(),
3556                                    workspace.clone(),
3557                                    window,
3558                                    cx,
3559                                );
3560                            }
3561                        })
3562                        .hoverable_tooltip({
3563                            let repo = active_repository.clone();
3564                            move |window, cx| {
3565                                GitPanelMessageTooltip::new(
3566                                    this.clone(),
3567                                    commit.sha.clone(),
3568                                    repo.clone(),
3569                                    window,
3570                                    cx,
3571                                )
3572                                .into()
3573                            }
3574                        }),
3575                )
3576                .when(commit.has_parent, |this| {
3577                    let has_unstaged = self.has_unstaged_changes();
3578                    this.child(
3579                        panel_icon_button("undo", IconName::Undo)
3580                            .icon_size(IconSize::XSmall)
3581                            .icon_color(Color::Muted)
3582                            .tooltip(move |window, cx| {
3583                                Tooltip::with_meta(
3584                                    "Uncommit",
3585                                    Some(&git::Uncommit),
3586                                    if has_unstaged {
3587                                        "git reset HEAD^ --soft"
3588                                    } else {
3589                                        "git reset HEAD^"
3590                                    },
3591                                    window,
3592                                    cx,
3593                                )
3594                            })
3595                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3596                    )
3597                }),
3598        )
3599    }
3600
3601    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3602        h_flex().h_full().flex_grow().justify_center().child(
3603            v_flex()
3604                .gap_2()
3605                .child(h_flex().w_full().justify_around().child(
3606                    if self.active_repository.is_some() {
3607                        "No changes to commit"
3608                    } else {
3609                        "No Git repositories"
3610                    },
3611                ))
3612                .children({
3613                    let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3614                    (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3615                        h_flex().w_full().justify_around().child(
3616                            panel_filled_button("Initialize Repository")
3617                                .tooltip(Tooltip::for_action_title_in(
3618                                    "git init",
3619                                    &git::Init,
3620                                    &self.focus_handle,
3621                                ))
3622                                .on_click(move |_, _, cx| {
3623                                    cx.defer(move |cx| {
3624                                        cx.dispatch_action(&git::Init);
3625                                    })
3626                                }),
3627                        )
3628                    })
3629                })
3630                .text_ui_sm(cx)
3631                .mx_auto()
3632                .text_color(Color::Placeholder.color(cx)),
3633        )
3634    }
3635
3636    fn render_buffer_header_controls(
3637        &self,
3638        entity: &Entity<Self>,
3639        file: &Arc<dyn File>,
3640        _: &Window,
3641        cx: &App,
3642    ) -> Option<AnyElement> {
3643        let repo = self.active_repository.as_ref()?.read(cx);
3644        let project_path = (file.worktree_id(cx), file.path()).into();
3645        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3646        let ix = self.entry_by_path(&repo_path, cx)?;
3647        let entry = self.entries.get(ix)?;
3648
3649        let entry_staging = self.entry_staging(entry.status_entry()?);
3650
3651        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3652            .disabled(!self.has_write_access(cx))
3653            .fill()
3654            .elevation(ElevationIndex::Surface)
3655            .on_click({
3656                let entry = entry.clone();
3657                let git_panel = entity.downgrade();
3658                move |_, window, cx| {
3659                    git_panel
3660                        .update(cx, |this, cx| {
3661                            this.toggle_staged_for_entry(&entry, window, cx);
3662                            cx.stop_propagation();
3663                        })
3664                        .ok();
3665                }
3666            });
3667        Some(
3668            h_flex()
3669                .id("start-slot")
3670                .text_lg()
3671                .child(checkbox)
3672                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3673                    // prevent the list item active state triggering when toggling checkbox
3674                    cx.stop_propagation();
3675                })
3676                .into_any_element(),
3677        )
3678    }
3679
3680    fn render_entries(
3681        &self,
3682        has_write_access: bool,
3683        window: &mut Window,
3684        cx: &mut Context<Self>,
3685    ) -> impl IntoElement {
3686        let entry_count = self.entries.len();
3687
3688        v_flex()
3689            .flex_1()
3690            .size_full()
3691            .overflow_hidden()
3692            .relative()
3693            .child(
3694                h_flex()
3695                    .flex_1()
3696                    .size_full()
3697                    .relative()
3698                    .overflow_hidden()
3699                    .child(
3700                        uniform_list(
3701                            "entries",
3702                            entry_count,
3703                            cx.processor(move |this, range: Range<usize>, window, cx| {
3704                                let mut items = Vec::with_capacity(range.end - range.start);
3705
3706                                for ix in range {
3707                                    match &this.entries.get(ix) {
3708                                        Some(GitListEntry::Status(entry)) => {
3709                                            items.push(this.render_entry(
3710                                                ix,
3711                                                entry,
3712                                                has_write_access,
3713                                                window,
3714                                                cx,
3715                                            ));
3716                                        }
3717                                        Some(GitListEntry::Header(header)) => {
3718                                            items.push(this.render_list_header(
3719                                                ix,
3720                                                header,
3721                                                has_write_access,
3722                                                window,
3723                                                cx,
3724                                            ));
3725                                        }
3726                                        None => {}
3727                                    }
3728                                }
3729
3730                                items
3731                            }),
3732                        )
3733                        .size_full()
3734                        .flex_grow()
3735                        .with_sizing_behavior(ListSizingBehavior::Auto)
3736                        .with_horizontal_sizing_behavior(
3737                            ListHorizontalSizingBehavior::Unconstrained,
3738                        )
3739                        .with_width_from_item(self.max_width_item_index)
3740                        .track_scroll(self.scroll_handle.clone()),
3741                    )
3742                    .on_mouse_down(
3743                        MouseButton::Right,
3744                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3745                            this.deploy_panel_context_menu(event.position, window, cx)
3746                        }),
3747                    )
3748                    .custom_scrollbars(
3749                        Scrollbars::for_settings::<GitPanelSettings>()
3750                            .tracked_scroll_handle(self.scroll_handle.clone())
3751                            .with_track_along(
3752                                ScrollAxes::Horizontal,
3753                                cx.theme().colors().panel_background,
3754                            ),
3755                        window,
3756                        cx,
3757                    ),
3758            )
3759    }
3760
3761    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3762        Label::new(label.into()).color(color).single_line()
3763    }
3764
3765    fn list_item_height(&self) -> Rems {
3766        rems(1.75)
3767    }
3768
3769    fn render_list_header(
3770        &self,
3771        ix: usize,
3772        header: &GitHeaderEntry,
3773        _: bool,
3774        _: &Window,
3775        _: &Context<Self>,
3776    ) -> AnyElement {
3777        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3778
3779        h_flex()
3780            .id(id)
3781            .h(self.list_item_height())
3782            .w_full()
3783            .items_end()
3784            .px(rems(0.75)) // ~12px
3785            .pb(rems(0.3125)) // ~ 5px
3786            .child(
3787                Label::new(header.title())
3788                    .color(Color::Muted)
3789                    .size(LabelSize::Small)
3790                    .line_height_style(LineHeightStyle::UiLabel)
3791                    .single_line(),
3792            )
3793            .into_any_element()
3794    }
3795
3796    pub fn load_commit_details(
3797        &self,
3798        sha: String,
3799        cx: &mut Context<Self>,
3800    ) -> Task<anyhow::Result<CommitDetails>> {
3801        let Some(repo) = self.active_repository.clone() else {
3802            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3803        };
3804        repo.update(cx, |repo, cx| {
3805            let show = repo.show(sha);
3806            cx.spawn(async move |_, _| show.await?)
3807        })
3808    }
3809
3810    fn deploy_entry_context_menu(
3811        &mut self,
3812        position: Point<Pixels>,
3813        ix: usize,
3814        window: &mut Window,
3815        cx: &mut Context<Self>,
3816    ) {
3817        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3818            return;
3819        };
3820        let stage_title = if entry.status.staging().is_fully_staged() {
3821            "Unstage File"
3822        } else {
3823            "Stage File"
3824        };
3825        let restore_title = if entry.status.is_created() {
3826            "Trash File"
3827        } else {
3828            "Restore File"
3829        };
3830        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3831            context_menu
3832                .context(self.focus_handle.clone())
3833                .action(stage_title, ToggleStaged.boxed_clone())
3834                .action(restore_title, git::RestoreFile::default().boxed_clone())
3835                .separator()
3836                .action("Open Diff", Confirm.boxed_clone())
3837                .action("Open File", SecondaryConfirm.boxed_clone())
3838        });
3839        self.selected_entry = Some(ix);
3840        self.set_context_menu(context_menu, position, window, cx);
3841    }
3842
3843    fn deploy_panel_context_menu(
3844        &mut self,
3845        position: Point<Pixels>,
3846        window: &mut Window,
3847        cx: &mut Context<Self>,
3848    ) {
3849        let context_menu = git_panel_context_menu(
3850            self.focus_handle.clone(),
3851            GitMenuState {
3852                has_tracked_changes: self.has_tracked_changes(),
3853                has_staged_changes: self.has_staged_changes(),
3854                has_unstaged_changes: self.has_unstaged_changes(),
3855                has_new_changes: self.new_count > 0,
3856                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3857                has_stash_items: self.stash_entries.entries.len() > 0,
3858            },
3859            window,
3860            cx,
3861        );
3862        self.set_context_menu(context_menu, position, window, cx);
3863    }
3864
3865    fn set_context_menu(
3866        &mut self,
3867        context_menu: Entity<ContextMenu>,
3868        position: Point<Pixels>,
3869        window: &Window,
3870        cx: &mut Context<Self>,
3871    ) {
3872        let subscription = cx.subscribe_in(
3873            &context_menu,
3874            window,
3875            |this, _, _: &DismissEvent, window, cx| {
3876                if this.context_menu.as_ref().is_some_and(|context_menu| {
3877                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3878                }) {
3879                    cx.focus_self(window);
3880                }
3881                this.context_menu.take();
3882                cx.notify();
3883            },
3884        );
3885        self.context_menu = Some((context_menu, position, subscription));
3886        cx.notify();
3887    }
3888
3889    fn render_entry(
3890        &self,
3891        ix: usize,
3892        entry: &GitStatusEntry,
3893        has_write_access: bool,
3894        window: &Window,
3895        cx: &Context<Self>,
3896    ) -> AnyElement {
3897        let display_name = entry.display_name();
3898
3899        let selected = self.selected_entry == Some(ix);
3900        let marked = self.marked_entries.contains(&ix);
3901        let status_style = GitPanelSettings::get_global(cx).status_style;
3902        let status = entry.status;
3903
3904        let has_conflict = status.is_conflicted();
3905        let is_modified = status.is_modified();
3906        let is_deleted = status.is_deleted();
3907
3908        let label_color = if status_style == StatusStyle::LabelColor {
3909            if has_conflict {
3910                Color::VersionControlConflict
3911            } else if is_modified {
3912                Color::VersionControlModified
3913            } else if is_deleted {
3914                // We don't want a bunch of red labels in the list
3915                Color::Disabled
3916            } else {
3917                Color::VersionControlAdded
3918            }
3919        } else {
3920            Color::Default
3921        };
3922
3923        let path_color = if status.is_deleted() {
3924            Color::Disabled
3925        } else {
3926            Color::Muted
3927        };
3928
3929        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3930        let checkbox_wrapper_id: ElementId =
3931            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3932        let checkbox_id: ElementId =
3933            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3934
3935        let entry_staging = self.entry_staging(entry);
3936        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3937        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
3938            is_staged = ToggleState::Selected;
3939        }
3940
3941        let handle = cx.weak_entity();
3942
3943        let selected_bg_alpha = 0.08;
3944        let marked_bg_alpha = 0.12;
3945        let state_opacity_step = 0.04;
3946
3947        let base_bg = match (selected, marked) {
3948            (true, true) => cx
3949                .theme()
3950                .status()
3951                .info
3952                .alpha(selected_bg_alpha + marked_bg_alpha),
3953            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3954            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3955            _ => cx.theme().colors().ghost_element_background,
3956        };
3957
3958        let hover_bg = if selected {
3959            cx.theme()
3960                .status()
3961                .info
3962                .alpha(selected_bg_alpha + state_opacity_step)
3963        } else {
3964            cx.theme().colors().ghost_element_hover
3965        };
3966
3967        let active_bg = if selected {
3968            cx.theme()
3969                .status()
3970                .info
3971                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3972        } else {
3973            cx.theme().colors().ghost_element_active
3974        };
3975
3976        h_flex()
3977            .id(id)
3978            .h(self.list_item_height())
3979            .w_full()
3980            .items_center()
3981            .border_1()
3982            .when(selected && self.focus_handle.is_focused(window), |el| {
3983                el.border_color(cx.theme().colors().border_focused)
3984            })
3985            .px(rems(0.75)) // ~12px
3986            .overflow_hidden()
3987            .flex_none()
3988            .gap_1p5()
3989            .bg(base_bg)
3990            .hover(|this| this.bg(hover_bg))
3991            .active(|this| this.bg(active_bg))
3992            .on_click({
3993                cx.listener(move |this, event: &ClickEvent, window, cx| {
3994                    this.selected_entry = Some(ix);
3995                    cx.notify();
3996                    if event.modifiers().secondary() {
3997                        this.open_file(&Default::default(), window, cx)
3998                    } else {
3999                        this.open_diff(&Default::default(), window, cx);
4000                        this.focus_handle.focus(window);
4001                    }
4002                })
4003            })
4004            .on_mouse_down(
4005                MouseButton::Right,
4006                move |event: &MouseDownEvent, window, cx| {
4007                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4008                    if event.button != MouseButton::Right {
4009                        return;
4010                    }
4011
4012                    let Some(this) = handle.upgrade() else {
4013                        return;
4014                    };
4015                    this.update(cx, |this, cx| {
4016                        this.deploy_entry_context_menu(event.position, ix, window, cx);
4017                    });
4018                    cx.stop_propagation();
4019                },
4020            )
4021            .child(
4022                div()
4023                    .id(checkbox_wrapper_id)
4024                    .flex_none()
4025                    .occlude()
4026                    .cursor_pointer()
4027                    .child(
4028                        Checkbox::new(checkbox_id, is_staged)
4029                            .disabled(!has_write_access)
4030                            .fill()
4031                            .elevation(ElevationIndex::Surface)
4032                            .on_click_ext({
4033                                let entry = entry.clone();
4034                                let this = cx.weak_entity();
4035                                move |_, click, window, cx| {
4036                                    this.update(cx, |this, cx| {
4037                                        if !has_write_access {
4038                                            return;
4039                                        }
4040                                        if click.modifiers().shift {
4041                                            this.stage_bulk(ix, cx);
4042                                        } else {
4043                                            this.toggle_staged_for_entry(
4044                                                &GitListEntry::Status(entry.clone()),
4045                                                window,
4046                                                cx,
4047                                            );
4048                                        }
4049                                        cx.stop_propagation();
4050                                    })
4051                                    .ok();
4052                                }
4053                            })
4054                            .tooltip(move |window, cx| {
4055                                let is_staged = entry_staging.is_fully_staged();
4056
4057                                let action = if is_staged { "Unstage" } else { "Stage" };
4058                                let tooltip_name = action.to_string();
4059
4060                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4061                            }),
4062                    ),
4063            )
4064            .child(git_status_icon(status))
4065            .child(
4066                h_flex()
4067                    .items_center()
4068                    .flex_1()
4069                    // .overflow_hidden()
4070                    .when_some(entry.parent_dir(), |this, parent| {
4071                        if !parent.is_empty() {
4072                            this.child(
4073                                self.entry_label(format!("{}/", parent), path_color)
4074                                    .when(status.is_deleted(), |this| this.strikethrough()),
4075                            )
4076                        } else {
4077                            this
4078                        }
4079                    })
4080                    .child(
4081                        self.entry_label(display_name, label_color)
4082                            .when(status.is_deleted(), |this| this.strikethrough()),
4083                    ),
4084            )
4085            .into_any_element()
4086    }
4087
4088    fn has_write_access(&self, cx: &App) -> bool {
4089        !self.project.read(cx).is_read_only(cx)
4090    }
4091
4092    pub fn amend_pending(&self) -> bool {
4093        self.amend_pending
4094    }
4095
4096    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4097        if value && !self.amend_pending {
4098            let current_message = self.commit_message_buffer(cx).read(cx).text();
4099            self.original_commit_message = if current_message.trim().is_empty() {
4100                None
4101            } else {
4102                Some(current_message)
4103            };
4104        } else if !value && self.amend_pending {
4105            let message = self.original_commit_message.take().unwrap_or_default();
4106            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4107                let start = buffer.anchor_before(0);
4108                let end = buffer.anchor_after(buffer.len());
4109                buffer.edit([(start..end, message)], None, cx);
4110            });
4111        }
4112
4113        self.amend_pending = value;
4114        self.serialize(cx);
4115        cx.notify();
4116    }
4117
4118    pub fn signoff_enabled(&self) -> bool {
4119        self.signoff_enabled
4120    }
4121
4122    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4123        self.signoff_enabled = value;
4124        self.serialize(cx);
4125        cx.notify();
4126    }
4127
4128    pub fn toggle_signoff_enabled(
4129        &mut self,
4130        _: &Signoff,
4131        _window: &mut Window,
4132        cx: &mut Context<Self>,
4133    ) {
4134        self.set_signoff_enabled(!self.signoff_enabled, cx);
4135    }
4136
4137    pub async fn load(
4138        workspace: WeakEntity<Workspace>,
4139        mut cx: AsyncWindowContext,
4140    ) -> anyhow::Result<Entity<Self>> {
4141        let serialized_panel = match workspace
4142            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4143            .ok()
4144            .flatten()
4145        {
4146            Some(serialization_key) => cx
4147                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4148                .await
4149                .context("loading git panel")
4150                .log_err()
4151                .flatten()
4152                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4153                .transpose()
4154                .log_err()
4155                .flatten(),
4156            None => None,
4157        };
4158
4159        workspace.update_in(&mut cx, |workspace, window, cx| {
4160            let panel = GitPanel::new(workspace, window, cx);
4161
4162            if let Some(serialized_panel) = serialized_panel {
4163                panel.update(cx, |panel, cx| {
4164                    panel.width = serialized_panel.width;
4165                    panel.amend_pending = serialized_panel.amend_pending;
4166                    panel.signoff_enabled = serialized_panel.signoff_enabled;
4167                    cx.notify();
4168                })
4169            }
4170
4171            panel
4172        })
4173    }
4174
4175    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4176        let Some(op) = self.bulk_staging.as_ref() else {
4177            return;
4178        };
4179        let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4180            return;
4181        };
4182        if let Some(entry) = self.entries.get(index)
4183            && let Some(entry) = entry.status_entry()
4184        {
4185            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4186        }
4187        if index < anchor_index {
4188            std::mem::swap(&mut index, &mut anchor_index);
4189        }
4190        let entries = self
4191            .entries
4192            .get(anchor_index..=index)
4193            .unwrap_or_default()
4194            .iter()
4195            .filter_map(|entry| entry.status_entry().cloned())
4196            .collect::<Vec<_>>();
4197        self.change_file_stage(true, entries, cx);
4198    }
4199
4200    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4201        let Some(repo) = self.active_repository.as_ref() else {
4202            return;
4203        };
4204        self.bulk_staging = Some(BulkStaging {
4205            repo_id: repo.read(cx).id,
4206            anchor: path,
4207        });
4208    }
4209
4210    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4211        self.set_amend_pending(!self.amend_pending, cx);
4212        if self.amend_pending {
4213            self.load_last_commit_message_if_empty(cx);
4214        }
4215    }
4216}
4217
4218impl Render for GitPanel {
4219    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4220        let project = self.project.read(cx);
4221        let has_entries = !self.entries.is_empty();
4222        let room = self
4223            .workspace
4224            .upgrade()
4225            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4226
4227        let has_write_access = self.has_write_access(cx);
4228
4229        let has_co_authors = room.is_some_and(|room| {
4230            self.load_local_committer(cx);
4231            let room = room.read(cx);
4232            room.remote_participants()
4233                .values()
4234                .any(|remote_participant| remote_participant.can_write())
4235        });
4236
4237        v_flex()
4238            .id("git_panel")
4239            .key_context(self.dispatch_context(window, cx))
4240            .track_focus(&self.focus_handle)
4241            .when(has_write_access && !project.is_read_only(cx), |this| {
4242                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4243                    .on_action(cx.listener(Self::stage_range))
4244                    .on_action(cx.listener(GitPanel::commit))
4245                    .on_action(cx.listener(GitPanel::amend))
4246                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4247                    .on_action(cx.listener(Self::stage_all))
4248                    .on_action(cx.listener(Self::unstage_all))
4249                    .on_action(cx.listener(Self::stage_selected))
4250                    .on_action(cx.listener(Self::unstage_selected))
4251                    .on_action(cx.listener(Self::restore_tracked_files))
4252                    .on_action(cx.listener(Self::revert_selected))
4253                    .on_action(cx.listener(Self::clean_all))
4254                    .on_action(cx.listener(Self::generate_commit_message_action))
4255                    .on_action(cx.listener(Self::stash_all))
4256                    .on_action(cx.listener(Self::stash_pop))
4257            })
4258            .on_action(cx.listener(Self::select_first))
4259            .on_action(cx.listener(Self::select_next))
4260            .on_action(cx.listener(Self::select_previous))
4261            .on_action(cx.listener(Self::select_last))
4262            .on_action(cx.listener(Self::close_panel))
4263            .on_action(cx.listener(Self::open_diff))
4264            .on_action(cx.listener(Self::open_file))
4265            .on_action(cx.listener(Self::focus_changes_list))
4266            .on_action(cx.listener(Self::focus_editor))
4267            .on_action(cx.listener(Self::expand_commit_editor))
4268            .when(has_write_access && has_co_authors, |git_panel| {
4269                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4270            })
4271            .on_action(cx.listener(Self::toggle_sort_by_path))
4272            .size_full()
4273            .overflow_hidden()
4274            .bg(cx.theme().colors().panel_background)
4275            .child(
4276                v_flex()
4277                    .size_full()
4278                    .children(self.render_panel_header(window, cx))
4279                    .map(|this| {
4280                        if has_entries {
4281                            this.child(self.render_entries(has_write_access, window, cx))
4282                        } else {
4283                            this.child(self.render_empty_state(cx).into_any_element())
4284                        }
4285                    })
4286                    .children(self.render_footer(window, cx))
4287                    .when(self.amend_pending, |this| {
4288                        this.child(self.render_pending_amend(cx))
4289                    })
4290                    .when(!self.amend_pending, |this| {
4291                        this.children(self.render_previous_commit(cx))
4292                    })
4293                    .into_any_element(),
4294            )
4295            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4296                deferred(
4297                    anchored()
4298                        .position(*position)
4299                        .anchor(Corner::TopLeft)
4300                        .child(menu.clone()),
4301                )
4302                .with_priority(1)
4303            }))
4304    }
4305}
4306
4307impl Focusable for GitPanel {
4308    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4309        if self.entries.is_empty() {
4310            self.commit_editor.focus_handle(cx)
4311        } else {
4312            self.focus_handle.clone()
4313        }
4314    }
4315}
4316
4317impl EventEmitter<Event> for GitPanel {}
4318
4319impl EventEmitter<PanelEvent> for GitPanel {}
4320
4321pub(crate) struct GitPanelAddon {
4322    pub(crate) workspace: WeakEntity<Workspace>,
4323}
4324
4325impl editor::Addon for GitPanelAddon {
4326    fn to_any(&self) -> &dyn std::any::Any {
4327        self
4328    }
4329
4330    fn render_buffer_header_controls(
4331        &self,
4332        excerpt_info: &ExcerptInfo,
4333        window: &Window,
4334        cx: &App,
4335    ) -> Option<AnyElement> {
4336        let file = excerpt_info.buffer.file()?;
4337        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4338
4339        git_panel
4340            .read(cx)
4341            .render_buffer_header_controls(&git_panel, file, window, cx)
4342    }
4343}
4344
4345impl Panel for GitPanel {
4346    fn persistent_name() -> &'static str {
4347        "GitPanel"
4348    }
4349
4350    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4351        GitPanelSettings::get_global(cx).dock
4352    }
4353
4354    fn position_is_valid(&self, position: DockPosition) -> bool {
4355        matches!(position, DockPosition::Left | DockPosition::Right)
4356    }
4357
4358    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4359        settings::update_settings_file::<GitPanelSettings>(
4360            self.fs.clone(),
4361            cx,
4362            move |settings, _| settings.dock = Some(position),
4363        );
4364    }
4365
4366    fn size(&self, _: &Window, cx: &App) -> Pixels {
4367        self.width
4368            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4369    }
4370
4371    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4372        self.width = size;
4373        self.serialize(cx);
4374        cx.notify();
4375    }
4376
4377    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4378        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4379    }
4380
4381    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4382        Some("Git Panel")
4383    }
4384
4385    fn toggle_action(&self) -> Box<dyn Action> {
4386        Box::new(ToggleFocus)
4387    }
4388
4389    fn activation_priority(&self) -> u32 {
4390        2
4391    }
4392}
4393
4394impl PanelHeader for GitPanel {}
4395
4396struct GitPanelMessageTooltip {
4397    commit_tooltip: Option<Entity<CommitTooltip>>,
4398}
4399
4400impl GitPanelMessageTooltip {
4401    fn new(
4402        git_panel: Entity<GitPanel>,
4403        sha: SharedString,
4404        repository: Entity<Repository>,
4405        window: &mut Window,
4406        cx: &mut App,
4407    ) -> Entity<Self> {
4408        cx.new(|cx| {
4409            cx.spawn_in(window, async move |this, cx| {
4410                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4411                    (
4412                        git_panel.load_commit_details(sha.to_string(), cx),
4413                        git_panel.workspace.clone(),
4414                    )
4415                })?;
4416                let details = details.await?;
4417
4418                let commit_details = crate::commit_tooltip::CommitDetails {
4419                    sha: details.sha.clone(),
4420                    author_name: details.author_name.clone(),
4421                    author_email: details.author_email.clone(),
4422                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4423                    message: Some(ParsedCommitMessage {
4424                        message: details.message,
4425                        ..Default::default()
4426                    }),
4427                };
4428
4429                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4430                    this.commit_tooltip = Some(cx.new(move |cx| {
4431                        CommitTooltip::new(commit_details, repository, workspace, cx)
4432                    }));
4433                    cx.notify();
4434                })
4435            })
4436            .detach();
4437
4438            Self {
4439                commit_tooltip: None,
4440            }
4441        })
4442    }
4443}
4444
4445impl Render for GitPanelMessageTooltip {
4446    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4447        if let Some(commit_tooltip) = &self.commit_tooltip {
4448            commit_tooltip.clone().into_any_element()
4449        } else {
4450            gpui::Empty.into_any_element()
4451        }
4452    }
4453}
4454
4455#[derive(IntoElement, RegisterComponent)]
4456pub struct PanelRepoFooter {
4457    active_repository: SharedString,
4458    branch: Option<Branch>,
4459    head_commit: Option<CommitDetails>,
4460
4461    // Getting a GitPanel in previews will be difficult.
4462    //
4463    // For now just take an option here, and we won't bind handlers to buttons in previews.
4464    git_panel: Option<Entity<GitPanel>>,
4465}
4466
4467impl PanelRepoFooter {
4468    pub fn new(
4469        active_repository: SharedString,
4470        branch: Option<Branch>,
4471        head_commit: Option<CommitDetails>,
4472        git_panel: Option<Entity<GitPanel>>,
4473    ) -> Self {
4474        Self {
4475            active_repository,
4476            branch,
4477            head_commit,
4478            git_panel,
4479        }
4480    }
4481
4482    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4483        Self {
4484            active_repository,
4485            branch,
4486            head_commit: None,
4487            git_panel: None,
4488        }
4489    }
4490}
4491
4492impl RenderOnce for PanelRepoFooter {
4493    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4494        let project = self
4495            .git_panel
4496            .as_ref()
4497            .map(|panel| panel.read(cx).project.clone());
4498
4499        let repo = self
4500            .git_panel
4501            .as_ref()
4502            .and_then(|panel| panel.read(cx).active_repository.clone());
4503
4504        let single_repo = project
4505            .as_ref()
4506            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4507            .unwrap_or(true);
4508
4509        const MAX_BRANCH_LEN: usize = 16;
4510        const MAX_REPO_LEN: usize = 16;
4511        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4512        const MAX_SHORT_SHA_LEN: usize = 8;
4513
4514        let branch_name = self
4515            .branch
4516            .as_ref()
4517            .map(|branch| branch.name().to_owned())
4518            .or_else(|| {
4519                self.head_commit.as_ref().map(|commit| {
4520                    commit
4521                        .sha
4522                        .chars()
4523                        .take(MAX_SHORT_SHA_LEN)
4524                        .collect::<String>()
4525                })
4526            })
4527            .unwrap_or_else(|| " (no branch)".to_owned());
4528        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4529
4530        let active_repo_name = self.active_repository.clone();
4531
4532        let branch_actual_len = branch_name.len();
4533        let repo_actual_len = active_repo_name.len();
4534
4535        // ideally, show the whole branch and repo names but
4536        // when we can't, use a budget to allocate space between the two
4537        let (repo_display_len, branch_display_len) =
4538            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4539                (repo_actual_len, branch_actual_len)
4540            } else if branch_actual_len <= MAX_BRANCH_LEN {
4541                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4542                (repo_space, branch_actual_len)
4543            } else if repo_actual_len <= MAX_REPO_LEN {
4544                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4545                (repo_actual_len, branch_space)
4546            } else {
4547                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4548            };
4549
4550        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4551            active_repo_name.to_string()
4552        } else {
4553            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4554        };
4555
4556        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4557            branch_name
4558        } else {
4559            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4560        };
4561
4562        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4563            .style(ButtonStyle::Transparent)
4564            .size(ButtonSize::None)
4565            .label_size(LabelSize::Small)
4566            .color(Color::Muted);
4567
4568        let repo_selector = PopoverMenu::new("repository-switcher")
4569            .menu({
4570                let project = project;
4571                move |window, cx| {
4572                    let project = project.clone()?;
4573                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4574                }
4575            })
4576            .trigger_with_tooltip(
4577                repo_selector_trigger.disabled(single_repo).truncate(true),
4578                Tooltip::text("Switch Active Repository"),
4579            )
4580            .anchor(Corner::BottomLeft)
4581            .into_any_element();
4582
4583        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4584            .style(ButtonStyle::Transparent)
4585            .size(ButtonSize::None)
4586            .label_size(LabelSize::Small)
4587            .truncate(true)
4588            .tooltip(Tooltip::for_action_title(
4589                "Switch Branch",
4590                &zed_actions::git::Switch,
4591            ))
4592            .on_click(|_, window, cx| {
4593                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4594            });
4595
4596        let branch_selector = PopoverMenu::new("popover-button")
4597            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4598            .trigger_with_tooltip(
4599                branch_selector_button,
4600                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4601            )
4602            .anchor(Corner::BottomLeft)
4603            .offset(gpui::Point {
4604                x: px(0.0),
4605                y: px(-2.0),
4606            });
4607
4608        h_flex()
4609            .w_full()
4610            .px_2()
4611            .h(px(36.))
4612            .items_center()
4613            .justify_between()
4614            .gap_1()
4615            .child(
4616                h_flex()
4617                    .flex_1()
4618                    .overflow_hidden()
4619                    .items_center()
4620                    .child(
4621                        div().child(
4622                            Icon::new(IconName::GitBranchAlt)
4623                                .size(IconSize::Small)
4624                                .color(if single_repo {
4625                                    Color::Disabled
4626                                } else {
4627                                    Color::Muted
4628                                }),
4629                        ),
4630                    )
4631                    .child(repo_selector)
4632                    .when(show_separator, |this| {
4633                        this.child(
4634                            div()
4635                                .text_color(cx.theme().colors().text_muted)
4636                                .text_sm()
4637                                .child("/"),
4638                        )
4639                    })
4640                    .child(branch_selector),
4641            )
4642            .children(if let Some(git_panel) = self.git_panel {
4643                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4644            } else {
4645                None
4646            })
4647    }
4648}
4649
4650impl Component for PanelRepoFooter {
4651    fn scope() -> ComponentScope {
4652        ComponentScope::VersionControl
4653    }
4654
4655    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4656        let unknown_upstream = None;
4657        let no_remote_upstream = Some(UpstreamTracking::Gone);
4658        let ahead_of_upstream = Some(
4659            UpstreamTrackingStatus {
4660                ahead: 2,
4661                behind: 0,
4662            }
4663            .into(),
4664        );
4665        let behind_upstream = Some(
4666            UpstreamTrackingStatus {
4667                ahead: 0,
4668                behind: 2,
4669            }
4670            .into(),
4671        );
4672        let ahead_and_behind_upstream = Some(
4673            UpstreamTrackingStatus {
4674                ahead: 3,
4675                behind: 1,
4676            }
4677            .into(),
4678        );
4679
4680        let not_ahead_or_behind_upstream = Some(
4681            UpstreamTrackingStatus {
4682                ahead: 0,
4683                behind: 0,
4684            }
4685            .into(),
4686        );
4687
4688        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4689            Branch {
4690                is_head: true,
4691                ref_name: "some-branch".into(),
4692                upstream: upstream.map(|tracking| Upstream {
4693                    ref_name: "origin/some-branch".into(),
4694                    tracking,
4695                }),
4696                most_recent_commit: Some(CommitSummary {
4697                    sha: "abc123".into(),
4698                    subject: "Modify stuff".into(),
4699                    commit_timestamp: 1710932954,
4700                    author_name: "John Doe".into(),
4701                    has_parent: true,
4702                }),
4703            }
4704        }
4705
4706        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4707            Branch {
4708                is_head: true,
4709                ref_name: branch_name.to_string().into(),
4710                upstream: upstream.map(|tracking| Upstream {
4711                    ref_name: format!("zed/{}", branch_name).into(),
4712                    tracking,
4713                }),
4714                most_recent_commit: Some(CommitSummary {
4715                    sha: "abc123".into(),
4716                    subject: "Modify stuff".into(),
4717                    commit_timestamp: 1710932954,
4718                    author_name: "John Doe".into(),
4719                    has_parent: true,
4720                }),
4721            }
4722        }
4723
4724        fn active_repository(id: usize) -> SharedString {
4725            format!("repo-{}", id).into()
4726        }
4727
4728        let example_width = px(340.);
4729        Some(
4730            v_flex()
4731                .gap_6()
4732                .w_full()
4733                .flex_none()
4734                .children(vec![
4735                    example_group_with_title(
4736                        "Action Button States",
4737                        vec![
4738                            single_example(
4739                                "No Branch",
4740                                div()
4741                                    .w(example_width)
4742                                    .overflow_hidden()
4743                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
4744                                    .into_any_element(),
4745                            ),
4746                            single_example(
4747                                "Remote status unknown",
4748                                div()
4749                                    .w(example_width)
4750                                    .overflow_hidden()
4751                                    .child(PanelRepoFooter::new_preview(
4752                                        active_repository(2),
4753                                        Some(branch(unknown_upstream)),
4754                                    ))
4755                                    .into_any_element(),
4756                            ),
4757                            single_example(
4758                                "No Remote Upstream",
4759                                div()
4760                                    .w(example_width)
4761                                    .overflow_hidden()
4762                                    .child(PanelRepoFooter::new_preview(
4763                                        active_repository(3),
4764                                        Some(branch(no_remote_upstream)),
4765                                    ))
4766                                    .into_any_element(),
4767                            ),
4768                            single_example(
4769                                "Not Ahead or Behind",
4770                                div()
4771                                    .w(example_width)
4772                                    .overflow_hidden()
4773                                    .child(PanelRepoFooter::new_preview(
4774                                        active_repository(4),
4775                                        Some(branch(not_ahead_or_behind_upstream)),
4776                                    ))
4777                                    .into_any_element(),
4778                            ),
4779                            single_example(
4780                                "Behind remote",
4781                                div()
4782                                    .w(example_width)
4783                                    .overflow_hidden()
4784                                    .child(PanelRepoFooter::new_preview(
4785                                        active_repository(5),
4786                                        Some(branch(behind_upstream)),
4787                                    ))
4788                                    .into_any_element(),
4789                            ),
4790                            single_example(
4791                                "Ahead of remote",
4792                                div()
4793                                    .w(example_width)
4794                                    .overflow_hidden()
4795                                    .child(PanelRepoFooter::new_preview(
4796                                        active_repository(6),
4797                                        Some(branch(ahead_of_upstream)),
4798                                    ))
4799                                    .into_any_element(),
4800                            ),
4801                            single_example(
4802                                "Ahead and behind remote",
4803                                div()
4804                                    .w(example_width)
4805                                    .overflow_hidden()
4806                                    .child(PanelRepoFooter::new_preview(
4807                                        active_repository(7),
4808                                        Some(branch(ahead_and_behind_upstream)),
4809                                    ))
4810                                    .into_any_element(),
4811                            ),
4812                        ],
4813                    )
4814                    .grow()
4815                    .vertical(),
4816                ])
4817                .children(vec![
4818                    example_group_with_title(
4819                        "Labels",
4820                        vec![
4821                            single_example(
4822                                "Short Branch & Repo",
4823                                div()
4824                                    .w(example_width)
4825                                    .overflow_hidden()
4826                                    .child(PanelRepoFooter::new_preview(
4827                                        SharedString::from("zed"),
4828                                        Some(custom("main", behind_upstream)),
4829                                    ))
4830                                    .into_any_element(),
4831                            ),
4832                            single_example(
4833                                "Long Branch",
4834                                div()
4835                                    .w(example_width)
4836                                    .overflow_hidden()
4837                                    .child(PanelRepoFooter::new_preview(
4838                                        SharedString::from("zed"),
4839                                        Some(custom(
4840                                            "redesign-and-update-git-ui-list-entry-style",
4841                                            behind_upstream,
4842                                        )),
4843                                    ))
4844                                    .into_any_element(),
4845                            ),
4846                            single_example(
4847                                "Long Repo",
4848                                div()
4849                                    .w(example_width)
4850                                    .overflow_hidden()
4851                                    .child(PanelRepoFooter::new_preview(
4852                                        SharedString::from("zed-industries-community-examples"),
4853                                        Some(custom("gpui", ahead_of_upstream)),
4854                                    ))
4855                                    .into_any_element(),
4856                            ),
4857                            single_example(
4858                                "Long Repo & Branch",
4859                                div()
4860                                    .w(example_width)
4861                                    .overflow_hidden()
4862                                    .child(PanelRepoFooter::new_preview(
4863                                        SharedString::from("zed-industries-community-examples"),
4864                                        Some(custom(
4865                                            "redesign-and-update-git-ui-list-entry-style",
4866                                            behind_upstream,
4867                                        )),
4868                                    ))
4869                                    .into_any_element(),
4870                            ),
4871                            single_example(
4872                                "Uppercase Repo",
4873                                div()
4874                                    .w(example_width)
4875                                    .overflow_hidden()
4876                                    .child(PanelRepoFooter::new_preview(
4877                                        SharedString::from("LICENSES"),
4878                                        Some(custom("main", ahead_of_upstream)),
4879                                    ))
4880                                    .into_any_element(),
4881                            ),
4882                            single_example(
4883                                "Uppercase Branch",
4884                                div()
4885                                    .w(example_width)
4886                                    .overflow_hidden()
4887                                    .child(PanelRepoFooter::new_preview(
4888                                        SharedString::from("zed"),
4889                                        Some(custom("update-README", behind_upstream)),
4890                                    ))
4891                                    .into_any_element(),
4892                            ),
4893                        ],
4894                    )
4895                    .grow()
4896                    .vertical(),
4897                ])
4898                .into_any_element(),
4899        )
4900    }
4901}
4902
4903#[cfg(test)]
4904mod tests {
4905    use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
4906    use gpui::{TestAppContext, VisualTestContext};
4907    use project::{FakeFs, WorktreeSettings};
4908    use serde_json::json;
4909    use settings::SettingsStore;
4910    use theme::LoadThemes;
4911    use util::path;
4912
4913    use super::*;
4914
4915    fn init_test(cx: &mut gpui::TestAppContext) {
4916        zlog::init_test();
4917
4918        cx.update(|cx| {
4919            let settings_store = SettingsStore::test(cx);
4920            cx.set_global(settings_store);
4921            AgentSettings::register(cx);
4922            WorktreeSettings::register(cx);
4923            workspace::init_settings(cx);
4924            theme::init(LoadThemes::JustBase, cx);
4925            language::init(cx);
4926            editor::init(cx);
4927            Project::init_settings(cx);
4928            crate::init(cx);
4929        });
4930    }
4931
4932    #[gpui::test]
4933    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4934        init_test(cx);
4935        let fs = FakeFs::new(cx.background_executor.clone());
4936        fs.insert_tree(
4937            "/root",
4938            json!({
4939                "zed": {
4940                    ".git": {},
4941                    "crates": {
4942                        "gpui": {
4943                            "gpui.rs": "fn main() {}"
4944                        },
4945                        "util": {
4946                            "util.rs": "fn do_it() {}"
4947                        }
4948                    }
4949                },
4950            }),
4951        )
4952        .await;
4953
4954        fs.set_status_for_repo(
4955            Path::new(path!("/root/zed/.git")),
4956            &[
4957                (
4958                    Path::new("crates/gpui/gpui.rs"),
4959                    StatusCode::Modified.worktree(),
4960                ),
4961                (
4962                    Path::new("crates/util/util.rs"),
4963                    StatusCode::Modified.worktree(),
4964                ),
4965            ],
4966        );
4967
4968        let project =
4969            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4970        let workspace =
4971            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4972        let cx = &mut VisualTestContext::from_window(*workspace, cx);
4973
4974        cx.read(|cx| {
4975            project
4976                .read(cx)
4977                .worktrees(cx)
4978                .next()
4979                .unwrap()
4980                .read(cx)
4981                .as_local()
4982                .unwrap()
4983                .scan_complete()
4984        })
4985        .await;
4986
4987        cx.executor().run_until_parked();
4988
4989        let panel = workspace.update(cx, GitPanel::new).unwrap();
4990
4991        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4992            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4993        });
4994        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4995        handle.await;
4996
4997        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
4998        pretty_assertions::assert_eq!(
4999            entries,
5000            [
5001                GitListEntry::Header(GitHeaderEntry {
5002                    header: Section::Tracked
5003                }),
5004                GitListEntry::Status(GitStatusEntry {
5005                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5006                    repo_path: "crates/gpui/gpui.rs".into(),
5007                    status: StatusCode::Modified.worktree(),
5008                    staging: StageStatus::Unstaged,
5009                }),
5010                GitListEntry::Status(GitStatusEntry {
5011                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5012                    repo_path: "crates/util/util.rs".into(),
5013                    status: StatusCode::Modified.worktree(),
5014                    staging: StageStatus::Unstaged,
5015                },),
5016            ],
5017        );
5018
5019        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5020            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5021        });
5022        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5023        handle.await;
5024        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5025        pretty_assertions::assert_eq!(
5026            entries,
5027            [
5028                GitListEntry::Header(GitHeaderEntry {
5029                    header: Section::Tracked
5030                }),
5031                GitListEntry::Status(GitStatusEntry {
5032                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5033                    repo_path: "crates/gpui/gpui.rs".into(),
5034                    status: StatusCode::Modified.worktree(),
5035                    staging: StageStatus::Unstaged,
5036                }),
5037                GitListEntry::Status(GitStatusEntry {
5038                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5039                    repo_path: "crates/util/util.rs".into(),
5040                    status: StatusCode::Modified.worktree(),
5041                    staging: StageStatus::Unstaged,
5042                },),
5043            ],
5044        );
5045    }
5046
5047    #[gpui::test]
5048    async fn test_bulk_staging(cx: &mut TestAppContext) {
5049        use GitListEntry::*;
5050
5051        init_test(cx);
5052        let fs = FakeFs::new(cx.background_executor.clone());
5053        fs.insert_tree(
5054            "/root",
5055            json!({
5056                "project": {
5057                    ".git": {},
5058                    "src": {
5059                        "main.rs": "fn main() {}",
5060                        "lib.rs": "pub fn hello() {}",
5061                        "utils.rs": "pub fn util() {}"
5062                    },
5063                    "tests": {
5064                        "test.rs": "fn test() {}"
5065                    },
5066                    "new_file.txt": "new content",
5067                    "another_new.rs": "// new file",
5068                    "conflict.txt": "conflicted content"
5069                }
5070            }),
5071        )
5072        .await;
5073
5074        fs.set_status_for_repo(
5075            Path::new(path!("/root/project/.git")),
5076            &[
5077                (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5078                (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5079                (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5080                (Path::new("new_file.txt"), FileStatus::Untracked),
5081                (Path::new("another_new.rs"), FileStatus::Untracked),
5082                (Path::new("src/utils.rs"), FileStatus::Untracked),
5083                (
5084                    Path::new("conflict.txt"),
5085                    UnmergedStatus {
5086                        first_head: UnmergedStatusCode::Updated,
5087                        second_head: UnmergedStatusCode::Updated,
5088                    }
5089                    .into(),
5090                ),
5091            ],
5092        );
5093
5094        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5095        let workspace =
5096            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5097        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5098
5099        cx.read(|cx| {
5100            project
5101                .read(cx)
5102                .worktrees(cx)
5103                .next()
5104                .unwrap()
5105                .read(cx)
5106                .as_local()
5107                .unwrap()
5108                .scan_complete()
5109        })
5110        .await;
5111
5112        cx.executor().run_until_parked();
5113
5114        let panel = workspace.update(cx, GitPanel::new).unwrap();
5115
5116        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5117            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5118        });
5119        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5120        handle.await;
5121
5122        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5123        #[rustfmt::skip]
5124        pretty_assertions::assert_matches!(
5125            entries.as_slice(),
5126            &[
5127                Header(GitHeaderEntry { header: Section::Conflict }),
5128                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5129                Header(GitHeaderEntry { header: Section::Tracked }),
5130                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5131                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5132                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5133                Header(GitHeaderEntry { header: Section::New }),
5134                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5135                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5136                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5137            ],
5138        );
5139
5140        let second_status_entry = entries[3].clone();
5141        panel.update_in(cx, |panel, window, cx| {
5142            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5143        });
5144
5145        panel.update_in(cx, |panel, window, cx| {
5146            panel.selected_entry = Some(7);
5147            panel.stage_range(&git::StageRange, window, cx);
5148        });
5149
5150        cx.read(|cx| {
5151            project
5152                .read(cx)
5153                .worktrees(cx)
5154                .next()
5155                .unwrap()
5156                .read(cx)
5157                .as_local()
5158                .unwrap()
5159                .scan_complete()
5160        })
5161        .await;
5162
5163        cx.executor().run_until_parked();
5164
5165        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5166            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5167        });
5168        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5169        handle.await;
5170
5171        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5172        #[rustfmt::skip]
5173        pretty_assertions::assert_matches!(
5174            entries.as_slice(),
5175            &[
5176                Header(GitHeaderEntry { header: Section::Conflict }),
5177                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5178                Header(GitHeaderEntry { header: Section::Tracked }),
5179                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5180                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5181                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5182                Header(GitHeaderEntry { header: Section::New }),
5183                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5184                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5185                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5186            ],
5187        );
5188
5189        let third_status_entry = entries[4].clone();
5190        panel.update_in(cx, |panel, window, cx| {
5191            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5192        });
5193
5194        panel.update_in(cx, |panel, window, cx| {
5195            panel.selected_entry = Some(9);
5196            panel.stage_range(&git::StageRange, window, cx);
5197        });
5198
5199        cx.read(|cx| {
5200            project
5201                .read(cx)
5202                .worktrees(cx)
5203                .next()
5204                .unwrap()
5205                .read(cx)
5206                .as_local()
5207                .unwrap()
5208                .scan_complete()
5209        })
5210        .await;
5211
5212        cx.executor().run_until_parked();
5213
5214        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5215            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5216        });
5217        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5218        handle.await;
5219
5220        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5221        #[rustfmt::skip]
5222        pretty_assertions::assert_matches!(
5223            entries.as_slice(),
5224            &[
5225                Header(GitHeaderEntry { header: Section::Conflict }),
5226                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5227                Header(GitHeaderEntry { header: Section::Tracked }),
5228                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5229                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5230                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5231                Header(GitHeaderEntry { header: Section::New }),
5232                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5233                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5234                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5235            ],
5236        );
5237    }
5238
5239    #[gpui::test]
5240    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5241        init_test(cx);
5242        let fs = FakeFs::new(cx.background_executor.clone());
5243        fs.insert_tree(
5244            "/root",
5245            json!({
5246                "project": {
5247                    ".git": {},
5248                    "src": {
5249                        "main.rs": "fn main() {}"
5250                    }
5251                }
5252            }),
5253        )
5254        .await;
5255
5256        fs.set_status_for_repo(
5257            Path::new(path!("/root/project/.git")),
5258            &[(Path::new("src/main.rs"), StatusCode::Modified.worktree())],
5259        );
5260
5261        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5262        let workspace =
5263            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5264        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5265
5266        let panel = workspace.update(cx, GitPanel::new).unwrap();
5267
5268        // Test: User has commit message, enables amend (saves message), then disables (restores message)
5269        panel.update(cx, |panel, cx| {
5270            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5271                let start = buffer.anchor_before(0);
5272                let end = buffer.anchor_after(buffer.len());
5273                buffer.edit([(start..end, "Initial commit message")], None, cx);
5274            });
5275
5276            panel.set_amend_pending(true, cx);
5277            assert!(panel.original_commit_message.is_some());
5278
5279            panel.set_amend_pending(false, cx);
5280            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5281            assert_eq!(current_message, "Initial commit message");
5282            assert!(panel.original_commit_message.is_none());
5283        });
5284
5285        // Test: User has empty commit message, enables amend, then disables (clears message)
5286        panel.update(cx, |panel, cx| {
5287            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5288                let start = buffer.anchor_before(0);
5289                let end = buffer.anchor_after(buffer.len());
5290                buffer.edit([(start..end, "")], None, cx);
5291            });
5292
5293            panel.set_amend_pending(true, cx);
5294            assert!(panel.original_commit_message.is_none());
5295
5296            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5297                let start = buffer.anchor_before(0);
5298                let end = buffer.anchor_after(buffer.len());
5299                buffer.edit([(start..end, "Previous commit message")], None, cx);
5300            });
5301
5302            panel.set_amend_pending(false, cx);
5303            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5304            assert_eq!(current_message, "");
5305        });
5306    }
5307}