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