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