git_panel.rs

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