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