git_panel.rs

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