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