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.commit_changes(
1434                        CommitOptions {
1435                            amend: true,
1436                            signoff: self.signoff_enabled,
1437                        },
1438                        window,
1439                        cx,
1440                    );
1441                }
1442            }
1443        } else {
1444            cx.propagate();
1445        }
1446    }
1447
1448    pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
1449        self.active_repository
1450            .as_ref()
1451            .and_then(|repo| repo.read(cx).head_commit.as_ref())
1452            .cloned()
1453    }
1454
1455    pub fn load_last_commit_message_if_empty(&mut self, cx: &mut Context<Self>) {
1456        if !self.commit_editor.read(cx).is_empty(cx) {
1457            return;
1458        }
1459        let Some(head_commit) = self.head_commit(cx) else {
1460            return;
1461        };
1462        let recent_sha = head_commit.sha.to_string();
1463        let detail_task = self.load_commit_details(recent_sha, cx);
1464        cx.spawn(async move |this, cx| {
1465            if let Ok(message) = detail_task.await.map(|detail| detail.message) {
1466                this.update(cx, |this, cx| {
1467                    this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1468                        let start = buffer.anchor_before(0);
1469                        let end = buffer.anchor_after(buffer.len());
1470                        buffer.edit([(start..end, message)], None, cx);
1471                    });
1472                })
1473                .log_err();
1474            }
1475        })
1476        .detach();
1477    }
1478
1479    fn custom_or_suggested_commit_message(
1480        &self,
1481        window: &mut Window,
1482        cx: &mut Context<Self>,
1483    ) -> Option<String> {
1484        let git_commit_language = self.commit_editor.read(cx).language_at(0, cx);
1485        let message = self.commit_editor.read(cx).text(cx);
1486        if message.is_empty() {
1487            return self
1488                .suggest_commit_message(cx)
1489                .filter(|message| !message.trim().is_empty());
1490        } else if message.trim().is_empty() {
1491            return None;
1492        }
1493        let buffer = cx.new(|cx| {
1494            let mut buffer = Buffer::local(message, cx);
1495            buffer.set_language(git_commit_language, cx);
1496            buffer
1497        });
1498        let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
1499        let wrapped_message = editor.update(cx, |editor, cx| {
1500            editor.select_all(&Default::default(), window, cx);
1501            editor.rewrap(&Default::default(), window, cx);
1502            editor.text(cx)
1503        });
1504        if wrapped_message.trim().is_empty() {
1505            return None;
1506        }
1507        Some(wrapped_message)
1508    }
1509
1510    fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
1511        let text = self.commit_editor.read(cx).text(cx);
1512        if !text.trim().is_empty() {
1513            true
1514        } else if text.is_empty() {
1515            self.suggest_commit_message(cx)
1516                .is_some_and(|text| !text.trim().is_empty())
1517        } else {
1518            false
1519        }
1520    }
1521
1522    pub(crate) fn commit_changes(
1523        &mut self,
1524        options: CommitOptions,
1525        window: &mut Window,
1526        cx: &mut Context<Self>,
1527    ) {
1528        let Some(active_repository) = self.active_repository.clone() else {
1529            return;
1530        };
1531        let error_spawn = |message, window: &mut Window, cx: &mut App| {
1532            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1533            cx.spawn(async move |_| {
1534                prompt.await.ok();
1535            })
1536            .detach();
1537        };
1538
1539        if self.has_unstaged_conflicts() {
1540            error_spawn(
1541                "There are still conflicts. You must stage these before committing",
1542                window,
1543                cx,
1544            );
1545            return;
1546        }
1547
1548        let commit_message = self.custom_or_suggested_commit_message(window, cx);
1549
1550        let Some(mut message) = commit_message else {
1551            self.commit_editor.read(cx).focus_handle(cx).focus(window);
1552            return;
1553        };
1554
1555        if self.add_coauthors {
1556            self.fill_co_authors(&mut message, cx);
1557        }
1558
1559        let task = if self.has_staged_changes() {
1560            // Repository serializes all git operations, so we can just send a commit immediately
1561            let commit_task = active_repository.update(cx, |repo, cx| {
1562                repo.commit(message.into(), None, options, cx)
1563            });
1564            cx.background_spawn(async move { commit_task.await? })
1565        } else {
1566            let changed_files = self
1567                .entries
1568                .iter()
1569                .filter_map(|entry| entry.status_entry())
1570                .filter(|status_entry| !status_entry.status.is_created())
1571                .map(|status_entry| status_entry.repo_path.clone())
1572                .collect::<Vec<_>>();
1573
1574            if changed_files.is_empty() && !options.amend {
1575                error_spawn("No changes to commit", window, cx);
1576                return;
1577            }
1578
1579            let stage_task =
1580                active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1581            cx.spawn(async move |_, cx| {
1582                stage_task.await?;
1583                let commit_task = active_repository.update(cx, |repo, cx| {
1584                    repo.commit(message.into(), None, options, cx)
1585                })?;
1586                commit_task.await?
1587            })
1588        };
1589        let task = cx.spawn_in(window, async move |this, cx| {
1590            let result = task.await;
1591            this.update_in(cx, |this, window, cx| {
1592                this.pending_commit.take();
1593                match result {
1594                    Ok(()) => {
1595                        this.commit_editor
1596                            .update(cx, |editor, cx| editor.clear(window, cx));
1597                        this.original_commit_message = None;
1598                    }
1599                    Err(e) => this.show_error_toast("commit", e, cx),
1600                }
1601            })
1602            .ok();
1603        });
1604
1605        self.pending_commit = Some(task);
1606        if options.amend {
1607            self.set_amend_pending(false, cx);
1608        }
1609    }
1610
1611    pub(crate) fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1612        let Some(repo) = self.active_repository.clone() else {
1613            return;
1614        };
1615        telemetry::event!("Git Uncommitted");
1616
1617        let confirmation = self.check_for_pushed_commits(window, cx);
1618        let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1619
1620        let task = cx.spawn_in(window, async move |this, cx| {
1621            let result = maybe!(async {
1622                if let Ok(true) = confirmation.await {
1623                    let prior_head = prior_head.await?;
1624
1625                    repo.update(cx, |repo, cx| {
1626                        repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1627                    })?
1628                    .await??;
1629
1630                    Ok(Some(prior_head))
1631                } else {
1632                    Ok(None)
1633                }
1634            })
1635            .await;
1636
1637            this.update_in(cx, |this, window, cx| {
1638                this.pending_commit.take();
1639                match result {
1640                    Ok(None) => {}
1641                    Ok(Some(prior_commit)) => {
1642                        this.commit_editor.update(cx, |editor, cx| {
1643                            editor.set_text(prior_commit.message, window, cx)
1644                        });
1645                    }
1646                    Err(e) => this.show_error_toast("reset", e, cx),
1647                }
1648            })
1649            .ok();
1650        });
1651
1652        self.pending_commit = Some(task);
1653    }
1654
1655    fn check_for_pushed_commits(
1656        &mut self,
1657        window: &mut Window,
1658        cx: &mut Context<Self>,
1659    ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
1660        let repo = self.active_repository.clone();
1661        let mut cx = window.to_async(cx);
1662
1663        async move {
1664            let repo = repo.context("No active repository")?;
1665
1666            let pushed_to: Vec<SharedString> = repo
1667                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1668                .await??;
1669
1670            if pushed_to.is_empty() {
1671                Ok(true)
1672            } else {
1673                #[derive(strum::EnumIter, strum::VariantNames)]
1674                #[strum(serialize_all = "title_case")]
1675                enum CancelUncommit {
1676                    Uncommit,
1677                    Cancel,
1678                }
1679                let detail = format!(
1680                    "This commit was already pushed to {}.",
1681                    pushed_to.into_iter().join(", ")
1682                );
1683                let result = cx
1684                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1685                    .await?;
1686
1687                match result {
1688                    CancelUncommit::Cancel => Ok(false),
1689                    CancelUncommit::Uncommit => Ok(true),
1690                }
1691            }
1692        }
1693    }
1694
1695    /// Suggests a commit message based on the changed files and their statuses
1696    pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
1697        if let Some(merge_message) = self
1698            .active_repository
1699            .as_ref()
1700            .and_then(|repo| repo.read(cx).merge.message.as_ref())
1701        {
1702            return Some(merge_message.to_string());
1703        }
1704
1705        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1706            Some(staged_entry)
1707        } else if self.total_staged_count() == 0
1708            && let Some(single_tracked_entry) = &self.single_tracked_entry
1709        {
1710            Some(single_tracked_entry)
1711        } else {
1712            None
1713        }?;
1714
1715        let action_text = if git_status_entry.status.is_deleted() {
1716            Some("Delete")
1717        } else if git_status_entry.status.is_created() {
1718            Some("Create")
1719        } else if git_status_entry.status.is_modified() {
1720            Some("Update")
1721        } else {
1722            None
1723        }?;
1724
1725        let file_name = git_status_entry
1726            .repo_path
1727            .file_name()
1728            .unwrap_or_default()
1729            .to_string_lossy();
1730
1731        Some(format!("{} {}", action_text, file_name))
1732    }
1733
1734    fn generate_commit_message_action(
1735        &mut self,
1736        _: &git::GenerateCommitMessage,
1737        _window: &mut Window,
1738        cx: &mut Context<Self>,
1739    ) {
1740        self.generate_commit_message(cx);
1741    }
1742
1743    /// Generates a commit message using an LLM.
1744    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1745        if !self.can_commit()
1746            || DisableAiSettings::get_global(cx).disable_ai
1747            || !agent_settings::AgentSettings::get_global(cx).enabled
1748        {
1749            return;
1750        }
1751
1752        let Some(ConfiguredModel { provider, model }) =
1753            LanguageModelRegistry::read_global(cx).commit_message_model()
1754        else {
1755            return;
1756        };
1757
1758        let Some(repo) = self.active_repository.as_ref() else {
1759            return;
1760        };
1761
1762        telemetry::event!("Git Commit Message Generated");
1763
1764        let diff = repo.update(cx, |repo, cx| {
1765            if self.has_staged_changes() {
1766                repo.diff(DiffType::HeadToIndex, cx)
1767            } else {
1768                repo.diff(DiffType::HeadToWorktree, cx)
1769            }
1770        });
1771
1772        let temperature = AgentSettings::temperature_for_model(&model, cx);
1773
1774        self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1775             async move {
1776                let _defer = cx.on_drop(&this, |this, _cx| {
1777                    this.generate_commit_message_task.take();
1778                });
1779
1780                if let Some(task) = cx.update(|cx| {
1781                    if !provider.is_authenticated(cx) {
1782                        Some(provider.authenticate(cx))
1783                    } else {
1784                        None
1785                    }
1786                })? {
1787                    task.await.log_err();
1788                };
1789
1790                let mut diff_text = match diff.await {
1791                    Ok(result) => match result {
1792                        Ok(text) => text,
1793                        Err(e) => {
1794                            Self::show_commit_message_error(&this, &e, cx);
1795                            return anyhow::Ok(());
1796                        }
1797                    },
1798                    Err(e) => {
1799                        Self::show_commit_message_error(&this, &e, cx);
1800                        return anyhow::Ok(());
1801                    }
1802                };
1803
1804                const ONE_MB: usize = 1_000_000;
1805                if diff_text.len() > ONE_MB {
1806                    diff_text = diff_text.chars().take(ONE_MB).collect()
1807                }
1808
1809                let subject = this.update(cx, |this, cx| {
1810                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1811                })?;
1812
1813                let text_empty = subject.trim().is_empty();
1814
1815                let content = if text_empty {
1816                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1817                } else {
1818                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1819                };
1820
1821                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1822
1823                let request = LanguageModelRequest {
1824                    thread_id: None,
1825                    prompt_id: None,
1826                    intent: Some(CompletionIntent::GenerateGitCommitMessage),
1827                    mode: None,
1828                    messages: vec![LanguageModelRequestMessage {
1829                        role: Role::User,
1830                        content: vec![content.into()],
1831                        cache: false,
1832                    }],
1833                    tools: Vec::new(),
1834                    tool_choice: None,
1835                    stop: Vec::new(),
1836                    temperature,
1837                    thinking_allowed: false,
1838                };
1839
1840                let stream = model.stream_completion_text(request, cx);
1841                match stream.await {
1842                    Ok(mut messages) => {
1843                        if !text_empty {
1844                            this.update(cx, |this, cx| {
1845                                this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1846                                    let insert_position = buffer.anchor_before(buffer.len());
1847                                    buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1848                                });
1849                            })?;
1850                        }
1851
1852                        while let Some(message) = messages.stream.next().await {
1853                            match message {
1854                                Ok(text) => {
1855                                    this.update(cx, |this, cx| {
1856                                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1857                                            let insert_position = buffer.anchor_before(buffer.len());
1858                                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1859                                        });
1860                                    })?;
1861                                }
1862                                Err(e) => {
1863                                    Self::show_commit_message_error(&this, &e, cx);
1864                                    break;
1865                                }
1866                            }
1867                        }
1868                    }
1869                    Err(e) => {
1870                        Self::show_commit_message_error(&this, &e, cx);
1871                    }
1872                }
1873
1874                anyhow::Ok(())
1875            }
1876            .log_err().await
1877        }));
1878    }
1879
1880    fn get_fetch_options(
1881        &self,
1882        window: &mut Window,
1883        cx: &mut Context<Self>,
1884    ) -> Task<Option<FetchOptions>> {
1885        let repo = self.active_repository.clone();
1886        let workspace = self.workspace.clone();
1887
1888        cx.spawn_in(window, async move |_, cx| {
1889            let repo = repo?;
1890            let remotes = repo
1891                .update(cx, |repo, _| repo.get_remotes(None))
1892                .ok()?
1893                .await
1894                .ok()?
1895                .log_err()?;
1896
1897            let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
1898            if remotes.len() > 1 {
1899                remotes.push(FetchOptions::All);
1900            }
1901            let selection = cx
1902                .update(|window, cx| {
1903                    picker_prompt::prompt(
1904                        "Pick which remote to fetch",
1905                        remotes.iter().map(|r| r.name()).collect(),
1906                        workspace,
1907                        window,
1908                        cx,
1909                    )
1910                })
1911                .ok()?
1912                .await?;
1913            remotes.get(selection).cloned()
1914        })
1915    }
1916
1917    pub(crate) fn fetch(
1918        &mut self,
1919        is_fetch_all: bool,
1920        window: &mut Window,
1921        cx: &mut Context<Self>,
1922    ) {
1923        if !self.can_push_and_pull(cx) {
1924            return;
1925        }
1926
1927        let Some(repo) = self.active_repository.clone() else {
1928            return;
1929        };
1930        telemetry::event!("Git Fetched");
1931        let askpass = self.askpass_delegate("git fetch", window, cx);
1932        let this = cx.weak_entity();
1933
1934        let fetch_options = if is_fetch_all {
1935            Task::ready(Some(FetchOptions::All))
1936        } else {
1937            self.get_fetch_options(window, cx)
1938        };
1939
1940        window
1941            .spawn(cx, async move |cx| {
1942                let Some(fetch_options) = fetch_options.await else {
1943                    return Ok(());
1944                };
1945                let fetch = repo.update(cx, |repo, cx| {
1946                    repo.fetch(fetch_options.clone(), askpass, cx)
1947                })?;
1948
1949                let remote_message = fetch.await?;
1950                this.update(cx, |this, cx| {
1951                    let action = match fetch_options {
1952                        FetchOptions::All => RemoteAction::Fetch(None),
1953                        FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
1954                    };
1955                    match remote_message {
1956                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1957                        Err(e) => {
1958                            log::error!("Error while fetching {:?}", e);
1959                            this.show_error_toast(action.name(), e, cx)
1960                        }
1961                    }
1962
1963                    anyhow::Ok(())
1964                })
1965                .ok();
1966                anyhow::Ok(())
1967            })
1968            .detach_and_log_err(cx);
1969    }
1970
1971    pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
1972        let path = cx.prompt_for_paths(gpui::PathPromptOptions {
1973            files: false,
1974            directories: true,
1975            multiple: false,
1976            prompt: Some("Select as Repository Destination".into()),
1977        });
1978
1979        let workspace = self.workspace.clone();
1980
1981        cx.spawn_in(window, async move |this, cx| {
1982            let mut paths = path.await.ok()?.ok()??;
1983            let mut path = paths.pop()?;
1984            let repo_name = repo
1985                .split(std::path::MAIN_SEPARATOR_STR)
1986                .last()?
1987                .strip_suffix(".git")?
1988                .to_owned();
1989
1990            let fs = this.read_with(cx, |this, _| this.fs.clone()).ok()?;
1991
1992            let prompt_answer = match fs.git_clone(&repo, path.as_path()).await {
1993                Ok(_) => cx.update(|window, cx| {
1994                    window.prompt(
1995                        PromptLevel::Info,
1996                        &format!("Git Clone: {}", repo_name),
1997                        None,
1998                        &["Add repo to project", "Open repo in new project"],
1999                        cx,
2000                    )
2001                }),
2002                Err(e) => {
2003                    this.update(cx, |this: &mut GitPanel, cx| {
2004                        let toast = StatusToast::new(e.to_string(), cx, |this, _| {
2005                            this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2006                                .dismiss_button(true)
2007                        });
2008
2009                        this.workspace
2010                            .update(cx, |workspace, cx| {
2011                                workspace.toggle_status_toast(toast, cx);
2012                            })
2013                            .ok();
2014                    })
2015                    .ok()?;
2016
2017                    return None;
2018                }
2019            }
2020            .ok()?;
2021
2022            path.push(repo_name);
2023            match prompt_answer.await.ok()? {
2024                0 => {
2025                    workspace
2026                        .update(cx, |workspace, cx| {
2027                            workspace
2028                                .project()
2029                                .update(cx, |project, cx| {
2030                                    project.create_worktree(path.as_path(), true, cx)
2031                                })
2032                                .detach();
2033                        })
2034                        .ok();
2035                }
2036                1 => {
2037                    workspace
2038                        .update(cx, move |workspace, cx| {
2039                            workspace::open_new(
2040                                Default::default(),
2041                                workspace.app_state().clone(),
2042                                cx,
2043                                move |workspace, _, cx| {
2044                                    cx.activate(true);
2045                                    workspace
2046                                        .project()
2047                                        .update(cx, |project, cx| {
2048                                            project.create_worktree(&path, true, cx)
2049                                        })
2050                                        .detach();
2051                                },
2052                            )
2053                            .detach();
2054                        })
2055                        .ok();
2056                }
2057                _ => {}
2058            }
2059
2060            Some(())
2061        })
2062        .detach();
2063    }
2064
2065    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2066        let worktrees = self
2067            .project
2068            .read(cx)
2069            .visible_worktrees(cx)
2070            .collect::<Vec<_>>();
2071
2072        let worktree = if worktrees.len() == 1 {
2073            Task::ready(Some(worktrees.first().unwrap().clone()))
2074        } else if worktrees.is_empty() {
2075            let result = window.prompt(
2076                PromptLevel::Warning,
2077                "Unable to initialize a git repository",
2078                Some("Open a directory first"),
2079                &["Ok"],
2080                cx,
2081            );
2082            cx.background_executor()
2083                .spawn(async move {
2084                    result.await.ok();
2085                })
2086                .detach();
2087            return;
2088        } else {
2089            let worktree_directories = worktrees
2090                .iter()
2091                .map(|worktree| worktree.read(cx).abs_path())
2092                .map(|worktree_abs_path| {
2093                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2094                        Path::new("~")
2095                            .join(path)
2096                            .to_string_lossy()
2097                            .to_string()
2098                            .into()
2099                    } else {
2100                        worktree_abs_path.to_string_lossy().to_string().into()
2101                    }
2102                })
2103                .collect_vec();
2104            let prompt = picker_prompt::prompt(
2105                "Where would you like to initialize this git repository?",
2106                worktree_directories,
2107                self.workspace.clone(),
2108                window,
2109                cx,
2110            );
2111
2112            cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2113        };
2114
2115        cx.spawn_in(window, async move |this, cx| {
2116            let worktree = match worktree.await {
2117                Some(worktree) => worktree,
2118                None => {
2119                    return;
2120                }
2121            };
2122
2123            let Ok(result) = this.update(cx, |this, cx| {
2124                let fallback_branch_name = GitPanelSettings::get_global(cx)
2125                    .fallback_branch_name
2126                    .clone();
2127                this.project.read(cx).git_init(
2128                    worktree.read(cx).abs_path(),
2129                    fallback_branch_name,
2130                    cx,
2131                )
2132            }) else {
2133                return;
2134            };
2135
2136            let result = result.await;
2137
2138            this.update_in(cx, |this, _, cx| match result {
2139                Ok(()) => {}
2140                Err(e) => this.show_error_toast("init", e, cx),
2141            })
2142            .ok();
2143        })
2144        .detach();
2145    }
2146
2147    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2148        if !self.can_push_and_pull(cx) {
2149            return;
2150        }
2151        let Some(repo) = self.active_repository.clone() else {
2152            return;
2153        };
2154        let Some(branch) = repo.read(cx).branch.as_ref() else {
2155            return;
2156        };
2157        telemetry::event!("Git Pulled");
2158        let branch = branch.clone();
2159        let remote = self.get_remote(false, window, cx);
2160        cx.spawn_in(window, async move |this, cx| {
2161            let remote = match remote.await {
2162                Ok(Some(remote)) => remote,
2163                Ok(None) => {
2164                    return Ok(());
2165                }
2166                Err(e) => {
2167                    log::error!("Failed to get current remote: {}", e);
2168                    this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2169                        .ok();
2170                    return Ok(());
2171                }
2172            };
2173
2174            let askpass = this.update_in(cx, |this, window, cx| {
2175                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2176            })?;
2177
2178            let pull = repo.update(cx, |repo, cx| {
2179                repo.pull(
2180                    branch.name().to_owned().into(),
2181                    remote.name.clone(),
2182                    askpass,
2183                    cx,
2184                )
2185            })?;
2186
2187            let remote_message = pull.await?;
2188
2189            let action = RemoteAction::Pull(remote);
2190            this.update(cx, |this, cx| match remote_message {
2191                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2192                Err(e) => {
2193                    log::error!("Error while pulling {:?}", e);
2194                    this.show_error_toast(action.name(), e, cx)
2195                }
2196            })
2197            .ok();
2198
2199            anyhow::Ok(())
2200        })
2201        .detach_and_log_err(cx);
2202    }
2203
2204    pub(crate) fn push(
2205        &mut self,
2206        force_push: bool,
2207        select_remote: bool,
2208        window: &mut Window,
2209        cx: &mut Context<Self>,
2210    ) {
2211        if !self.can_push_and_pull(cx) {
2212            return;
2213        }
2214        let Some(repo) = self.active_repository.clone() else {
2215            return;
2216        };
2217        let Some(branch) = repo.read(cx).branch.as_ref() else {
2218            return;
2219        };
2220        telemetry::event!("Git Pushed");
2221        let branch = branch.clone();
2222
2223        let options = if force_push {
2224            Some(PushOptions::Force)
2225        } else {
2226            match branch.upstream {
2227                Some(Upstream {
2228                    tracking: UpstreamTracking::Gone,
2229                    ..
2230                })
2231                | None => Some(PushOptions::SetUpstream),
2232                _ => None,
2233            }
2234        };
2235        let remote = self.get_remote(select_remote, window, cx);
2236
2237        cx.spawn_in(window, async move |this, cx| {
2238            let remote = match remote.await {
2239                Ok(Some(remote)) => remote,
2240                Ok(None) => {
2241                    return Ok(());
2242                }
2243                Err(e) => {
2244                    log::error!("Failed to get current remote: {}", e);
2245                    this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2246                        .ok();
2247                    return Ok(());
2248                }
2249            };
2250
2251            let askpass_delegate = this.update_in(cx, |this, window, cx| {
2252                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2253            })?;
2254
2255            let push = repo.update(cx, |repo, cx| {
2256                repo.push(
2257                    branch.name().to_owned().into(),
2258                    remote.name.clone(),
2259                    options,
2260                    askpass_delegate,
2261                    cx,
2262                )
2263            })?;
2264
2265            let remote_output = push.await?;
2266
2267            let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2268            this.update(cx, |this, cx| match remote_output {
2269                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2270                Err(e) => {
2271                    log::error!("Error while pushing {:?}", e);
2272                    this.show_error_toast(action.name(), e, cx)
2273                }
2274            })?;
2275
2276            anyhow::Ok(())
2277        })
2278        .detach_and_log_err(cx);
2279    }
2280
2281    fn askpass_delegate(
2282        &self,
2283        operation: impl Into<SharedString>,
2284        window: &mut Window,
2285        cx: &mut Context<Self>,
2286    ) -> AskPassDelegate {
2287        let this = cx.weak_entity();
2288        let operation = operation.into();
2289        let window = window.window_handle();
2290        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2291            window
2292                .update(cx, |_, window, cx| {
2293                    this.update(cx, |this, cx| {
2294                        this.workspace.update(cx, |workspace, cx| {
2295                            workspace.toggle_modal(window, cx, |window, cx| {
2296                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2297                            });
2298                        })
2299                    })
2300                })
2301                .ok();
2302        })
2303    }
2304
2305    fn can_push_and_pull(&self, cx: &App) -> bool {
2306        !self.project.read(cx).is_via_collab()
2307    }
2308
2309    fn get_remote(
2310        &mut self,
2311        always_select: bool,
2312        window: &mut Window,
2313        cx: &mut Context<Self>,
2314    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2315        let repo = self.active_repository.clone();
2316        let workspace = self.workspace.clone();
2317        let mut cx = window.to_async(cx);
2318
2319        async move {
2320            let repo = repo.context("No active repository")?;
2321            let current_remotes: Vec<Remote> = repo
2322                .update(&mut cx, |repo, _| {
2323                    let current_branch = if always_select {
2324                        None
2325                    } else {
2326                        let current_branch = repo.branch.as_ref().context("No active branch")?;
2327                        Some(current_branch.name().to_string())
2328                    };
2329                    anyhow::Ok(repo.get_remotes(current_branch))
2330                })??
2331                .await??;
2332
2333            let current_remotes: Vec<_> = current_remotes
2334                .into_iter()
2335                .map(|remotes| remotes.name)
2336                .collect();
2337            let selection = cx
2338                .update(|window, cx| {
2339                    picker_prompt::prompt(
2340                        "Pick which remote to push to",
2341                        current_remotes.clone(),
2342                        workspace,
2343                        window,
2344                        cx,
2345                    )
2346                })?
2347                .await;
2348
2349            Ok(selection.map(|selection| Remote {
2350                name: current_remotes[selection].clone(),
2351            }))
2352        }
2353    }
2354
2355    pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2356        if self.local_committer_task.is_none() {
2357            self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2358                let committer = get_git_committer(cx).await;
2359                this.update(cx, |this, cx| {
2360                    this.local_committer = Some(committer);
2361                    cx.notify()
2362                })
2363                .ok();
2364            }));
2365        }
2366    }
2367
2368    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2369        let mut new_co_authors = Vec::new();
2370        let project = self.project.read(cx);
2371
2372        let Some(room) = self
2373            .workspace
2374            .upgrade()
2375            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2376        else {
2377            return Vec::default();
2378        };
2379
2380        let room = room.read(cx);
2381
2382        for (peer_id, collaborator) in project.collaborators() {
2383            if collaborator.is_host {
2384                continue;
2385            }
2386
2387            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2388                continue;
2389            };
2390            if !participant.can_write() {
2391                continue;
2392            }
2393            if let Some(email) = &collaborator.committer_email {
2394                let name = collaborator
2395                    .committer_name
2396                    .clone()
2397                    .or_else(|| participant.user.name.clone())
2398                    .unwrap_or_else(|| participant.user.github_login.clone().to_string());
2399                new_co_authors.push((name.clone(), email.clone()))
2400            }
2401        }
2402        if !project.is_local()
2403            && !project.is_read_only(cx)
2404            && let Some(local_committer) = self.local_committer(room, cx)
2405        {
2406            new_co_authors.push(local_committer);
2407        }
2408        new_co_authors
2409    }
2410
2411    fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2412        let user = room.local_participant_user(cx)?;
2413        let committer = self.local_committer.as_ref()?;
2414        let email = committer.email.clone()?;
2415        let name = committer
2416            .name
2417            .clone()
2418            .or_else(|| user.name.clone())
2419            .unwrap_or_else(|| user.github_login.clone().to_string());
2420        Some((name, email))
2421    }
2422
2423    fn toggle_fill_co_authors(
2424        &mut self,
2425        _: &ToggleFillCoAuthors,
2426        _: &mut Window,
2427        cx: &mut Context<Self>,
2428    ) {
2429        self.add_coauthors = !self.add_coauthors;
2430        cx.notify();
2431    }
2432
2433    fn toggle_sort_by_path(
2434        &mut self,
2435        _: &ToggleSortByPath,
2436        _: &mut Window,
2437        cx: &mut Context<Self>,
2438    ) {
2439        let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
2440        if let Some(workspace) = self.workspace.upgrade() {
2441            let workspace = workspace.read(cx);
2442            let fs = workspace.app_state().fs.clone();
2443            cx.update_global::<SettingsStore, _>(|store, _cx| {
2444                store.update_settings_file::<GitPanelSettings>(fs, move |settings, _cx| {
2445                    settings.sort_by_path = Some(!current_setting);
2446                });
2447            });
2448        }
2449    }
2450
2451    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2452        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2453
2454        let existing_text = message.to_ascii_lowercase();
2455        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2456        let mut ends_with_co_authors = false;
2457        let existing_co_authors = existing_text
2458            .lines()
2459            .filter_map(|line| {
2460                let line = line.trim();
2461                if line.starts_with(&lowercase_co_author_prefix) {
2462                    ends_with_co_authors = true;
2463                    Some(line)
2464                } else {
2465                    ends_with_co_authors = false;
2466                    None
2467                }
2468            })
2469            .collect::<HashSet<_>>();
2470
2471        let new_co_authors = self
2472            .potential_co_authors(cx)
2473            .into_iter()
2474            .filter(|(_, email)| {
2475                !existing_co_authors
2476                    .iter()
2477                    .any(|existing| existing.contains(email.as_str()))
2478            })
2479            .collect::<Vec<_>>();
2480
2481        if new_co_authors.is_empty() {
2482            return;
2483        }
2484
2485        if !ends_with_co_authors {
2486            message.push('\n');
2487        }
2488        for (name, email) in new_co_authors {
2489            message.push('\n');
2490            message.push_str(CO_AUTHOR_PREFIX);
2491            message.push_str(&name);
2492            message.push_str(" <");
2493            message.push_str(&email);
2494            message.push('>');
2495        }
2496        message.push('\n');
2497    }
2498
2499    fn schedule_update(
2500        &mut self,
2501        clear_pending: bool,
2502        window: &mut Window,
2503        cx: &mut Context<Self>,
2504    ) {
2505        let handle = cx.entity().downgrade();
2506        self.reopen_commit_buffer(window, cx);
2507        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2508            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2509            if let Some(git_panel) = handle.upgrade() {
2510                git_panel
2511                    .update_in(cx, |git_panel, window, cx| {
2512                        if clear_pending {
2513                            git_panel.clear_pending();
2514                        }
2515                        git_panel.update_visible_entries(window, cx);
2516                    })
2517                    .ok();
2518            }
2519        });
2520    }
2521
2522    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2523        let Some(active_repo) = self.active_repository.as_ref() else {
2524            return;
2525        };
2526        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2527            let project = self.project.read(cx);
2528            active_repo.open_commit_buffer(
2529                Some(project.languages().clone()),
2530                project.buffer_store().clone(),
2531                cx,
2532            )
2533        });
2534
2535        cx.spawn_in(window, async move |git_panel, cx| {
2536            let buffer = load_buffer.await?;
2537            git_panel.update_in(cx, |git_panel, window, cx| {
2538                if git_panel
2539                    .commit_editor
2540                    .read(cx)
2541                    .buffer()
2542                    .read(cx)
2543                    .as_singleton()
2544                    .as_ref()
2545                    != Some(&buffer)
2546                {
2547                    git_panel.commit_editor = cx.new(|cx| {
2548                        commit_message_editor(
2549                            buffer,
2550                            git_panel.suggest_commit_message(cx).map(SharedString::from),
2551                            git_panel.project.clone(),
2552                            true,
2553                            window,
2554                            cx,
2555                        )
2556                    });
2557                }
2558            })
2559        })
2560        .detach_and_log_err(cx);
2561    }
2562
2563    fn clear_pending(&mut self) {
2564        self.pending.retain(|v| !v.finished)
2565    }
2566
2567    fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2568        let bulk_staging = self.bulk_staging.take();
2569        let last_staged_path_prev_index = bulk_staging
2570            .as_ref()
2571            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2572
2573        self.entries.clear();
2574        self.single_staged_entry.take();
2575        self.single_tracked_entry.take();
2576        self.conflicted_count = 0;
2577        self.conflicted_staged_count = 0;
2578        self.new_count = 0;
2579        self.tracked_count = 0;
2580        self.new_staged_count = 0;
2581        self.tracked_staged_count = 0;
2582        self.entry_count = 0;
2583
2584        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2585
2586        let mut changed_entries = Vec::new();
2587        let mut new_entries = Vec::new();
2588        let mut conflict_entries = Vec::new();
2589        let mut single_staged_entry = None;
2590        let mut staged_count = 0;
2591        let mut max_width_item: Option<(RepoPath, usize)> = None;
2592
2593        let Some(repo) = self.active_repository.as_ref() else {
2594            // Just clear entries if no repository is active.
2595            cx.notify();
2596            return;
2597        };
2598
2599        let repo = repo.read(cx);
2600
2601        self.stash_entries = repo.cached_stash();
2602
2603        for entry in repo.cached_status() {
2604            let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2605            let is_new = entry.status.is_created();
2606            let staging = entry.status.staging();
2607
2608            if self.pending.iter().any(|pending| {
2609                pending.target_status == TargetStatus::Reverted
2610                    && !pending.finished
2611                    && pending
2612                        .entries
2613                        .iter()
2614                        .any(|pending| pending.repo_path == entry.repo_path)
2615            }) {
2616                continue;
2617            }
2618
2619            let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2620            let entry = GitStatusEntry {
2621                repo_path: entry.repo_path.clone(),
2622                abs_path,
2623                status: entry.status,
2624                staging,
2625            };
2626
2627            if staging.has_staged() {
2628                staged_count += 1;
2629                single_staged_entry = Some(entry.clone());
2630            }
2631
2632            let width_estimate = Self::item_width_estimate(
2633                entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2634                entry.display_name().len(),
2635            );
2636
2637            match max_width_item.as_mut() {
2638                Some((repo_path, estimate)) => {
2639                    if width_estimate > *estimate {
2640                        *repo_path = entry.repo_path.clone();
2641                        *estimate = width_estimate;
2642                    }
2643                }
2644                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2645            }
2646
2647            if sort_by_path {
2648                changed_entries.push(entry);
2649            } else if is_conflict {
2650                conflict_entries.push(entry);
2651            } else if is_new {
2652                new_entries.push(entry);
2653            } else {
2654                changed_entries.push(entry);
2655            }
2656        }
2657
2658        let mut pending_staged_count = 0;
2659        let mut last_pending_staged = None;
2660        let mut pending_status_for_single_staged = None;
2661        for pending in self.pending.iter() {
2662            if pending.target_status == TargetStatus::Staged {
2663                pending_staged_count += pending.entries.len();
2664                last_pending_staged = pending.entries.first().cloned();
2665            }
2666            if let Some(single_staged) = &single_staged_entry
2667                && pending
2668                    .entries
2669                    .iter()
2670                    .any(|entry| entry.repo_path == single_staged.repo_path)
2671            {
2672                pending_status_for_single_staged = Some(pending.target_status);
2673            }
2674        }
2675
2676        if conflict_entries.is_empty() && staged_count == 1 && pending_staged_count == 0 {
2677            match pending_status_for_single_staged {
2678                Some(TargetStatus::Staged) | None => {
2679                    self.single_staged_entry = single_staged_entry;
2680                }
2681                _ => {}
2682            }
2683        } else if conflict_entries.is_empty() && pending_staged_count == 1 {
2684            self.single_staged_entry = last_pending_staged;
2685        }
2686
2687        if conflict_entries.is_empty() && changed_entries.len() == 1 {
2688            self.single_tracked_entry = changed_entries.first().cloned();
2689        }
2690
2691        if !conflict_entries.is_empty() {
2692            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2693                header: Section::Conflict,
2694            }));
2695            self.entries
2696                .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2697        }
2698
2699        if !changed_entries.is_empty() {
2700            if !sort_by_path {
2701                self.entries.push(GitListEntry::Header(GitHeaderEntry {
2702                    header: Section::Tracked,
2703                }));
2704            }
2705            self.entries
2706                .extend(changed_entries.into_iter().map(GitListEntry::Status));
2707        }
2708        if !new_entries.is_empty() {
2709            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2710                header: Section::New,
2711            }));
2712            self.entries
2713                .extend(new_entries.into_iter().map(GitListEntry::Status));
2714        }
2715
2716        if let Some((repo_path, _)) = max_width_item {
2717            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2718                GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2719                GitListEntry::Header(_) => false,
2720            });
2721        }
2722
2723        self.update_counts(repo);
2724
2725        let bulk_staging_anchor_new_index = bulk_staging
2726            .as_ref()
2727            .filter(|op| op.repo_id == repo.id)
2728            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2729        if bulk_staging_anchor_new_index == last_staged_path_prev_index
2730            && let Some(index) = bulk_staging_anchor_new_index
2731            && let Some(entry) = self.entries.get(index)
2732            && let Some(entry) = entry.status_entry()
2733            && self.entry_staging(entry) == StageStatus::Staged
2734        {
2735            self.bulk_staging = bulk_staging;
2736        }
2737
2738        self.select_first_entry_if_none(cx);
2739
2740        let suggested_commit_message = self.suggest_commit_message(cx);
2741        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2742
2743        self.commit_editor.update(cx, |editor, cx| {
2744            editor.set_placeholder_text(&placeholder_text, window, cx)
2745        });
2746
2747        cx.notify();
2748    }
2749
2750    fn header_state(&self, header_type: Section) -> ToggleState {
2751        let (staged_count, count) = match header_type {
2752            Section::New => (self.new_staged_count, self.new_count),
2753            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2754            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2755        };
2756        if staged_count == 0 {
2757            ToggleState::Unselected
2758        } else if count == staged_count {
2759            ToggleState::Selected
2760        } else {
2761            ToggleState::Indeterminate
2762        }
2763    }
2764
2765    fn update_counts(&mut self, repo: &Repository) {
2766        self.show_placeholders = false;
2767        self.conflicted_count = 0;
2768        self.conflicted_staged_count = 0;
2769        self.new_count = 0;
2770        self.tracked_count = 0;
2771        self.new_staged_count = 0;
2772        self.tracked_staged_count = 0;
2773        self.entry_count = 0;
2774        for entry in &self.entries {
2775            let Some(status_entry) = entry.status_entry() else {
2776                continue;
2777            };
2778            self.entry_count += 1;
2779            if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2780                self.conflicted_count += 1;
2781                if self.entry_staging(status_entry).has_staged() {
2782                    self.conflicted_staged_count += 1;
2783                }
2784            } else if status_entry.status.is_created() {
2785                self.new_count += 1;
2786                if self.entry_staging(status_entry).has_staged() {
2787                    self.new_staged_count += 1;
2788                }
2789            } else {
2790                self.tracked_count += 1;
2791                if self.entry_staging(status_entry).has_staged() {
2792                    self.tracked_staged_count += 1;
2793                }
2794            }
2795        }
2796    }
2797
2798    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2799        for pending in self.pending.iter().rev() {
2800            if pending
2801                .entries
2802                .iter()
2803                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2804            {
2805                match pending.target_status {
2806                    TargetStatus::Staged => return StageStatus::Staged,
2807                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2808                    TargetStatus::Reverted => continue,
2809                    TargetStatus::Unchanged => continue,
2810                }
2811            }
2812        }
2813        entry.staging
2814    }
2815
2816    pub(crate) fn has_staged_changes(&self) -> bool {
2817        self.tracked_staged_count > 0
2818            || self.new_staged_count > 0
2819            || self.conflicted_staged_count > 0
2820    }
2821
2822    pub(crate) fn has_unstaged_changes(&self) -> bool {
2823        self.tracked_count > self.tracked_staged_count
2824            || self.new_count > self.new_staged_count
2825            || self.conflicted_count > self.conflicted_staged_count
2826    }
2827
2828    fn has_tracked_changes(&self) -> bool {
2829        self.tracked_count > 0
2830    }
2831
2832    pub fn has_unstaged_conflicts(&self) -> bool {
2833        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2834    }
2835
2836    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2837        let action = action.into();
2838        let Some(workspace) = self.workspace.upgrade() else {
2839            return;
2840        };
2841
2842        let message = e.to_string().trim().to_string();
2843        if message
2844            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2845            .next()
2846            .is_some()
2847        { // Hide the cancelled by user message
2848        } else {
2849            workspace.update(cx, |workspace, cx| {
2850                let workspace_weak = cx.weak_entity();
2851                let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2852                    this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2853                        .action("View Log", move |window, cx| {
2854                            let message = message.clone();
2855                            let action = action.clone();
2856                            workspace_weak
2857                                .update(cx, move |workspace, cx| {
2858                                    Self::open_output(action, workspace, &message, window, cx)
2859                                })
2860                                .ok();
2861                        })
2862                });
2863                workspace.toggle_status_toast(toast, cx)
2864            });
2865        }
2866    }
2867
2868    fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
2869    where
2870        E: std::fmt::Debug + std::fmt::Display,
2871    {
2872        if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
2873            let _ = workspace.update(cx, |workspace, cx| {
2874                struct CommitMessageError;
2875                let notification_id = NotificationId::unique::<CommitMessageError>();
2876                workspace.show_notification(notification_id, cx, |cx| {
2877                    cx.new(|cx| {
2878                        ErrorMessagePrompt::new(
2879                            format!("Failed to generate commit message: {err}"),
2880                            cx,
2881                        )
2882                    })
2883                });
2884            });
2885        }
2886    }
2887
2888    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2889        let Some(workspace) = self.workspace.upgrade() else {
2890            return;
2891        };
2892
2893        workspace.update(cx, |workspace, cx| {
2894            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2895            let workspace_weak = cx.weak_entity();
2896            let operation = action.name();
2897
2898            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2899                use remote_output::SuccessStyle::*;
2900                match style {
2901                    Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
2902                    ToastWithLog { output } => this
2903                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2904                        .action("View Log", move |window, cx| {
2905                            let output = output.clone();
2906                            let output =
2907                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2908                            workspace_weak
2909                                .update(cx, move |workspace, cx| {
2910                                    Self::open_output(operation, workspace, &output, window, cx)
2911                                })
2912                                .ok();
2913                        }),
2914                    PushPrLink { text, link } => this
2915                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2916                        .action(text, move |_, cx| cx.open_url(&link)),
2917                }
2918            });
2919            workspace.toggle_status_toast(status_toast, cx)
2920        });
2921    }
2922
2923    fn open_output(
2924        operation: impl Into<SharedString>,
2925        workspace: &mut Workspace,
2926        output: &str,
2927        window: &mut Window,
2928        cx: &mut Context<Workspace>,
2929    ) {
2930        let operation = operation.into();
2931        let buffer = cx.new(|cx| Buffer::local(output, cx));
2932        buffer.update(cx, |buffer, cx| {
2933            buffer.set_capability(language::Capability::ReadOnly, cx);
2934        });
2935        let editor = cx.new(|cx| {
2936            let mut editor = Editor::for_buffer(buffer, None, window, cx);
2937            editor.buffer().update(cx, |buffer, cx| {
2938                buffer.set_title(format!("Output from git {operation}"), cx);
2939            });
2940            editor.set_read_only(true);
2941            editor
2942        });
2943
2944        workspace.add_item_to_center(Box::new(editor), window, cx);
2945    }
2946
2947    pub fn can_commit(&self) -> bool {
2948        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2949    }
2950
2951    pub fn can_stage_all(&self) -> bool {
2952        self.has_unstaged_changes()
2953    }
2954
2955    pub fn can_unstage_all(&self) -> bool {
2956        self.has_staged_changes()
2957    }
2958
2959    // eventually we'll need to take depth into account here
2960    // if we add a tree view
2961    fn item_width_estimate(path: usize, file_name: usize) -> usize {
2962        path + file_name
2963    }
2964
2965    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2966        let focus_handle = self.focus_handle.clone();
2967        let has_tracked_changes = self.has_tracked_changes();
2968        let has_staged_changes = self.has_staged_changes();
2969        let has_unstaged_changes = self.has_unstaged_changes();
2970        let has_new_changes = self.new_count > 0;
2971        let has_stash_items = self.stash_entries.entries.len() > 0;
2972
2973        PopoverMenu::new(id.into())
2974            .trigger(
2975                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
2976                    .icon_size(IconSize::Small)
2977                    .icon_color(Color::Muted),
2978            )
2979            .menu(move |window, cx| {
2980                Some(git_panel_context_menu(
2981                    focus_handle.clone(),
2982                    GitMenuState {
2983                        has_tracked_changes,
2984                        has_staged_changes,
2985                        has_unstaged_changes,
2986                        has_new_changes,
2987                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
2988                        has_stash_items,
2989                    },
2990                    window,
2991                    cx,
2992                ))
2993            })
2994            .anchor(Corner::TopRight)
2995    }
2996
2997    pub(crate) fn render_generate_commit_message_button(
2998        &self,
2999        cx: &Context<Self>,
3000    ) -> Option<AnyElement> {
3001        if !agent_settings::AgentSettings::get_global(cx).enabled
3002            || DisableAiSettings::get_global(cx).disable_ai
3003            || LanguageModelRegistry::read_global(cx)
3004                .commit_message_model()
3005                .is_none()
3006        {
3007            return None;
3008        }
3009
3010        if self.generate_commit_message_task.is_some() {
3011            return Some(
3012                h_flex()
3013                    .gap_1()
3014                    .child(
3015                        Icon::new(IconName::ArrowCircle)
3016                            .size(IconSize::XSmall)
3017                            .color(Color::Info)
3018                            .with_rotate_animation(2),
3019                    )
3020                    .child(
3021                        Label::new("Generating Commit...")
3022                            .size(LabelSize::Small)
3023                            .color(Color::Muted),
3024                    )
3025                    .into_any_element(),
3026            );
3027        }
3028
3029        let can_commit = self.can_commit();
3030        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3031        Some(
3032            IconButton::new("generate-commit-message", IconName::AiEdit)
3033                .shape(ui::IconButtonShape::Square)
3034                .icon_color(Color::Muted)
3035                .tooltip(move |window, cx| {
3036                    if can_commit {
3037                        Tooltip::for_action_in(
3038                            "Generate Commit Message",
3039                            &git::GenerateCommitMessage,
3040                            &editor_focus_handle,
3041                            window,
3042                            cx,
3043                        )
3044                    } else {
3045                        Tooltip::simple("No changes to commit", cx)
3046                    }
3047                })
3048                .disabled(!can_commit)
3049                .on_click(cx.listener(move |this, _event, _window, cx| {
3050                    this.generate_commit_message(cx);
3051                }))
3052                .into_any_element(),
3053        )
3054    }
3055
3056    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3057        let potential_co_authors = self.potential_co_authors(cx);
3058
3059        let (tooltip_label, icon) = if self.add_coauthors {
3060            ("Remove co-authored-by", IconName::Person)
3061        } else {
3062            ("Add co-authored-by", IconName::UserCheck)
3063        };
3064
3065        if potential_co_authors.is_empty() {
3066            None
3067        } else {
3068            Some(
3069                IconButton::new("co-authors", icon)
3070                    .shape(ui::IconButtonShape::Square)
3071                    .icon_color(Color::Disabled)
3072                    .selected_icon_color(Color::Selected)
3073                    .toggle_state(self.add_coauthors)
3074                    .tooltip(move |_, cx| {
3075                        let title = format!(
3076                            "{}:{}{}",
3077                            tooltip_label,
3078                            if potential_co_authors.len() == 1 {
3079                                ""
3080                            } else {
3081                                "\n"
3082                            },
3083                            potential_co_authors
3084                                .iter()
3085                                .map(|(name, email)| format!(" {} <{}>", name, email))
3086                                .join("\n")
3087                        );
3088                        Tooltip::simple(title, cx)
3089                    })
3090                    .on_click(cx.listener(|this, _, _, cx| {
3091                        this.add_coauthors = !this.add_coauthors;
3092                        cx.notify();
3093                    }))
3094                    .into_any_element(),
3095            )
3096        }
3097    }
3098
3099    fn render_git_commit_menu(
3100        &self,
3101        id: impl Into<ElementId>,
3102        keybinding_target: Option<FocusHandle>,
3103        cx: &mut Context<Self>,
3104    ) -> impl IntoElement {
3105        PopoverMenu::new(id.into())
3106            .trigger(
3107                ui::ButtonLike::new_rounded_right("commit-split-button-right")
3108                    .layer(ui::ElevationIndex::ModalSurface)
3109                    .size(ButtonSize::None)
3110                    .child(
3111                        h_flex()
3112                            .px_1()
3113                            .h_full()
3114                            .justify_center()
3115                            .border_l_1()
3116                            .border_color(cx.theme().colors().border)
3117                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3118                    ),
3119            )
3120            .menu({
3121                let git_panel = cx.entity();
3122                let has_previous_commit = self.head_commit(cx).is_some();
3123                let amend = self.amend_pending();
3124                let signoff = self.signoff_enabled;
3125
3126                move |window, cx| {
3127                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3128                        context_menu
3129                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
3130                                el.context(keybinding_target)
3131                            })
3132                            .when(has_previous_commit, |this| {
3133                                this.toggleable_entry(
3134                                    "Amend",
3135                                    amend,
3136                                    IconPosition::Start,
3137                                    Some(Box::new(Amend)),
3138                                    {
3139                                        let git_panel = git_panel.downgrade();
3140                                        move |_, cx| {
3141                                            git_panel
3142                                                .update(cx, |git_panel, cx| {
3143                                                    git_panel.toggle_amend_pending(cx);
3144                                                })
3145                                                .ok();
3146                                        }
3147                                    },
3148                                )
3149                            })
3150                            .toggleable_entry(
3151                                "Signoff",
3152                                signoff,
3153                                IconPosition::Start,
3154                                Some(Box::new(Signoff)),
3155                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3156                            )
3157                    }))
3158                }
3159            })
3160            .anchor(Corner::TopRight)
3161    }
3162
3163    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3164        if self.has_unstaged_conflicts() {
3165            (false, "You must resolve conflicts before committing")
3166        } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
3167            (false, "No changes to commit")
3168        } else if self.pending_commit.is_some() {
3169            (false, "Commit in progress")
3170        } else if !self.has_commit_message(cx) {
3171            (false, "No commit message")
3172        } else if !self.has_write_access(cx) {
3173            (false, "You do not have write access to this project")
3174        } else {
3175            (true, self.commit_button_title())
3176        }
3177    }
3178
3179    pub fn commit_button_title(&self) -> &'static str {
3180        if self.amend_pending {
3181            if self.has_staged_changes() {
3182                "Amend"
3183            } else if self.has_tracked_changes() {
3184                "Amend Tracked"
3185            } else {
3186                "Amend"
3187            }
3188        } else if self.has_staged_changes() {
3189            "Commit"
3190        } else {
3191            "Commit Tracked"
3192        }
3193    }
3194
3195    fn expand_commit_editor(
3196        &mut self,
3197        _: &git::ExpandCommitEditor,
3198        window: &mut Window,
3199        cx: &mut Context<Self>,
3200    ) {
3201        let workspace = self.workspace.clone();
3202        window.defer(cx, move |window, cx| {
3203            workspace
3204                .update(cx, |workspace, cx| {
3205                    CommitModal::toggle(workspace, None, window, cx)
3206                })
3207                .ok();
3208        })
3209    }
3210
3211    fn render_panel_header(
3212        &self,
3213        window: &mut Window,
3214        cx: &mut Context<Self>,
3215    ) -> Option<impl IntoElement> {
3216        self.active_repository.as_ref()?;
3217
3218        let text;
3219        let action;
3220        let tooltip;
3221        if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3222            text = "Unstage All";
3223            action = git::UnstageAll.boxed_clone();
3224            tooltip = "git reset";
3225        } else {
3226            text = "Stage All";
3227            action = git::StageAll.boxed_clone();
3228            tooltip = "git add --all ."
3229        }
3230
3231        let change_string = match self.entry_count {
3232            0 => "No Changes".to_string(),
3233            1 => "1 Change".to_string(),
3234            _ => format!("{} Changes", self.entry_count),
3235        };
3236
3237        Some(
3238            self.panel_header_container(window, cx)
3239                .px_2()
3240                .justify_between()
3241                .child(
3242                    panel_button(change_string)
3243                        .color(Color::Muted)
3244                        .tooltip(Tooltip::for_action_title_in(
3245                            "Open Diff",
3246                            &Diff,
3247                            &self.focus_handle,
3248                        ))
3249                        .on_click(|_, _, cx| {
3250                            cx.defer(|cx| {
3251                                cx.dispatch_action(&Diff);
3252                            })
3253                        }),
3254                )
3255                .child(
3256                    h_flex()
3257                        .gap_1()
3258                        .child(self.render_overflow_menu("overflow_menu"))
3259                        .child(
3260                            panel_filled_button(text)
3261                                .tooltip(Tooltip::for_action_title_in(
3262                                    tooltip,
3263                                    action.as_ref(),
3264                                    &self.focus_handle,
3265                                ))
3266                                .disabled(self.entry_count == 0)
3267                                .on_click(move |_, _, cx| {
3268                                    let action = action.boxed_clone();
3269                                    cx.defer(move |cx| {
3270                                        cx.dispatch_action(action.as_ref());
3271                                    })
3272                                }),
3273                        ),
3274                ),
3275        )
3276    }
3277
3278    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3279        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3280        if !self.can_push_and_pull(cx) {
3281            return None;
3282        }
3283        Some(
3284            h_flex()
3285                .gap_1()
3286                .flex_shrink_0()
3287                .when_some(branch, |this, branch| {
3288                    let focus_handle = Some(self.focus_handle(cx));
3289
3290                    this.children(render_remote_button(
3291                        "remote-button",
3292                        &branch,
3293                        focus_handle,
3294                        true,
3295                    ))
3296                })
3297                .into_any_element(),
3298        )
3299    }
3300
3301    pub fn render_footer(
3302        &self,
3303        window: &mut Window,
3304        cx: &mut Context<Self>,
3305    ) -> Option<impl IntoElement> {
3306        let active_repository = self.active_repository.clone()?;
3307        let panel_editor_style = panel_editor_style(true, window, cx);
3308
3309        let enable_coauthors = self.render_co_authors(cx);
3310
3311        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3312        let expand_tooltip_focus_handle = editor_focus_handle;
3313
3314        let branch = active_repository.read(cx).branch.clone();
3315        let head_commit = active_repository.read(cx).head_commit.clone();
3316
3317        let footer_size = px(32.);
3318        let gap = px(9.0);
3319        let max_height = panel_editor_style
3320            .text
3321            .line_height_in_pixels(window.rem_size())
3322            * MAX_PANEL_EDITOR_LINES
3323            + gap;
3324
3325        let git_panel = cx.entity();
3326        let display_name = SharedString::from(Arc::from(
3327            active_repository
3328                .read(cx)
3329                .display_name()
3330                .trim_end_matches("/"),
3331        ));
3332        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3333            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3334        });
3335
3336        let footer = v_flex()
3337            .child(PanelRepoFooter::new(
3338                display_name,
3339                branch,
3340                head_commit,
3341                Some(git_panel),
3342            ))
3343            .child(
3344                panel_editor_container(window, cx)
3345                    .id("commit-editor-container")
3346                    .relative()
3347                    .w_full()
3348                    .h(max_height + footer_size)
3349                    .border_t_1()
3350                    .border_color(cx.theme().colors().border)
3351                    .cursor_text()
3352                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3353                        window.focus(&this.commit_editor.focus_handle(cx));
3354                    }))
3355                    .child(
3356                        h_flex()
3357                            .id("commit-footer")
3358                            .border_t_1()
3359                            .when(editor_is_long, |el| {
3360                                el.border_color(cx.theme().colors().border_variant)
3361                            })
3362                            .absolute()
3363                            .bottom_0()
3364                            .left_0()
3365                            .w_full()
3366                            .px_2()
3367                            .h(footer_size)
3368                            .flex_none()
3369                            .justify_between()
3370                            .child(
3371                                self.render_generate_commit_message_button(cx)
3372                                    .unwrap_or_else(|| div().into_any_element()),
3373                            )
3374                            .child(
3375                                h_flex()
3376                                    .gap_0p5()
3377                                    .children(enable_coauthors)
3378                                    .child(self.render_commit_button(cx)),
3379                            ),
3380                    )
3381                    .child(
3382                        div()
3383                            .pr_2p5()
3384                            .on_action(|&editor::actions::MoveUp, _, cx| {
3385                                cx.stop_propagation();
3386                            })
3387                            .on_action(|&editor::actions::MoveDown, _, cx| {
3388                                cx.stop_propagation();
3389                            })
3390                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3391                    )
3392                    .child(
3393                        h_flex()
3394                            .absolute()
3395                            .top_2()
3396                            .right_2()
3397                            .opacity(0.5)
3398                            .hover(|this| this.opacity(1.0))
3399                            .child(
3400                                panel_icon_button("expand-commit-editor", IconName::Maximize)
3401                                    .icon_size(IconSize::Small)
3402                                    .size(ui::ButtonSize::Default)
3403                                    .tooltip(move |window, cx| {
3404                                        Tooltip::for_action_in(
3405                                            "Open Commit Modal",
3406                                            &git::ExpandCommitEditor,
3407                                            &expand_tooltip_focus_handle,
3408                                            window,
3409                                            cx,
3410                                        )
3411                                    })
3412                                    .on_click(cx.listener({
3413                                        move |_, _, window, cx| {
3414                                            window.dispatch_action(
3415                                                git::ExpandCommitEditor.boxed_clone(),
3416                                                cx,
3417                                            )
3418                                        }
3419                                    })),
3420                            ),
3421                    ),
3422            );
3423
3424        Some(footer)
3425    }
3426
3427    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3428        let (can_commit, tooltip) = self.configure_commit_button(cx);
3429        let title = self.commit_button_title();
3430        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3431        let amend = self.amend_pending();
3432        let signoff = self.signoff_enabled;
3433
3434        div()
3435            .id("commit-wrapper")
3436            .on_hover(cx.listener(move |this, hovered, _, cx| {
3437                this.show_placeholders =
3438                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3439                cx.notify()
3440            }))
3441            .child(SplitButton::new(
3442                ui::ButtonLike::new_rounded_left(ElementId::Name(
3443                    format!("split-button-left-{}", title).into(),
3444                ))
3445                .layer(ui::ElevationIndex::ModalSurface)
3446                .size(ui::ButtonSize::Compact)
3447                .child(
3448                    div()
3449                        .child(Label::new(title).size(LabelSize::Small))
3450                        .mr_0p5(),
3451                )
3452                .on_click({
3453                    let git_panel = cx.weak_entity();
3454                    move |_, window, cx| {
3455                        telemetry::event!("Git Committed", source = "Git Panel");
3456                        git_panel
3457                            .update(cx, |git_panel, cx| {
3458                                git_panel.commit_changes(
3459                                    CommitOptions { amend, signoff },
3460                                    window,
3461                                    cx,
3462                                );
3463                            })
3464                            .ok();
3465                    }
3466                })
3467                .disabled(!can_commit || self.modal_open)
3468                .tooltip({
3469                    let handle = commit_tooltip_focus_handle.clone();
3470                    move |window, cx| {
3471                        if can_commit {
3472                            Tooltip::with_meta_in(
3473                                tooltip,
3474                                Some(&git::Commit),
3475                                format!(
3476                                    "git commit{}{}",
3477                                    if amend { " --amend" } else { "" },
3478                                    if signoff { " --signoff" } else { "" }
3479                                ),
3480                                &handle.clone(),
3481                                window,
3482                                cx,
3483                            )
3484                        } else {
3485                            Tooltip::simple(tooltip, cx)
3486                        }
3487                    }
3488                }),
3489                self.render_git_commit_menu(
3490                    ElementId::Name(format!("split-button-right-{}", title).into()),
3491                    Some(commit_tooltip_focus_handle),
3492                    cx,
3493                )
3494                .into_any_element(),
3495            ))
3496    }
3497
3498    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3499        h_flex()
3500            .py_1p5()
3501            .px_2()
3502            .gap_1p5()
3503            .justify_between()
3504            .border_t_1()
3505            .border_color(cx.theme().colors().border.opacity(0.8))
3506            .child(
3507                div()
3508                    .flex_grow()
3509                    .overflow_hidden()
3510                    .max_w(relative(0.85))
3511                    .child(
3512                        Label::new("This will update your most recent commit.")
3513                            .size(LabelSize::Small)
3514                            .truncate(),
3515                    ),
3516            )
3517            .child(
3518                panel_button("Cancel")
3519                    .size(ButtonSize::Default)
3520                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3521            )
3522    }
3523
3524    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3525        let active_repository = self.active_repository.as_ref()?;
3526        let branch = active_repository.read(cx).branch.as_ref()?;
3527        let commit = branch.most_recent_commit.as_ref()?.clone();
3528        let workspace = self.workspace.clone();
3529        let this = cx.entity();
3530
3531        Some(
3532            h_flex()
3533                .py_1p5()
3534                .px_2()
3535                .gap_1p5()
3536                .justify_between()
3537                .border_t_1()
3538                .border_color(cx.theme().colors().border.opacity(0.8))
3539                .child(
3540                    div()
3541                        .flex_grow()
3542                        .overflow_hidden()
3543                        .max_w(relative(0.85))
3544                        .child(
3545                            Label::new(commit.subject.clone())
3546                                .size(LabelSize::Small)
3547                                .truncate(),
3548                        )
3549                        .id("commit-msg-hover")
3550                        .on_click({
3551                            let commit = commit.clone();
3552                            let repo = active_repository.downgrade();
3553                            move |_, window, cx| {
3554                                CommitView::open(
3555                                    commit.clone(),
3556                                    repo.clone(),
3557                                    workspace.clone(),
3558                                    window,
3559                                    cx,
3560                                );
3561                            }
3562                        })
3563                        .hoverable_tooltip({
3564                            let repo = active_repository.clone();
3565                            move |window, cx| {
3566                                GitPanelMessageTooltip::new(
3567                                    this.clone(),
3568                                    commit.sha.clone(),
3569                                    repo.clone(),
3570                                    window,
3571                                    cx,
3572                                )
3573                                .into()
3574                            }
3575                        }),
3576                )
3577                .when(commit.has_parent, |this| {
3578                    let has_unstaged = self.has_unstaged_changes();
3579                    this.child(
3580                        panel_icon_button("undo", IconName::Undo)
3581                            .icon_size(IconSize::XSmall)
3582                            .icon_color(Color::Muted)
3583                            .tooltip(move |window, cx| {
3584                                Tooltip::with_meta(
3585                                    "Uncommit",
3586                                    Some(&git::Uncommit),
3587                                    if has_unstaged {
3588                                        "git reset HEAD^ --soft"
3589                                    } else {
3590                                        "git reset HEAD^"
3591                                    },
3592                                    window,
3593                                    cx,
3594                                )
3595                            })
3596                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3597                    )
3598                }),
3599        )
3600    }
3601
3602    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3603        h_flex().h_full().flex_grow().justify_center().child(
3604            v_flex()
3605                .gap_2()
3606                .child(h_flex().w_full().justify_around().child(
3607                    if self.active_repository.is_some() {
3608                        "No changes to commit"
3609                    } else {
3610                        "No Git repositories"
3611                    },
3612                ))
3613                .children({
3614                    let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3615                    (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3616                        h_flex().w_full().justify_around().child(
3617                            panel_filled_button("Initialize Repository")
3618                                .tooltip(Tooltip::for_action_title_in(
3619                                    "git init",
3620                                    &git::Init,
3621                                    &self.focus_handle,
3622                                ))
3623                                .on_click(move |_, _, cx| {
3624                                    cx.defer(move |cx| {
3625                                        cx.dispatch_action(&git::Init);
3626                                    })
3627                                }),
3628                        )
3629                    })
3630                })
3631                .text_ui_sm(cx)
3632                .mx_auto()
3633                .text_color(Color::Placeholder.color(cx)),
3634        )
3635    }
3636
3637    fn render_buffer_header_controls(
3638        &self,
3639        entity: &Entity<Self>,
3640        file: &Arc<dyn File>,
3641        _: &Window,
3642        cx: &App,
3643    ) -> Option<AnyElement> {
3644        let repo = self.active_repository.as_ref()?.read(cx);
3645        let project_path = (file.worktree_id(cx), file.path()).into();
3646        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3647        let ix = self.entry_by_path(&repo_path, cx)?;
3648        let entry = self.entries.get(ix)?;
3649
3650        let entry_staging = self.entry_staging(entry.status_entry()?);
3651
3652        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3653            .disabled(!self.has_write_access(cx))
3654            .fill()
3655            .elevation(ElevationIndex::Surface)
3656            .on_click({
3657                let entry = entry.clone();
3658                let git_panel = entity.downgrade();
3659                move |_, window, cx| {
3660                    git_panel
3661                        .update(cx, |this, cx| {
3662                            this.toggle_staged_for_entry(&entry, window, cx);
3663                            cx.stop_propagation();
3664                        })
3665                        .ok();
3666                }
3667            });
3668        Some(
3669            h_flex()
3670                .id("start-slot")
3671                .text_lg()
3672                .child(checkbox)
3673                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3674                    // prevent the list item active state triggering when toggling checkbox
3675                    cx.stop_propagation();
3676                })
3677                .into_any_element(),
3678        )
3679    }
3680
3681    fn render_entries(
3682        &self,
3683        has_write_access: bool,
3684        window: &mut Window,
3685        cx: &mut Context<Self>,
3686    ) -> impl IntoElement {
3687        let entry_count = self.entries.len();
3688
3689        v_flex()
3690            .flex_1()
3691            .size_full()
3692            .overflow_hidden()
3693            .relative()
3694            .child(
3695                h_flex()
3696                    .flex_1()
3697                    .size_full()
3698                    .relative()
3699                    .overflow_hidden()
3700                    .child(
3701                        uniform_list(
3702                            "entries",
3703                            entry_count,
3704                            cx.processor(move |this, range: Range<usize>, window, cx| {
3705                                let mut items = Vec::with_capacity(range.end - range.start);
3706
3707                                for ix in range {
3708                                    match &this.entries.get(ix) {
3709                                        Some(GitListEntry::Status(entry)) => {
3710                                            items.push(this.render_entry(
3711                                                ix,
3712                                                entry,
3713                                                has_write_access,
3714                                                window,
3715                                                cx,
3716                                            ));
3717                                        }
3718                                        Some(GitListEntry::Header(header)) => {
3719                                            items.push(this.render_list_header(
3720                                                ix,
3721                                                header,
3722                                                has_write_access,
3723                                                window,
3724                                                cx,
3725                                            ));
3726                                        }
3727                                        None => {}
3728                                    }
3729                                }
3730
3731                                items
3732                            }),
3733                        )
3734                        .size_full()
3735                        .flex_grow()
3736                        .with_sizing_behavior(ListSizingBehavior::Auto)
3737                        .with_horizontal_sizing_behavior(
3738                            ListHorizontalSizingBehavior::Unconstrained,
3739                        )
3740                        .with_width_from_item(self.max_width_item_index)
3741                        .track_scroll(self.scroll_handle.clone()),
3742                    )
3743                    .on_mouse_down(
3744                        MouseButton::Right,
3745                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3746                            this.deploy_panel_context_menu(event.position, window, cx)
3747                        }),
3748                    )
3749                    .custom_scrollbars(
3750                        Scrollbars::for_settings::<GitPanelSettings>()
3751                            .tracked_scroll_handle(self.scroll_handle.clone())
3752                            .with_track_along(
3753                                ScrollAxes::Horizontal,
3754                                cx.theme().colors().panel_background,
3755                            ),
3756                        window,
3757                        cx,
3758                    ),
3759            )
3760    }
3761
3762    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3763        Label::new(label.into()).color(color).single_line()
3764    }
3765
3766    fn list_item_height(&self) -> Rems {
3767        rems(1.75)
3768    }
3769
3770    fn render_list_header(
3771        &self,
3772        ix: usize,
3773        header: &GitHeaderEntry,
3774        _: bool,
3775        _: &Window,
3776        _: &Context<Self>,
3777    ) -> AnyElement {
3778        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3779
3780        h_flex()
3781            .id(id)
3782            .h(self.list_item_height())
3783            .w_full()
3784            .items_end()
3785            .px(rems(0.75)) // ~12px
3786            .pb(rems(0.3125)) // ~ 5px
3787            .child(
3788                Label::new(header.title())
3789                    .color(Color::Muted)
3790                    .size(LabelSize::Small)
3791                    .line_height_style(LineHeightStyle::UiLabel)
3792                    .single_line(),
3793            )
3794            .into_any_element()
3795    }
3796
3797    pub fn load_commit_details(
3798        &self,
3799        sha: String,
3800        cx: &mut Context<Self>,
3801    ) -> Task<anyhow::Result<CommitDetails>> {
3802        let Some(repo) = self.active_repository.clone() else {
3803            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3804        };
3805        repo.update(cx, |repo, cx| {
3806            let show = repo.show(sha);
3807            cx.spawn(async move |_, _| show.await?)
3808        })
3809    }
3810
3811    fn deploy_entry_context_menu(
3812        &mut self,
3813        position: Point<Pixels>,
3814        ix: usize,
3815        window: &mut Window,
3816        cx: &mut Context<Self>,
3817    ) {
3818        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3819            return;
3820        };
3821        let stage_title = if entry.status.staging().is_fully_staged() {
3822            "Unstage File"
3823        } else {
3824            "Stage File"
3825        };
3826        let restore_title = if entry.status.is_created() {
3827            "Trash File"
3828        } else {
3829            "Restore File"
3830        };
3831        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3832            context_menu
3833                .context(self.focus_handle.clone())
3834                .action(stage_title, ToggleStaged.boxed_clone())
3835                .action(restore_title, git::RestoreFile::default().boxed_clone())
3836                .separator()
3837                .action("Open Diff", Confirm.boxed_clone())
3838                .action("Open File", SecondaryConfirm.boxed_clone())
3839        });
3840        self.selected_entry = Some(ix);
3841        self.set_context_menu(context_menu, position, window, cx);
3842    }
3843
3844    fn deploy_panel_context_menu(
3845        &mut self,
3846        position: Point<Pixels>,
3847        window: &mut Window,
3848        cx: &mut Context<Self>,
3849    ) {
3850        let context_menu = git_panel_context_menu(
3851            self.focus_handle.clone(),
3852            GitMenuState {
3853                has_tracked_changes: self.has_tracked_changes(),
3854                has_staged_changes: self.has_staged_changes(),
3855                has_unstaged_changes: self.has_unstaged_changes(),
3856                has_new_changes: self.new_count > 0,
3857                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3858                has_stash_items: self.stash_entries.entries.len() > 0,
3859            },
3860            window,
3861            cx,
3862        );
3863        self.set_context_menu(context_menu, position, window, cx);
3864    }
3865
3866    fn set_context_menu(
3867        &mut self,
3868        context_menu: Entity<ContextMenu>,
3869        position: Point<Pixels>,
3870        window: &Window,
3871        cx: &mut Context<Self>,
3872    ) {
3873        let subscription = cx.subscribe_in(
3874            &context_menu,
3875            window,
3876            |this, _, _: &DismissEvent, window, cx| {
3877                if this.context_menu.as_ref().is_some_and(|context_menu| {
3878                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3879                }) {
3880                    cx.focus_self(window);
3881                }
3882                this.context_menu.take();
3883                cx.notify();
3884            },
3885        );
3886        self.context_menu = Some((context_menu, position, subscription));
3887        cx.notify();
3888    }
3889
3890    fn render_entry(
3891        &self,
3892        ix: usize,
3893        entry: &GitStatusEntry,
3894        has_write_access: bool,
3895        window: &Window,
3896        cx: &Context<Self>,
3897    ) -> AnyElement {
3898        let display_name = entry.display_name();
3899
3900        let selected = self.selected_entry == Some(ix);
3901        let marked = self.marked_entries.contains(&ix);
3902        let status_style = GitPanelSettings::get_global(cx).status_style;
3903        let status = entry.status;
3904
3905        let has_conflict = status.is_conflicted();
3906        let is_modified = status.is_modified();
3907        let is_deleted = status.is_deleted();
3908
3909        let label_color = if status_style == StatusStyle::LabelColor {
3910            if has_conflict {
3911                Color::VersionControlConflict
3912            } else if is_modified {
3913                Color::VersionControlModified
3914            } else if is_deleted {
3915                // We don't want a bunch of red labels in the list
3916                Color::Disabled
3917            } else {
3918                Color::VersionControlAdded
3919            }
3920        } else {
3921            Color::Default
3922        };
3923
3924        let path_color = if status.is_deleted() {
3925            Color::Disabled
3926        } else {
3927            Color::Muted
3928        };
3929
3930        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3931        let checkbox_wrapper_id: ElementId =
3932            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3933        let checkbox_id: ElementId =
3934            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3935
3936        let entry_staging = self.entry_staging(entry);
3937        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3938        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
3939            is_staged = ToggleState::Selected;
3940        }
3941
3942        let handle = cx.weak_entity();
3943
3944        let selected_bg_alpha = 0.08;
3945        let marked_bg_alpha = 0.12;
3946        let state_opacity_step = 0.04;
3947
3948        let base_bg = match (selected, marked) {
3949            (true, true) => cx
3950                .theme()
3951                .status()
3952                .info
3953                .alpha(selected_bg_alpha + marked_bg_alpha),
3954            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3955            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3956            _ => cx.theme().colors().ghost_element_background,
3957        };
3958
3959        let hover_bg = if selected {
3960            cx.theme()
3961                .status()
3962                .info
3963                .alpha(selected_bg_alpha + state_opacity_step)
3964        } else {
3965            cx.theme().colors().ghost_element_hover
3966        };
3967
3968        let active_bg = if selected {
3969            cx.theme()
3970                .status()
3971                .info
3972                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3973        } else {
3974            cx.theme().colors().ghost_element_active
3975        };
3976
3977        h_flex()
3978            .id(id)
3979            .h(self.list_item_height())
3980            .w_full()
3981            .items_center()
3982            .border_1()
3983            .when(selected && self.focus_handle.is_focused(window), |el| {
3984                el.border_color(cx.theme().colors().border_focused)
3985            })
3986            .px(rems(0.75)) // ~12px
3987            .overflow_hidden()
3988            .flex_none()
3989            .gap_1p5()
3990            .bg(base_bg)
3991            .hover(|this| this.bg(hover_bg))
3992            .active(|this| this.bg(active_bg))
3993            .on_click({
3994                cx.listener(move |this, event: &ClickEvent, window, cx| {
3995                    this.selected_entry = Some(ix);
3996                    cx.notify();
3997                    if event.modifiers().secondary() {
3998                        this.open_file(&Default::default(), window, cx)
3999                    } else {
4000                        this.open_diff(&Default::default(), window, cx);
4001                        this.focus_handle.focus(window);
4002                    }
4003                })
4004            })
4005            .on_mouse_down(
4006                MouseButton::Right,
4007                move |event: &MouseDownEvent, window, cx| {
4008                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4009                    if event.button != MouseButton::Right {
4010                        return;
4011                    }
4012
4013                    let Some(this) = handle.upgrade() else {
4014                        return;
4015                    };
4016                    this.update(cx, |this, cx| {
4017                        this.deploy_entry_context_menu(event.position, ix, window, cx);
4018                    });
4019                    cx.stop_propagation();
4020                },
4021            )
4022            .child(
4023                div()
4024                    .id(checkbox_wrapper_id)
4025                    .flex_none()
4026                    .occlude()
4027                    .cursor_pointer()
4028                    .child(
4029                        Checkbox::new(checkbox_id, is_staged)
4030                            .disabled(!has_write_access)
4031                            .fill()
4032                            .elevation(ElevationIndex::Surface)
4033                            .on_click_ext({
4034                                let entry = entry.clone();
4035                                let this = cx.weak_entity();
4036                                move |_, click, window, cx| {
4037                                    this.update(cx, |this, cx| {
4038                                        if !has_write_access {
4039                                            return;
4040                                        }
4041                                        if click.modifiers().shift {
4042                                            this.stage_bulk(ix, cx);
4043                                        } else {
4044                                            this.toggle_staged_for_entry(
4045                                                &GitListEntry::Status(entry.clone()),
4046                                                window,
4047                                                cx,
4048                                            );
4049                                        }
4050                                        cx.stop_propagation();
4051                                    })
4052                                    .ok();
4053                                }
4054                            })
4055                            .tooltip(move |window, cx| {
4056                                let is_staged = entry_staging.is_fully_staged();
4057
4058                                let action = if is_staged { "Unstage" } else { "Stage" };
4059                                let tooltip_name = action.to_string();
4060
4061                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4062                            }),
4063                    ),
4064            )
4065            .child(git_status_icon(status))
4066            .child(
4067                h_flex()
4068                    .items_center()
4069                    .flex_1()
4070                    // .overflow_hidden()
4071                    .when_some(entry.parent_dir(), |this, parent| {
4072                        if !parent.is_empty() {
4073                            this.child(
4074                                self.entry_label(format!("{}/", parent), path_color)
4075                                    .when(status.is_deleted(), |this| this.strikethrough()),
4076                            )
4077                        } else {
4078                            this
4079                        }
4080                    })
4081                    .child(
4082                        self.entry_label(display_name, label_color)
4083                            .when(status.is_deleted(), |this| this.strikethrough()),
4084                    ),
4085            )
4086            .into_any_element()
4087    }
4088
4089    fn has_write_access(&self, cx: &App) -> bool {
4090        !self.project.read(cx).is_read_only(cx)
4091    }
4092
4093    pub fn amend_pending(&self) -> bool {
4094        self.amend_pending
4095    }
4096
4097    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4098        if value && !self.amend_pending {
4099            let current_message = self.commit_message_buffer(cx).read(cx).text();
4100            self.original_commit_message = if current_message.trim().is_empty() {
4101                None
4102            } else {
4103                Some(current_message)
4104            };
4105        } else if !value && self.amend_pending {
4106            let message = self.original_commit_message.take().unwrap_or_default();
4107            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4108                let start = buffer.anchor_before(0);
4109                let end = buffer.anchor_after(buffer.len());
4110                buffer.edit([(start..end, message)], None, cx);
4111            });
4112        }
4113
4114        self.amend_pending = value;
4115        self.serialize(cx);
4116        cx.notify();
4117    }
4118
4119    pub fn signoff_enabled(&self) -> bool {
4120        self.signoff_enabled
4121    }
4122
4123    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4124        self.signoff_enabled = value;
4125        self.serialize(cx);
4126        cx.notify();
4127    }
4128
4129    pub fn toggle_signoff_enabled(
4130        &mut self,
4131        _: &Signoff,
4132        _window: &mut Window,
4133        cx: &mut Context<Self>,
4134    ) {
4135        self.set_signoff_enabled(!self.signoff_enabled, cx);
4136    }
4137
4138    pub async fn load(
4139        workspace: WeakEntity<Workspace>,
4140        mut cx: AsyncWindowContext,
4141    ) -> anyhow::Result<Entity<Self>> {
4142        let serialized_panel = match workspace
4143            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4144            .ok()
4145            .flatten()
4146        {
4147            Some(serialization_key) => cx
4148                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4149                .await
4150                .context("loading git panel")
4151                .log_err()
4152                .flatten()
4153                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4154                .transpose()
4155                .log_err()
4156                .flatten(),
4157            None => None,
4158        };
4159
4160        workspace.update_in(&mut cx, |workspace, window, cx| {
4161            let panel = GitPanel::new(workspace, window, cx);
4162
4163            if let Some(serialized_panel) = serialized_panel {
4164                panel.update(cx, |panel, cx| {
4165                    panel.width = serialized_panel.width;
4166                    panel.amend_pending = serialized_panel.amend_pending;
4167                    panel.signoff_enabled = serialized_panel.signoff_enabled;
4168                    cx.notify();
4169                })
4170            }
4171
4172            panel
4173        })
4174    }
4175
4176    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4177        let Some(op) = self.bulk_staging.as_ref() else {
4178            return;
4179        };
4180        let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4181            return;
4182        };
4183        if let Some(entry) = self.entries.get(index)
4184            && let Some(entry) = entry.status_entry()
4185        {
4186            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4187        }
4188        if index < anchor_index {
4189            std::mem::swap(&mut index, &mut anchor_index);
4190        }
4191        let entries = self
4192            .entries
4193            .get(anchor_index..=index)
4194            .unwrap_or_default()
4195            .iter()
4196            .filter_map(|entry| entry.status_entry().cloned())
4197            .collect::<Vec<_>>();
4198        self.change_file_stage(true, entries, cx);
4199    }
4200
4201    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4202        let Some(repo) = self.active_repository.as_ref() else {
4203            return;
4204        };
4205        self.bulk_staging = Some(BulkStaging {
4206            repo_id: repo.read(cx).id,
4207            anchor: path,
4208        });
4209    }
4210
4211    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4212        self.set_amend_pending(!self.amend_pending, cx);
4213        if self.amend_pending {
4214            self.load_last_commit_message_if_empty(cx);
4215        }
4216    }
4217}
4218
4219impl Render for GitPanel {
4220    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4221        let project = self.project.read(cx);
4222        let has_entries = !self.entries.is_empty();
4223        let room = self
4224            .workspace
4225            .upgrade()
4226            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4227
4228        let has_write_access = self.has_write_access(cx);
4229
4230        let has_co_authors = room.is_some_and(|room| {
4231            self.load_local_committer(cx);
4232            let room = room.read(cx);
4233            room.remote_participants()
4234                .values()
4235                .any(|remote_participant| remote_participant.can_write())
4236        });
4237
4238        v_flex()
4239            .id("git_panel")
4240            .key_context(self.dispatch_context(window, cx))
4241            .track_focus(&self.focus_handle)
4242            .when(has_write_access && !project.is_read_only(cx), |this| {
4243                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4244                    .on_action(cx.listener(Self::stage_range))
4245                    .on_action(cx.listener(GitPanel::commit))
4246                    .on_action(cx.listener(GitPanel::amend))
4247                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4248                    .on_action(cx.listener(Self::stage_all))
4249                    .on_action(cx.listener(Self::unstage_all))
4250                    .on_action(cx.listener(Self::stage_selected))
4251                    .on_action(cx.listener(Self::unstage_selected))
4252                    .on_action(cx.listener(Self::restore_tracked_files))
4253                    .on_action(cx.listener(Self::revert_selected))
4254                    .on_action(cx.listener(Self::clean_all))
4255                    .on_action(cx.listener(Self::generate_commit_message_action))
4256                    .on_action(cx.listener(Self::stash_all))
4257                    .on_action(cx.listener(Self::stash_pop))
4258            })
4259            .on_action(cx.listener(Self::select_first))
4260            .on_action(cx.listener(Self::select_next))
4261            .on_action(cx.listener(Self::select_previous))
4262            .on_action(cx.listener(Self::select_last))
4263            .on_action(cx.listener(Self::close_panel))
4264            .on_action(cx.listener(Self::open_diff))
4265            .on_action(cx.listener(Self::open_file))
4266            .on_action(cx.listener(Self::focus_changes_list))
4267            .on_action(cx.listener(Self::focus_editor))
4268            .on_action(cx.listener(Self::expand_commit_editor))
4269            .when(has_write_access && has_co_authors, |git_panel| {
4270                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4271            })
4272            .on_action(cx.listener(Self::toggle_sort_by_path))
4273            .size_full()
4274            .overflow_hidden()
4275            .bg(cx.theme().colors().panel_background)
4276            .child(
4277                v_flex()
4278                    .size_full()
4279                    .children(self.render_panel_header(window, cx))
4280                    .map(|this| {
4281                        if has_entries {
4282                            this.child(self.render_entries(has_write_access, window, cx))
4283                        } else {
4284                            this.child(self.render_empty_state(cx).into_any_element())
4285                        }
4286                    })
4287                    .children(self.render_footer(window, cx))
4288                    .when(self.amend_pending, |this| {
4289                        this.child(self.render_pending_amend(cx))
4290                    })
4291                    .when(!self.amend_pending, |this| {
4292                        this.children(self.render_previous_commit(cx))
4293                    })
4294                    .into_any_element(),
4295            )
4296            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4297                deferred(
4298                    anchored()
4299                        .position(*position)
4300                        .anchor(Corner::TopLeft)
4301                        .child(menu.clone()),
4302                )
4303                .with_priority(1)
4304            }))
4305    }
4306}
4307
4308impl Focusable for GitPanel {
4309    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4310        if self.entries.is_empty() {
4311            self.commit_editor.focus_handle(cx)
4312        } else {
4313            self.focus_handle.clone()
4314        }
4315    }
4316}
4317
4318impl EventEmitter<Event> for GitPanel {}
4319
4320impl EventEmitter<PanelEvent> for GitPanel {}
4321
4322pub(crate) struct GitPanelAddon {
4323    pub(crate) workspace: WeakEntity<Workspace>,
4324}
4325
4326impl editor::Addon for GitPanelAddon {
4327    fn to_any(&self) -> &dyn std::any::Any {
4328        self
4329    }
4330
4331    fn render_buffer_header_controls(
4332        &self,
4333        excerpt_info: &ExcerptInfo,
4334        window: &Window,
4335        cx: &App,
4336    ) -> Option<AnyElement> {
4337        let file = excerpt_info.buffer.file()?;
4338        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4339
4340        git_panel
4341            .read(cx)
4342            .render_buffer_header_controls(&git_panel, file, window, cx)
4343    }
4344}
4345
4346impl Panel for GitPanel {
4347    fn persistent_name() -> &'static str {
4348        "GitPanel"
4349    }
4350
4351    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4352        GitPanelSettings::get_global(cx).dock
4353    }
4354
4355    fn position_is_valid(&self, position: DockPosition) -> bool {
4356        matches!(position, DockPosition::Left | DockPosition::Right)
4357    }
4358
4359    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4360        settings::update_settings_file::<GitPanelSettings>(
4361            self.fs.clone(),
4362            cx,
4363            move |settings, _| settings.dock = Some(position),
4364        );
4365    }
4366
4367    fn size(&self, _: &Window, cx: &App) -> Pixels {
4368        self.width
4369            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4370    }
4371
4372    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4373        self.width = size;
4374        self.serialize(cx);
4375        cx.notify();
4376    }
4377
4378    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4379        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4380    }
4381
4382    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4383        Some("Git Panel")
4384    }
4385
4386    fn toggle_action(&self) -> Box<dyn Action> {
4387        Box::new(ToggleFocus)
4388    }
4389
4390    fn activation_priority(&self) -> u32 {
4391        2
4392    }
4393}
4394
4395impl PanelHeader for GitPanel {}
4396
4397struct GitPanelMessageTooltip {
4398    commit_tooltip: Option<Entity<CommitTooltip>>,
4399}
4400
4401impl GitPanelMessageTooltip {
4402    fn new(
4403        git_panel: Entity<GitPanel>,
4404        sha: SharedString,
4405        repository: Entity<Repository>,
4406        window: &mut Window,
4407        cx: &mut App,
4408    ) -> Entity<Self> {
4409        cx.new(|cx| {
4410            cx.spawn_in(window, async move |this, cx| {
4411                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4412                    (
4413                        git_panel.load_commit_details(sha.to_string(), cx),
4414                        git_panel.workspace.clone(),
4415                    )
4416                })?;
4417                let details = details.await?;
4418
4419                let commit_details = crate::commit_tooltip::CommitDetails {
4420                    sha: details.sha.clone(),
4421                    author_name: details.author_name.clone(),
4422                    author_email: details.author_email.clone(),
4423                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4424                    message: Some(ParsedCommitMessage {
4425                        message: details.message,
4426                        ..Default::default()
4427                    }),
4428                };
4429
4430                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4431                    this.commit_tooltip = Some(cx.new(move |cx| {
4432                        CommitTooltip::new(commit_details, repository, workspace, cx)
4433                    }));
4434                    cx.notify();
4435                })
4436            })
4437            .detach();
4438
4439            Self {
4440                commit_tooltip: None,
4441            }
4442        })
4443    }
4444}
4445
4446impl Render for GitPanelMessageTooltip {
4447    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4448        if let Some(commit_tooltip) = &self.commit_tooltip {
4449            commit_tooltip.clone().into_any_element()
4450        } else {
4451            gpui::Empty.into_any_element()
4452        }
4453    }
4454}
4455
4456#[derive(IntoElement, RegisterComponent)]
4457pub struct PanelRepoFooter {
4458    active_repository: SharedString,
4459    branch: Option<Branch>,
4460    head_commit: Option<CommitDetails>,
4461
4462    // Getting a GitPanel in previews will be difficult.
4463    //
4464    // For now just take an option here, and we won't bind handlers to buttons in previews.
4465    git_panel: Option<Entity<GitPanel>>,
4466}
4467
4468impl PanelRepoFooter {
4469    pub fn new(
4470        active_repository: SharedString,
4471        branch: Option<Branch>,
4472        head_commit: Option<CommitDetails>,
4473        git_panel: Option<Entity<GitPanel>>,
4474    ) -> Self {
4475        Self {
4476            active_repository,
4477            branch,
4478            head_commit,
4479            git_panel,
4480        }
4481    }
4482
4483    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4484        Self {
4485            active_repository,
4486            branch,
4487            head_commit: None,
4488            git_panel: None,
4489        }
4490    }
4491}
4492
4493impl RenderOnce for PanelRepoFooter {
4494    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4495        let project = self
4496            .git_panel
4497            .as_ref()
4498            .map(|panel| panel.read(cx).project.clone());
4499
4500        let repo = self
4501            .git_panel
4502            .as_ref()
4503            .and_then(|panel| panel.read(cx).active_repository.clone());
4504
4505        let single_repo = project
4506            .as_ref()
4507            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4508            .unwrap_or(true);
4509
4510        const MAX_BRANCH_LEN: usize = 16;
4511        const MAX_REPO_LEN: usize = 16;
4512        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4513        const MAX_SHORT_SHA_LEN: usize = 8;
4514
4515        let branch_name = self
4516            .branch
4517            .as_ref()
4518            .map(|branch| branch.name().to_owned())
4519            .or_else(|| {
4520                self.head_commit.as_ref().map(|commit| {
4521                    commit
4522                        .sha
4523                        .chars()
4524                        .take(MAX_SHORT_SHA_LEN)
4525                        .collect::<String>()
4526                })
4527            })
4528            .unwrap_or_else(|| " (no branch)".to_owned());
4529        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4530
4531        let active_repo_name = self.active_repository.clone();
4532
4533        let branch_actual_len = branch_name.len();
4534        let repo_actual_len = active_repo_name.len();
4535
4536        // ideally, show the whole branch and repo names but
4537        // when we can't, use a budget to allocate space between the two
4538        let (repo_display_len, branch_display_len) =
4539            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4540                (repo_actual_len, branch_actual_len)
4541            } else if branch_actual_len <= MAX_BRANCH_LEN {
4542                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4543                (repo_space, branch_actual_len)
4544            } else if repo_actual_len <= MAX_REPO_LEN {
4545                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4546                (repo_actual_len, branch_space)
4547            } else {
4548                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4549            };
4550
4551        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4552            active_repo_name.to_string()
4553        } else {
4554            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4555        };
4556
4557        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4558            branch_name
4559        } else {
4560            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4561        };
4562
4563        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4564            .style(ButtonStyle::Transparent)
4565            .size(ButtonSize::None)
4566            .label_size(LabelSize::Small)
4567            .color(Color::Muted);
4568
4569        let repo_selector = PopoverMenu::new("repository-switcher")
4570            .menu({
4571                let project = project;
4572                move |window, cx| {
4573                    let project = project.clone()?;
4574                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4575                }
4576            })
4577            .trigger_with_tooltip(
4578                repo_selector_trigger.disabled(single_repo).truncate(true),
4579                Tooltip::text("Switch Active Repository"),
4580            )
4581            .anchor(Corner::BottomLeft)
4582            .into_any_element();
4583
4584        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4585            .style(ButtonStyle::Transparent)
4586            .size(ButtonSize::None)
4587            .label_size(LabelSize::Small)
4588            .truncate(true)
4589            .tooltip(Tooltip::for_action_title(
4590                "Switch Branch",
4591                &zed_actions::git::Switch,
4592            ))
4593            .on_click(|_, window, cx| {
4594                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4595            });
4596
4597        let branch_selector = PopoverMenu::new("popover-button")
4598            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4599            .trigger_with_tooltip(
4600                branch_selector_button,
4601                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4602            )
4603            .anchor(Corner::BottomLeft)
4604            .offset(gpui::Point {
4605                x: px(0.0),
4606                y: px(-2.0),
4607            });
4608
4609        h_flex()
4610            .w_full()
4611            .px_2()
4612            .h(px(36.))
4613            .items_center()
4614            .justify_between()
4615            .gap_1()
4616            .child(
4617                h_flex()
4618                    .flex_1()
4619                    .overflow_hidden()
4620                    .items_center()
4621                    .child(
4622                        div().child(
4623                            Icon::new(IconName::GitBranchAlt)
4624                                .size(IconSize::Small)
4625                                .color(if single_repo {
4626                                    Color::Disabled
4627                                } else {
4628                                    Color::Muted
4629                                }),
4630                        ),
4631                    )
4632                    .child(repo_selector)
4633                    .when(show_separator, |this| {
4634                        this.child(
4635                            div()
4636                                .text_color(cx.theme().colors().text_muted)
4637                                .text_sm()
4638                                .child("/"),
4639                        )
4640                    })
4641                    .child(branch_selector),
4642            )
4643            .children(if let Some(git_panel) = self.git_panel {
4644                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4645            } else {
4646                None
4647            })
4648    }
4649}
4650
4651impl Component for PanelRepoFooter {
4652    fn scope() -> ComponentScope {
4653        ComponentScope::VersionControl
4654    }
4655
4656    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4657        let unknown_upstream = None;
4658        let no_remote_upstream = Some(UpstreamTracking::Gone);
4659        let ahead_of_upstream = Some(
4660            UpstreamTrackingStatus {
4661                ahead: 2,
4662                behind: 0,
4663            }
4664            .into(),
4665        );
4666        let behind_upstream = Some(
4667            UpstreamTrackingStatus {
4668                ahead: 0,
4669                behind: 2,
4670            }
4671            .into(),
4672        );
4673        let ahead_and_behind_upstream = Some(
4674            UpstreamTrackingStatus {
4675                ahead: 3,
4676                behind: 1,
4677            }
4678            .into(),
4679        );
4680
4681        let not_ahead_or_behind_upstream = Some(
4682            UpstreamTrackingStatus {
4683                ahead: 0,
4684                behind: 0,
4685            }
4686            .into(),
4687        );
4688
4689        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4690            Branch {
4691                is_head: true,
4692                ref_name: "some-branch".into(),
4693                upstream: upstream.map(|tracking| Upstream {
4694                    ref_name: "origin/some-branch".into(),
4695                    tracking,
4696                }),
4697                most_recent_commit: Some(CommitSummary {
4698                    sha: "abc123".into(),
4699                    subject: "Modify stuff".into(),
4700                    commit_timestamp: 1710932954,
4701                    author_name: "John Doe".into(),
4702                    has_parent: true,
4703                }),
4704            }
4705        }
4706
4707        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4708            Branch {
4709                is_head: true,
4710                ref_name: branch_name.to_string().into(),
4711                upstream: upstream.map(|tracking| Upstream {
4712                    ref_name: format!("zed/{}", branch_name).into(),
4713                    tracking,
4714                }),
4715                most_recent_commit: Some(CommitSummary {
4716                    sha: "abc123".into(),
4717                    subject: "Modify stuff".into(),
4718                    commit_timestamp: 1710932954,
4719                    author_name: "John Doe".into(),
4720                    has_parent: true,
4721                }),
4722            }
4723        }
4724
4725        fn active_repository(id: usize) -> SharedString {
4726            format!("repo-{}", id).into()
4727        }
4728
4729        let example_width = px(340.);
4730        Some(
4731            v_flex()
4732                .gap_6()
4733                .w_full()
4734                .flex_none()
4735                .children(vec![
4736                    example_group_with_title(
4737                        "Action Button States",
4738                        vec![
4739                            single_example(
4740                                "No Branch",
4741                                div()
4742                                    .w(example_width)
4743                                    .overflow_hidden()
4744                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
4745                                    .into_any_element(),
4746                            ),
4747                            single_example(
4748                                "Remote status unknown",
4749                                div()
4750                                    .w(example_width)
4751                                    .overflow_hidden()
4752                                    .child(PanelRepoFooter::new_preview(
4753                                        active_repository(2),
4754                                        Some(branch(unknown_upstream)),
4755                                    ))
4756                                    .into_any_element(),
4757                            ),
4758                            single_example(
4759                                "No Remote Upstream",
4760                                div()
4761                                    .w(example_width)
4762                                    .overflow_hidden()
4763                                    .child(PanelRepoFooter::new_preview(
4764                                        active_repository(3),
4765                                        Some(branch(no_remote_upstream)),
4766                                    ))
4767                                    .into_any_element(),
4768                            ),
4769                            single_example(
4770                                "Not Ahead or Behind",
4771                                div()
4772                                    .w(example_width)
4773                                    .overflow_hidden()
4774                                    .child(PanelRepoFooter::new_preview(
4775                                        active_repository(4),
4776                                        Some(branch(not_ahead_or_behind_upstream)),
4777                                    ))
4778                                    .into_any_element(),
4779                            ),
4780                            single_example(
4781                                "Behind remote",
4782                                div()
4783                                    .w(example_width)
4784                                    .overflow_hidden()
4785                                    .child(PanelRepoFooter::new_preview(
4786                                        active_repository(5),
4787                                        Some(branch(behind_upstream)),
4788                                    ))
4789                                    .into_any_element(),
4790                            ),
4791                            single_example(
4792                                "Ahead of remote",
4793                                div()
4794                                    .w(example_width)
4795                                    .overflow_hidden()
4796                                    .child(PanelRepoFooter::new_preview(
4797                                        active_repository(6),
4798                                        Some(branch(ahead_of_upstream)),
4799                                    ))
4800                                    .into_any_element(),
4801                            ),
4802                            single_example(
4803                                "Ahead and behind remote",
4804                                div()
4805                                    .w(example_width)
4806                                    .overflow_hidden()
4807                                    .child(PanelRepoFooter::new_preview(
4808                                        active_repository(7),
4809                                        Some(branch(ahead_and_behind_upstream)),
4810                                    ))
4811                                    .into_any_element(),
4812                            ),
4813                        ],
4814                    )
4815                    .grow()
4816                    .vertical(),
4817                ])
4818                .children(vec![
4819                    example_group_with_title(
4820                        "Labels",
4821                        vec![
4822                            single_example(
4823                                "Short Branch & Repo",
4824                                div()
4825                                    .w(example_width)
4826                                    .overflow_hidden()
4827                                    .child(PanelRepoFooter::new_preview(
4828                                        SharedString::from("zed"),
4829                                        Some(custom("main", behind_upstream)),
4830                                    ))
4831                                    .into_any_element(),
4832                            ),
4833                            single_example(
4834                                "Long Branch",
4835                                div()
4836                                    .w(example_width)
4837                                    .overflow_hidden()
4838                                    .child(PanelRepoFooter::new_preview(
4839                                        SharedString::from("zed"),
4840                                        Some(custom(
4841                                            "redesign-and-update-git-ui-list-entry-style",
4842                                            behind_upstream,
4843                                        )),
4844                                    ))
4845                                    .into_any_element(),
4846                            ),
4847                            single_example(
4848                                "Long Repo",
4849                                div()
4850                                    .w(example_width)
4851                                    .overflow_hidden()
4852                                    .child(PanelRepoFooter::new_preview(
4853                                        SharedString::from("zed-industries-community-examples"),
4854                                        Some(custom("gpui", ahead_of_upstream)),
4855                                    ))
4856                                    .into_any_element(),
4857                            ),
4858                            single_example(
4859                                "Long Repo & Branch",
4860                                div()
4861                                    .w(example_width)
4862                                    .overflow_hidden()
4863                                    .child(PanelRepoFooter::new_preview(
4864                                        SharedString::from("zed-industries-community-examples"),
4865                                        Some(custom(
4866                                            "redesign-and-update-git-ui-list-entry-style",
4867                                            behind_upstream,
4868                                        )),
4869                                    ))
4870                                    .into_any_element(),
4871                            ),
4872                            single_example(
4873                                "Uppercase Repo",
4874                                div()
4875                                    .w(example_width)
4876                                    .overflow_hidden()
4877                                    .child(PanelRepoFooter::new_preview(
4878                                        SharedString::from("LICENSES"),
4879                                        Some(custom("main", ahead_of_upstream)),
4880                                    ))
4881                                    .into_any_element(),
4882                            ),
4883                            single_example(
4884                                "Uppercase Branch",
4885                                div()
4886                                    .w(example_width)
4887                                    .overflow_hidden()
4888                                    .child(PanelRepoFooter::new_preview(
4889                                        SharedString::from("zed"),
4890                                        Some(custom("update-README", behind_upstream)),
4891                                    ))
4892                                    .into_any_element(),
4893                            ),
4894                        ],
4895                    )
4896                    .grow()
4897                    .vertical(),
4898                ])
4899                .into_any_element(),
4900        )
4901    }
4902}
4903
4904#[cfg(test)]
4905mod tests {
4906    use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
4907    use gpui::{TestAppContext, VisualTestContext};
4908    use project::{FakeFs, WorktreeSettings};
4909    use serde_json::json;
4910    use settings::SettingsStore;
4911    use theme::LoadThemes;
4912    use util::path;
4913
4914    use super::*;
4915
4916    fn init_test(cx: &mut gpui::TestAppContext) {
4917        zlog::init_test();
4918
4919        cx.update(|cx| {
4920            let settings_store = SettingsStore::test(cx);
4921            cx.set_global(settings_store);
4922            AgentSettings::register(cx);
4923            WorktreeSettings::register(cx);
4924            workspace::init_settings(cx);
4925            theme::init(LoadThemes::JustBase, cx);
4926            language::init(cx);
4927            editor::init(cx);
4928            Project::init_settings(cx);
4929            crate::init(cx);
4930        });
4931    }
4932
4933    #[gpui::test]
4934    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4935        init_test(cx);
4936        let fs = FakeFs::new(cx.background_executor.clone());
4937        fs.insert_tree(
4938            "/root",
4939            json!({
4940                "zed": {
4941                    ".git": {},
4942                    "crates": {
4943                        "gpui": {
4944                            "gpui.rs": "fn main() {}"
4945                        },
4946                        "util": {
4947                            "util.rs": "fn do_it() {}"
4948                        }
4949                    }
4950                },
4951            }),
4952        )
4953        .await;
4954
4955        fs.set_status_for_repo(
4956            Path::new(path!("/root/zed/.git")),
4957            &[
4958                (
4959                    Path::new("crates/gpui/gpui.rs"),
4960                    StatusCode::Modified.worktree(),
4961                ),
4962                (
4963                    Path::new("crates/util/util.rs"),
4964                    StatusCode::Modified.worktree(),
4965                ),
4966            ],
4967        );
4968
4969        let project =
4970            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4971        let workspace =
4972            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4973        let cx = &mut VisualTestContext::from_window(*workspace, cx);
4974
4975        cx.read(|cx| {
4976            project
4977                .read(cx)
4978                .worktrees(cx)
4979                .next()
4980                .unwrap()
4981                .read(cx)
4982                .as_local()
4983                .unwrap()
4984                .scan_complete()
4985        })
4986        .await;
4987
4988        cx.executor().run_until_parked();
4989
4990        let panel = workspace.update(cx, GitPanel::new).unwrap();
4991
4992        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4993            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4994        });
4995        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4996        handle.await;
4997
4998        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
4999        pretty_assertions::assert_eq!(
5000            entries,
5001            [
5002                GitListEntry::Header(GitHeaderEntry {
5003                    header: Section::Tracked
5004                }),
5005                GitListEntry::Status(GitStatusEntry {
5006                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5007                    repo_path: "crates/gpui/gpui.rs".into(),
5008                    status: StatusCode::Modified.worktree(),
5009                    staging: StageStatus::Unstaged,
5010                }),
5011                GitListEntry::Status(GitStatusEntry {
5012                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5013                    repo_path: "crates/util/util.rs".into(),
5014                    status: StatusCode::Modified.worktree(),
5015                    staging: StageStatus::Unstaged,
5016                },),
5017            ],
5018        );
5019
5020        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5021            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5022        });
5023        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5024        handle.await;
5025        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5026        pretty_assertions::assert_eq!(
5027            entries,
5028            [
5029                GitListEntry::Header(GitHeaderEntry {
5030                    header: Section::Tracked
5031                }),
5032                GitListEntry::Status(GitStatusEntry {
5033                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5034                    repo_path: "crates/gpui/gpui.rs".into(),
5035                    status: StatusCode::Modified.worktree(),
5036                    staging: StageStatus::Unstaged,
5037                }),
5038                GitListEntry::Status(GitStatusEntry {
5039                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
5040                    repo_path: "crates/util/util.rs".into(),
5041                    status: StatusCode::Modified.worktree(),
5042                    staging: StageStatus::Unstaged,
5043                },),
5044            ],
5045        );
5046    }
5047
5048    #[gpui::test]
5049    async fn test_bulk_staging(cx: &mut TestAppContext) {
5050        use GitListEntry::*;
5051
5052        init_test(cx);
5053        let fs = FakeFs::new(cx.background_executor.clone());
5054        fs.insert_tree(
5055            "/root",
5056            json!({
5057                "project": {
5058                    ".git": {},
5059                    "src": {
5060                        "main.rs": "fn main() {}",
5061                        "lib.rs": "pub fn hello() {}",
5062                        "utils.rs": "pub fn util() {}"
5063                    },
5064                    "tests": {
5065                        "test.rs": "fn test() {}"
5066                    },
5067                    "new_file.txt": "new content",
5068                    "another_new.rs": "// new file",
5069                    "conflict.txt": "conflicted content"
5070                }
5071            }),
5072        )
5073        .await;
5074
5075        fs.set_status_for_repo(
5076            Path::new(path!("/root/project/.git")),
5077            &[
5078                (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5079                (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5080                (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5081                (Path::new("new_file.txt"), FileStatus::Untracked),
5082                (Path::new("another_new.rs"), FileStatus::Untracked),
5083                (Path::new("src/utils.rs"), FileStatus::Untracked),
5084                (
5085                    Path::new("conflict.txt"),
5086                    UnmergedStatus {
5087                        first_head: UnmergedStatusCode::Updated,
5088                        second_head: UnmergedStatusCode::Updated,
5089                    }
5090                    .into(),
5091                ),
5092            ],
5093        );
5094
5095        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5096        let workspace =
5097            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5098        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5099
5100        cx.read(|cx| {
5101            project
5102                .read(cx)
5103                .worktrees(cx)
5104                .next()
5105                .unwrap()
5106                .read(cx)
5107                .as_local()
5108                .unwrap()
5109                .scan_complete()
5110        })
5111        .await;
5112
5113        cx.executor().run_until_parked();
5114
5115        let panel = workspace.update(cx, GitPanel::new).unwrap();
5116
5117        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5118            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5119        });
5120        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5121        handle.await;
5122
5123        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5124        #[rustfmt::skip]
5125        pretty_assertions::assert_matches!(
5126            entries.as_slice(),
5127            &[
5128                Header(GitHeaderEntry { header: Section::Conflict }),
5129                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5130                Header(GitHeaderEntry { header: Section::Tracked }),
5131                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5132                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5133                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5134                Header(GitHeaderEntry { header: Section::New }),
5135                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5136                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5137                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5138            ],
5139        );
5140
5141        let second_status_entry = entries[3].clone();
5142        panel.update_in(cx, |panel, window, cx| {
5143            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5144        });
5145
5146        panel.update_in(cx, |panel, window, cx| {
5147            panel.selected_entry = Some(7);
5148            panel.stage_range(&git::StageRange, window, cx);
5149        });
5150
5151        cx.read(|cx| {
5152            project
5153                .read(cx)
5154                .worktrees(cx)
5155                .next()
5156                .unwrap()
5157                .read(cx)
5158                .as_local()
5159                .unwrap()
5160                .scan_complete()
5161        })
5162        .await;
5163
5164        cx.executor().run_until_parked();
5165
5166        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5167            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5168        });
5169        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5170        handle.await;
5171
5172        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5173        #[rustfmt::skip]
5174        pretty_assertions::assert_matches!(
5175            entries.as_slice(),
5176            &[
5177                Header(GitHeaderEntry { header: Section::Conflict }),
5178                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5179                Header(GitHeaderEntry { header: Section::Tracked }),
5180                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5181                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5182                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5183                Header(GitHeaderEntry { header: Section::New }),
5184                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5185                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5186                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5187            ],
5188        );
5189
5190        let third_status_entry = entries[4].clone();
5191        panel.update_in(cx, |panel, window, cx| {
5192            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5193        });
5194
5195        panel.update_in(cx, |panel, window, cx| {
5196            panel.selected_entry = Some(9);
5197            panel.stage_range(&git::StageRange, window, cx);
5198        });
5199
5200        cx.read(|cx| {
5201            project
5202                .read(cx)
5203                .worktrees(cx)
5204                .next()
5205                .unwrap()
5206                .read(cx)
5207                .as_local()
5208                .unwrap()
5209                .scan_complete()
5210        })
5211        .await;
5212
5213        cx.executor().run_until_parked();
5214
5215        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5216            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5217        });
5218        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5219        handle.await;
5220
5221        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5222        #[rustfmt::skip]
5223        pretty_assertions::assert_matches!(
5224            entries.as_slice(),
5225            &[
5226                Header(GitHeaderEntry { header: Section::Conflict }),
5227                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5228                Header(GitHeaderEntry { header: Section::Tracked }),
5229                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5230                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5231                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5232                Header(GitHeaderEntry { header: Section::New }),
5233                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5234                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5235                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5236            ],
5237        );
5238    }
5239
5240    #[gpui::test]
5241    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5242        init_test(cx);
5243        let fs = FakeFs::new(cx.background_executor.clone());
5244        fs.insert_tree(
5245            "/root",
5246            json!({
5247                "project": {
5248                    ".git": {},
5249                    "src": {
5250                        "main.rs": "fn main() {}"
5251                    }
5252                }
5253            }),
5254        )
5255        .await;
5256
5257        fs.set_status_for_repo(
5258            Path::new(path!("/root/project/.git")),
5259            &[(Path::new("src/main.rs"), StatusCode::Modified.worktree())],
5260        );
5261
5262        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5263        let workspace =
5264            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5265        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5266
5267        let panel = workspace.update(cx, GitPanel::new).unwrap();
5268
5269        // Test: User has commit message, enables amend (saves message), then disables (restores message)
5270        panel.update(cx, |panel, cx| {
5271            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5272                let start = buffer.anchor_before(0);
5273                let end = buffer.anchor_after(buffer.len());
5274                buffer.edit([(start..end, "Initial commit message")], None, cx);
5275            });
5276
5277            panel.set_amend_pending(true, cx);
5278            assert!(panel.original_commit_message.is_some());
5279
5280            panel.set_amend_pending(false, cx);
5281            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5282            assert_eq!(current_message, "Initial commit message");
5283            assert!(panel.original_commit_message.is_none());
5284        });
5285
5286        // Test: User has empty commit message, enables amend, then disables (clears message)
5287        panel.update(cx, |panel, cx| {
5288            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5289                let start = buffer.anchor_before(0);
5290                let end = buffer.anchor_after(buffer.len());
5291                buffer.edit([(start..end, "")], None, cx);
5292            });
5293
5294            panel.set_amend_pending(true, cx);
5295            assert!(panel.original_commit_message.is_none());
5296
5297            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5298                let start = buffer.anchor_before(0);
5299                let end = buffer.anchor_after(buffer.len());
5300                buffer.edit([(start..end, "Previous commit message")], None, cx);
5301            });
5302
5303            panel.set_amend_pending(false, cx);
5304            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5305            assert_eq!(current_message, "");
5306        });
5307    }
5308}