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