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    ButtonLike, Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, PopoverMenu, ScrollAxes,
  62    Scrollbars, SplitButton, Tooltip, WithScrollbar, prelude::*,
  63};
  64use util::paths::PathStyle;
  65use util::{ResultExt, TryFutureExt, maybe};
  66use workspace::SERIALIZATION_THROTTLE_TIME;
  67
  68use cloud_llm_client::CompletionIntent;
  69use workspace::{
  70    Workspace,
  71    dock::{DockPosition, Panel, PanelEvent},
  72    notifications::{DetachAndPromptErr, ErrorMessagePrompt, NotificationId},
  73};
  74
  75actions!(
  76    git_panel,
  77    [
  78        /// Closes the git panel.
  79        Close,
  80        /// Toggles focus on the git panel.
  81        ToggleFocus,
  82        /// Opens the git panel menu.
  83        OpenMenu,
  84        /// Focuses on the commit message editor.
  85        FocusEditor,
  86        /// Focuses on the changes list.
  87        FocusChanges,
  88        /// Toggles automatic co-author suggestions.
  89        ToggleFillCoAuthors,
  90        /// Toggles sorting entries by path vs status.
  91        ToggleSortByPath,
  92    ]
  93);
  94
  95fn prompt<T>(
  96    msg: &str,
  97    detail: Option<&str>,
  98    window: &mut Window,
  99    cx: &mut App,
 100) -> Task<anyhow::Result<T>>
 101where
 102    T: IntoEnumIterator + VariantNames + 'static,
 103{
 104    let rx = window.prompt(PromptLevel::Info, msg, detail, T::VARIANTS, cx);
 105    cx.spawn(async move |_| Ok(T::iter().nth(rx.await?).unwrap()))
 106}
 107
 108#[derive(strum::EnumIter, strum::VariantNames)]
 109#[strum(serialize_all = "title_case")]
 110enum TrashCancel {
 111    Trash,
 112    Cancel,
 113}
 114
 115struct GitMenuState {
 116    has_tracked_changes: bool,
 117    has_staged_changes: bool,
 118    has_unstaged_changes: bool,
 119    has_new_changes: bool,
 120    sort_by_path: bool,
 121    has_stash_items: bool,
 122}
 123
 124fn git_panel_context_menu(
 125    focus_handle: FocusHandle,
 126    state: GitMenuState,
 127    window: &mut Window,
 128    cx: &mut App,
 129) -> Entity<ContextMenu> {
 130    ContextMenu::build(window, cx, move |context_menu, _, _| {
 131        context_menu
 132            .context(focus_handle)
 133            .action_disabled_when(
 134                !state.has_unstaged_changes,
 135                "Stage All",
 136                StageAll.boxed_clone(),
 137            )
 138            .action_disabled_when(
 139                !state.has_staged_changes,
 140                "Unstage All",
 141                UnstageAll.boxed_clone(),
 142            )
 143            .separator()
 144            .action_disabled_when(
 145                !(state.has_new_changes || state.has_tracked_changes),
 146                "Stash All",
 147                StashAll.boxed_clone(),
 148            )
 149            .action_disabled_when(!state.has_stash_items, "Stash Pop", StashPop.boxed_clone())
 150            .action("View Stash", zed_actions::git::ViewStash.boxed_clone())
 151            .separator()
 152            .action("Open Diff", project_diff::Diff.boxed_clone())
 153            .separator()
 154            .action_disabled_when(
 155                !state.has_tracked_changes,
 156                "Discard Tracked Changes",
 157                RestoreTrackedFiles.boxed_clone(),
 158            )
 159            .action_disabled_when(
 160                !state.has_new_changes,
 161                "Trash Untracked Files",
 162                TrashUntrackedFiles.boxed_clone(),
 163            )
 164            .separator()
 165            .entry(
 166                if state.sort_by_path {
 167                    "Sort by Status"
 168                } else {
 169                    "Sort by Path"
 170                },
 171                Some(Box::new(ToggleSortByPath)),
 172                move |window, cx| window.dispatch_action(Box::new(ToggleSortByPath), cx),
 173            )
 174    })
 175}
 176
 177const GIT_PANEL_KEY: &str = "GitPanel";
 178
 179const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
 180
 181pub fn register(workspace: &mut Workspace) {
 182    workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
 183        workspace.toggle_panel_focus::<GitPanel>(window, cx);
 184    });
 185    workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
 186        CommitModal::toggle(workspace, None, window, cx)
 187    });
 188}
 189
 190#[derive(Debug, Clone)]
 191pub enum Event {
 192    Focus,
 193}
 194
 195#[derive(Serialize, Deserialize)]
 196struct SerializedGitPanel {
 197    width: Option<Pixels>,
 198    #[serde(default)]
 199    amend_pending: bool,
 200    #[serde(default)]
 201    signoff_enabled: bool,
 202}
 203
 204#[derive(Debug, PartialEq, Eq, Clone, Copy)]
 205enum Section {
 206    Conflict,
 207    Tracked,
 208    New,
 209}
 210
 211#[derive(Debug, PartialEq, Eq, Clone)]
 212struct GitHeaderEntry {
 213    header: Section,
 214}
 215
 216impl GitHeaderEntry {
 217    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
 218        let this = &self.header;
 219        let status = status_entry.status;
 220        match this {
 221            Section::Conflict => {
 222                repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path)
 223            }
 224            Section::Tracked => !status.is_created(),
 225            Section::New => status.is_created(),
 226        }
 227    }
 228    pub fn title(&self) -> &'static str {
 229        match self.header {
 230            Section::Conflict => "Conflicts",
 231            Section::Tracked => "Tracked",
 232            Section::New => "Untracked",
 233        }
 234    }
 235}
 236
 237#[derive(Debug, PartialEq, Eq, Clone)]
 238enum GitListEntry {
 239    Status(GitStatusEntry),
 240    Header(GitHeaderEntry),
 241}
 242
 243impl GitListEntry {
 244    fn status_entry(&self) -> Option<&GitStatusEntry> {
 245        match self {
 246            GitListEntry::Status(entry) => Some(entry),
 247            _ => None,
 248        }
 249    }
 250}
 251
 252#[derive(Debug, PartialEq, Eq, Clone)]
 253pub struct GitStatusEntry {
 254    pub(crate) repo_path: RepoPath,
 255    pub(crate) status: FileStatus,
 256    pub(crate) staging: StageStatus,
 257}
 258
 259impl GitStatusEntry {
 260    fn display_name(&self, path_style: PathStyle) -> String {
 261        self.repo_path
 262            .file_name()
 263            .map(|name| name.to_owned())
 264            .unwrap_or_else(|| self.repo_path.display(path_style).to_string())
 265    }
 266
 267    fn parent_dir(&self, path_style: PathStyle) -> Option<String> {
 268        self.repo_path
 269            .parent()
 270            .map(|parent| parent.display(path_style).to_string())
 271    }
 272}
 273
 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        let label_color = if self.pending_commit.is_some() {
3509            Color::Disabled
3510        } else {
3511            Color::Default
3512        };
3513
3514        div()
3515            .id("commit-wrapper")
3516            .on_hover(cx.listener(move |this, hovered, _, cx| {
3517                this.show_placeholders =
3518                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3519                cx.notify()
3520            }))
3521            .child(SplitButton::new(
3522                ButtonLike::new_rounded_left(ElementId::Name(
3523                    format!("split-button-left-{}", title).into(),
3524                ))
3525                .layer(ElevationIndex::ModalSurface)
3526                .size(ButtonSize::Compact)
3527                .child(
3528                    Label::new(title)
3529                        .size(LabelSize::Small)
3530                        .color(label_color)
3531                        .mr_0p5(),
3532                )
3533                .on_click({
3534                    let git_panel = cx.weak_entity();
3535                    move |_, window, cx| {
3536                        telemetry::event!("Git Committed", source = "Git Panel");
3537                        git_panel
3538                            .update(cx, |git_panel, cx| {
3539                                git_panel.commit_changes(
3540                                    CommitOptions { amend, signoff },
3541                                    window,
3542                                    cx,
3543                                );
3544                            })
3545                            .ok();
3546                    }
3547                })
3548                .disabled(!can_commit || self.modal_open)
3549                .tooltip({
3550                    let handle = commit_tooltip_focus_handle.clone();
3551                    move |_window, cx| {
3552                        if can_commit {
3553                            Tooltip::with_meta_in(
3554                                tooltip,
3555                                Some(if amend { &git::Amend } else { &git::Commit }),
3556                                format!(
3557                                    "git commit{}{}",
3558                                    if amend { " --amend" } else { "" },
3559                                    if signoff { " --signoff" } else { "" }
3560                                ),
3561                                &handle.clone(),
3562                                cx,
3563                            )
3564                        } else {
3565                            Tooltip::simple(tooltip, cx)
3566                        }
3567                    }
3568                }),
3569                self.render_git_commit_menu(
3570                    ElementId::Name(format!("split-button-right-{}", title).into()),
3571                    Some(commit_tooltip_focus_handle),
3572                    cx,
3573                )
3574                .into_any_element(),
3575            ))
3576    }
3577
3578    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3579        h_flex()
3580            .py_1p5()
3581            .px_2()
3582            .gap_1p5()
3583            .justify_between()
3584            .border_t_1()
3585            .border_color(cx.theme().colors().border.opacity(0.8))
3586            .child(
3587                div()
3588                    .flex_grow()
3589                    .overflow_hidden()
3590                    .max_w(relative(0.85))
3591                    .child(
3592                        Label::new("This will update your most recent commit.")
3593                            .size(LabelSize::Small)
3594                            .truncate(),
3595                    ),
3596            )
3597            .child(
3598                panel_button("Cancel")
3599                    .size(ButtonSize::Default)
3600                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3601            )
3602    }
3603
3604    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3605        let active_repository = self.active_repository.as_ref()?;
3606        let branch = active_repository.read(cx).branch.as_ref()?;
3607        let commit = branch.most_recent_commit.as_ref()?.clone();
3608        let workspace = self.workspace.clone();
3609        let this = cx.entity();
3610
3611        Some(
3612            h_flex()
3613                .py_1p5()
3614                .px_2()
3615                .gap_1p5()
3616                .justify_between()
3617                .border_t_1()
3618                .border_color(cx.theme().colors().border.opacity(0.8))
3619                .child(
3620                    div()
3621                        .flex_grow()
3622                        .overflow_hidden()
3623                        .line_clamp(1)
3624                        .child(
3625                            Label::new(commit.subject.clone())
3626                                .size(LabelSize::Small)
3627                                .truncate(),
3628                        )
3629                        .id("commit-msg-hover")
3630                        .on_click({
3631                            let commit = commit.clone();
3632                            let repo = active_repository.downgrade();
3633                            move |_, window, cx| {
3634                                CommitView::open(
3635                                    commit.sha.to_string(),
3636                                    repo.clone(),
3637                                    workspace.clone(),
3638                                    None,
3639                                    window,
3640                                    cx,
3641                                );
3642                            }
3643                        })
3644                        .hoverable_tooltip({
3645                            let repo = active_repository.clone();
3646                            move |window, cx| {
3647                                GitPanelMessageTooltip::new(
3648                                    this.clone(),
3649                                    commit.sha.clone(),
3650                                    repo.clone(),
3651                                    window,
3652                                    cx,
3653                                )
3654                                .into()
3655                            }
3656                        }),
3657                )
3658                .when(commit.has_parent, |this| {
3659                    let has_unstaged = self.has_unstaged_changes();
3660                    this.child(
3661                        panel_icon_button("undo", IconName::Undo)
3662                            .icon_size(IconSize::XSmall)
3663                            .icon_color(Color::Muted)
3664                            .tooltip(move |_window, cx| {
3665                                Tooltip::with_meta(
3666                                    "Uncommit",
3667                                    Some(&git::Uncommit),
3668                                    if has_unstaged {
3669                                        "git reset HEAD^ --soft"
3670                                    } else {
3671                                        "git reset HEAD^"
3672                                    },
3673                                    cx,
3674                                )
3675                            })
3676                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3677                    )
3678                }),
3679        )
3680    }
3681
3682    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3683        h_flex().h_full().flex_grow().justify_center().child(
3684            v_flex()
3685                .gap_2()
3686                .child(h_flex().w_full().justify_around().child(
3687                    if self.active_repository.is_some() {
3688                        "No changes to commit"
3689                    } else {
3690                        "No Git repositories"
3691                    },
3692                ))
3693                .children({
3694                    let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3695                    (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3696                        h_flex().w_full().justify_around().child(
3697                            panel_filled_button("Initialize Repository")
3698                                .tooltip(Tooltip::for_action_title_in(
3699                                    "git init",
3700                                    &git::Init,
3701                                    &self.focus_handle,
3702                                ))
3703                                .on_click(move |_, _, cx| {
3704                                    cx.defer(move |cx| {
3705                                        cx.dispatch_action(&git::Init);
3706                                    })
3707                                }),
3708                        )
3709                    })
3710                })
3711                .text_ui_sm(cx)
3712                .mx_auto()
3713                .text_color(Color::Placeholder.color(cx)),
3714        )
3715    }
3716
3717    fn render_buffer_header_controls(
3718        &self,
3719        entity: &Entity<Self>,
3720        file: &Arc<dyn File>,
3721        _: &Window,
3722        cx: &App,
3723    ) -> Option<AnyElement> {
3724        let repo = self.active_repository.as_ref()?.read(cx);
3725        let project_path = (file.worktree_id(cx), file.path().clone()).into();
3726        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3727        let ix = self.entry_by_path(&repo_path, cx)?;
3728        let entry = self.entries.get(ix)?;
3729
3730        let status = entry.status_entry()?;
3731        let entry_staging = self.entry_staging(status).unwrap_or(status.staging);
3732
3733        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3734            .disabled(!self.has_write_access(cx))
3735            .fill()
3736            .elevation(ElevationIndex::Surface)
3737            .on_click({
3738                let entry = entry.clone();
3739                let git_panel = entity.downgrade();
3740                move |_, window, cx| {
3741                    git_panel
3742                        .update(cx, |this, cx| {
3743                            this.toggle_staged_for_entry(&entry, window, cx);
3744                            cx.stop_propagation();
3745                        })
3746                        .ok();
3747                }
3748            });
3749        Some(
3750            h_flex()
3751                .id("start-slot")
3752                .text_lg()
3753                .child(checkbox)
3754                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3755                    // prevent the list item active state triggering when toggling checkbox
3756                    cx.stop_propagation();
3757                })
3758                .into_any_element(),
3759        )
3760    }
3761
3762    fn render_entries(
3763        &self,
3764        has_write_access: bool,
3765        window: &mut Window,
3766        cx: &mut Context<Self>,
3767    ) -> impl IntoElement {
3768        let entry_count = self.entries.len();
3769
3770        v_flex()
3771            .flex_1()
3772            .size_full()
3773            .overflow_hidden()
3774            .relative()
3775            .child(
3776                h_flex()
3777                    .flex_1()
3778                    .size_full()
3779                    .relative()
3780                    .overflow_hidden()
3781                    .child(
3782                        uniform_list(
3783                            "entries",
3784                            entry_count,
3785                            cx.processor(move |this, range: Range<usize>, window, cx| {
3786                                let mut items = Vec::with_capacity(range.end - range.start);
3787
3788                                for ix in range {
3789                                    match &this.entries.get(ix) {
3790                                        Some(GitListEntry::Status(entry)) => {
3791                                            items.push(this.render_entry(
3792                                                ix,
3793                                                entry,
3794                                                has_write_access,
3795                                                window,
3796                                                cx,
3797                                            ));
3798                                        }
3799                                        Some(GitListEntry::Header(header)) => {
3800                                            items.push(this.render_list_header(
3801                                                ix,
3802                                                header,
3803                                                has_write_access,
3804                                                window,
3805                                                cx,
3806                                            ));
3807                                        }
3808                                        None => {}
3809                                    }
3810                                }
3811
3812                                items
3813                            }),
3814                        )
3815                        .size_full()
3816                        .flex_grow()
3817                        .with_sizing_behavior(ListSizingBehavior::Auto)
3818                        .with_horizontal_sizing_behavior(
3819                            ListHorizontalSizingBehavior::Unconstrained,
3820                        )
3821                        .with_width_from_item(self.max_width_item_index)
3822                        .track_scroll(self.scroll_handle.clone()),
3823                    )
3824                    .on_mouse_down(
3825                        MouseButton::Right,
3826                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3827                            this.deploy_panel_context_menu(event.position, window, cx)
3828                        }),
3829                    )
3830                    .custom_scrollbars(
3831                        Scrollbars::for_settings::<GitPanelSettings>()
3832                            .tracked_scroll_handle(self.scroll_handle.clone())
3833                            .with_track_along(
3834                                ScrollAxes::Horizontal,
3835                                cx.theme().colors().panel_background,
3836                            ),
3837                        window,
3838                        cx,
3839                    ),
3840            )
3841    }
3842
3843    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3844        Label::new(label.into()).color(color).single_line()
3845    }
3846
3847    fn list_item_height(&self) -> Rems {
3848        rems(1.75)
3849    }
3850
3851    fn render_list_header(
3852        &self,
3853        ix: usize,
3854        header: &GitHeaderEntry,
3855        _: bool,
3856        _: &Window,
3857        _: &Context<Self>,
3858    ) -> AnyElement {
3859        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3860
3861        h_flex()
3862            .id(id)
3863            .h(self.list_item_height())
3864            .w_full()
3865            .items_end()
3866            .px(rems(0.75)) // ~12px
3867            .pb(rems(0.3125)) // ~ 5px
3868            .child(
3869                Label::new(header.title())
3870                    .color(Color::Muted)
3871                    .size(LabelSize::Small)
3872                    .line_height_style(LineHeightStyle::UiLabel)
3873                    .single_line(),
3874            )
3875            .into_any_element()
3876    }
3877
3878    pub fn load_commit_details(
3879        &self,
3880        sha: String,
3881        cx: &mut Context<Self>,
3882    ) -> Task<anyhow::Result<CommitDetails>> {
3883        let Some(repo) = self.active_repository.clone() else {
3884            return Task::ready(Err(anyhow::anyhow!("no active repo")));
3885        };
3886        repo.update(cx, |repo, cx| {
3887            let show = repo.show(sha);
3888            cx.spawn(async move |_, _| show.await?)
3889        })
3890    }
3891
3892    fn deploy_entry_context_menu(
3893        &mut self,
3894        position: Point<Pixels>,
3895        ix: usize,
3896        window: &mut Window,
3897        cx: &mut Context<Self>,
3898    ) {
3899        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3900            return;
3901        };
3902        let stage_title = if entry.status.staging().is_fully_staged() {
3903            "Unstage File"
3904        } else {
3905            "Stage File"
3906        };
3907        let restore_title = if entry.status.is_created() {
3908            "Trash File"
3909        } else {
3910            "Restore File"
3911        };
3912        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3913            let mut context_menu = context_menu
3914                .context(self.focus_handle.clone())
3915                .action(stage_title, ToggleStaged.boxed_clone())
3916                .action(restore_title, git::RestoreFile::default().boxed_clone());
3917
3918            if entry.status.is_created() {
3919                context_menu =
3920                    context_menu.action("Add to .gitignore", git::AddToGitignore.boxed_clone());
3921            }
3922
3923            context_menu
3924                .separator()
3925                .action("Open Diff", Confirm.boxed_clone())
3926                .action("Open File", SecondaryConfirm.boxed_clone())
3927        });
3928        self.selected_entry = Some(ix);
3929        self.set_context_menu(context_menu, position, window, cx);
3930    }
3931
3932    fn deploy_panel_context_menu(
3933        &mut self,
3934        position: Point<Pixels>,
3935        window: &mut Window,
3936        cx: &mut Context<Self>,
3937    ) {
3938        let context_menu = git_panel_context_menu(
3939            self.focus_handle.clone(),
3940            GitMenuState {
3941                has_tracked_changes: self.has_tracked_changes(),
3942                has_staged_changes: self.has_staged_changes(),
3943                has_unstaged_changes: self.has_unstaged_changes(),
3944                has_new_changes: self.new_count > 0,
3945                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3946                has_stash_items: self.stash_entries.entries.len() > 0,
3947            },
3948            window,
3949            cx,
3950        );
3951        self.set_context_menu(context_menu, position, window, cx);
3952    }
3953
3954    fn set_context_menu(
3955        &mut self,
3956        context_menu: Entity<ContextMenu>,
3957        position: Point<Pixels>,
3958        window: &Window,
3959        cx: &mut Context<Self>,
3960    ) {
3961        let subscription = cx.subscribe_in(
3962            &context_menu,
3963            window,
3964            |this, _, _: &DismissEvent, window, cx| {
3965                if this.context_menu.as_ref().is_some_and(|context_menu| {
3966                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
3967                }) {
3968                    cx.focus_self(window);
3969                }
3970                this.context_menu.take();
3971                cx.notify();
3972            },
3973        );
3974        self.context_menu = Some((context_menu, position, subscription));
3975        cx.notify();
3976    }
3977
3978    fn render_entry(
3979        &self,
3980        ix: usize,
3981        entry: &GitStatusEntry,
3982        has_write_access: bool,
3983        window: &Window,
3984        cx: &Context<Self>,
3985    ) -> AnyElement {
3986        let path_style = self.project.read(cx).path_style(cx);
3987        let display_name = entry.display_name(path_style);
3988
3989        let selected = self.selected_entry == Some(ix);
3990        let marked = self.marked_entries.contains(&ix);
3991        let status_style = GitPanelSettings::get_global(cx).status_style;
3992        let status = entry.status;
3993
3994        let has_conflict = status.is_conflicted();
3995        let is_modified = status.is_modified();
3996        let is_deleted = status.is_deleted();
3997
3998        let label_color = if status_style == StatusStyle::LabelColor {
3999            if has_conflict {
4000                Color::VersionControlConflict
4001            } else if is_modified {
4002                Color::VersionControlModified
4003            } else if is_deleted {
4004                // We don't want a bunch of red labels in the list
4005                Color::Disabled
4006            } else {
4007                Color::VersionControlAdded
4008            }
4009        } else {
4010            Color::Default
4011        };
4012
4013        let path_color = if status.is_deleted() {
4014            Color::Disabled
4015        } else {
4016            Color::Muted
4017        };
4018
4019        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4020        let checkbox_wrapper_id: ElementId =
4021            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4022        let checkbox_id: ElementId =
4023            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4024
4025        let entry_staging = self.entry_staging(entry).unwrap_or(entry.staging);
4026        let mut is_staged: ToggleState = entry_staging.as_bool().into();
4027        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4028            is_staged = ToggleState::Selected;
4029        }
4030
4031        let handle = cx.weak_entity();
4032
4033        let selected_bg_alpha = 0.08;
4034        let marked_bg_alpha = 0.12;
4035        let state_opacity_step = 0.04;
4036
4037        let base_bg = match (selected, marked) {
4038            (true, true) => cx
4039                .theme()
4040                .status()
4041                .info
4042                .alpha(selected_bg_alpha + marked_bg_alpha),
4043            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4044            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4045            _ => cx.theme().colors().ghost_element_background,
4046        };
4047
4048        let hover_bg = if selected {
4049            cx.theme()
4050                .status()
4051                .info
4052                .alpha(selected_bg_alpha + state_opacity_step)
4053        } else {
4054            cx.theme().colors().ghost_element_hover
4055        };
4056
4057        let active_bg = if selected {
4058            cx.theme()
4059                .status()
4060                .info
4061                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4062        } else {
4063            cx.theme().colors().ghost_element_active
4064        };
4065
4066        h_flex()
4067            .id(id)
4068            .h(self.list_item_height())
4069            .w_full()
4070            .items_center()
4071            .border_1()
4072            .when(selected && self.focus_handle.is_focused(window), |el| {
4073                el.border_color(cx.theme().colors().border_focused)
4074            })
4075            .px(rems(0.75)) // ~12px
4076            .overflow_hidden()
4077            .flex_none()
4078            .gap_1p5()
4079            .bg(base_bg)
4080            .hover(|this| this.bg(hover_bg))
4081            .active(|this| this.bg(active_bg))
4082            .on_click({
4083                cx.listener(move |this, event: &ClickEvent, window, cx| {
4084                    this.selected_entry = Some(ix);
4085                    cx.notify();
4086                    if event.modifiers().secondary() {
4087                        this.open_file(&Default::default(), window, cx)
4088                    } else {
4089                        this.open_diff(&Default::default(), window, cx);
4090                        this.focus_handle.focus(window);
4091                    }
4092                })
4093            })
4094            .on_mouse_down(
4095                MouseButton::Right,
4096                move |event: &MouseDownEvent, window, cx| {
4097                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4098                    if event.button != MouseButton::Right {
4099                        return;
4100                    }
4101
4102                    let Some(this) = handle.upgrade() else {
4103                        return;
4104                    };
4105                    this.update(cx, |this, cx| {
4106                        this.deploy_entry_context_menu(event.position, ix, window, cx);
4107                    });
4108                    cx.stop_propagation();
4109                },
4110            )
4111            .child(
4112                div()
4113                    .id(checkbox_wrapper_id)
4114                    .flex_none()
4115                    .occlude()
4116                    .cursor_pointer()
4117                    .child(
4118                        Checkbox::new(checkbox_id, is_staged)
4119                            .disabled(!has_write_access)
4120                            .fill()
4121                            .elevation(ElevationIndex::Surface)
4122                            .on_click_ext({
4123                                let entry = entry.clone();
4124                                let this = cx.weak_entity();
4125                                move |_, click, window, cx| {
4126                                    this.update(cx, |this, cx| {
4127                                        if !has_write_access {
4128                                            return;
4129                                        }
4130                                        if click.modifiers().shift {
4131                                            this.stage_bulk(ix, cx);
4132                                        } else {
4133                                            this.toggle_staged_for_entry(
4134                                                &GitListEntry::Status(entry.clone()),
4135                                                window,
4136                                                cx,
4137                                            );
4138                                        }
4139                                        cx.stop_propagation();
4140                                    })
4141                                    .ok();
4142                                }
4143                            })
4144                            .tooltip(move |_window, cx| {
4145                                let is_staged = entry_staging.is_fully_staged();
4146
4147                                let action = if is_staged { "Unstage" } else { "Stage" };
4148                                let tooltip_name = action.to_string();
4149
4150                                Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
4151                            }),
4152                    ),
4153            )
4154            .child(git_status_icon(status))
4155            .child(
4156                h_flex()
4157                    .items_center()
4158                    .flex_1()
4159                    // .overflow_hidden()
4160                    .when_some(entry.parent_dir(path_style), |this, parent| {
4161                        if !parent.is_empty() {
4162                            this.child(
4163                                self.entry_label(
4164                                    format!("{parent}{}", path_style.separator()),
4165                                    path_color,
4166                                )
4167                                .when(status.is_deleted(), |this| this.strikethrough()),
4168                            )
4169                        } else {
4170                            this
4171                        }
4172                    })
4173                    .child(
4174                        self.entry_label(display_name, label_color)
4175                            .when(status.is_deleted(), |this| this.strikethrough()),
4176                    ),
4177            )
4178            .into_any_element()
4179    }
4180
4181    fn has_write_access(&self, cx: &App) -> bool {
4182        !self.project.read(cx).is_read_only(cx)
4183    }
4184
4185    pub fn amend_pending(&self) -> bool {
4186        self.amend_pending
4187    }
4188
4189    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4190        if value && !self.amend_pending {
4191            let current_message = self.commit_message_buffer(cx).read(cx).text();
4192            self.original_commit_message = if current_message.trim().is_empty() {
4193                None
4194            } else {
4195                Some(current_message)
4196            };
4197        } else if !value && self.amend_pending {
4198            let message = self.original_commit_message.take().unwrap_or_default();
4199            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4200                let start = buffer.anchor_before(0);
4201                let end = buffer.anchor_after(buffer.len());
4202                buffer.edit([(start..end, message)], None, cx);
4203            });
4204        }
4205
4206        self.amend_pending = value;
4207        self.serialize(cx);
4208        cx.notify();
4209    }
4210
4211    pub fn signoff_enabled(&self) -> bool {
4212        self.signoff_enabled
4213    }
4214
4215    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4216        self.signoff_enabled = value;
4217        self.serialize(cx);
4218        cx.notify();
4219    }
4220
4221    pub fn toggle_signoff_enabled(
4222        &mut self,
4223        _: &Signoff,
4224        _window: &mut Window,
4225        cx: &mut Context<Self>,
4226    ) {
4227        self.set_signoff_enabled(!self.signoff_enabled, cx);
4228    }
4229
4230    pub async fn load(
4231        workspace: WeakEntity<Workspace>,
4232        mut cx: AsyncWindowContext,
4233    ) -> anyhow::Result<Entity<Self>> {
4234        let serialized_panel = match workspace
4235            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4236            .ok()
4237            .flatten()
4238        {
4239            Some(serialization_key) => cx
4240                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4241                .await
4242                .context("loading git panel")
4243                .log_err()
4244                .flatten()
4245                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4246                .transpose()
4247                .log_err()
4248                .flatten(),
4249            None => None,
4250        };
4251
4252        workspace.update_in(&mut cx, |workspace, window, cx| {
4253            let panel = GitPanel::new(workspace, window, cx);
4254
4255            if let Some(serialized_panel) = serialized_panel {
4256                panel.update(cx, |panel, cx| {
4257                    panel.width = serialized_panel.width;
4258                    panel.amend_pending = serialized_panel.amend_pending;
4259                    panel.signoff_enabled = serialized_panel.signoff_enabled;
4260                    cx.notify();
4261                })
4262            }
4263
4264            panel
4265        })
4266    }
4267
4268    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4269        let Some(op) = self.bulk_staging.as_ref() else {
4270            return;
4271        };
4272        let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4273            return;
4274        };
4275        if let Some(entry) = self.entries.get(index)
4276            && let Some(entry) = entry.status_entry()
4277        {
4278            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4279        }
4280        if index < anchor_index {
4281            std::mem::swap(&mut index, &mut anchor_index);
4282        }
4283        let entries = self
4284            .entries
4285            .get(anchor_index..=index)
4286            .unwrap_or_default()
4287            .iter()
4288            .filter_map(|entry| entry.status_entry().cloned())
4289            .collect::<Vec<_>>();
4290        self.change_file_stage(true, entries, cx);
4291    }
4292
4293    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4294        let Some(repo) = self.active_repository.as_ref() else {
4295            return;
4296        };
4297        self.bulk_staging = Some(BulkStaging {
4298            repo_id: repo.read(cx).id,
4299            anchor: path,
4300        });
4301    }
4302
4303    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4304        self.set_amend_pending(!self.amend_pending, cx);
4305        if self.amend_pending {
4306            self.load_last_commit_message_if_empty(cx);
4307        }
4308    }
4309}
4310
4311impl Render for GitPanel {
4312    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4313        let project = self.project.read(cx);
4314        let has_entries = !self.entries.is_empty();
4315        let room = self
4316            .workspace
4317            .upgrade()
4318            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4319
4320        let has_write_access = self.has_write_access(cx);
4321
4322        let has_co_authors = room.is_some_and(|room| {
4323            self.load_local_committer(cx);
4324            let room = room.read(cx);
4325            room.remote_participants()
4326                .values()
4327                .any(|remote_participant| remote_participant.can_write())
4328        });
4329
4330        v_flex()
4331            .id("git_panel")
4332            .key_context(self.dispatch_context(window, cx))
4333            .track_focus(&self.focus_handle)
4334            .when(has_write_access && !project.is_read_only(cx), |this| {
4335                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4336                    .on_action(cx.listener(Self::stage_range))
4337                    .on_action(cx.listener(GitPanel::commit))
4338                    .on_action(cx.listener(GitPanel::amend))
4339                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4340                    .on_action(cx.listener(Self::stage_all))
4341                    .on_action(cx.listener(Self::unstage_all))
4342                    .on_action(cx.listener(Self::stage_selected))
4343                    .on_action(cx.listener(Self::unstage_selected))
4344                    .on_action(cx.listener(Self::restore_tracked_files))
4345                    .on_action(cx.listener(Self::revert_selected))
4346                    .on_action(cx.listener(Self::add_to_gitignore))
4347                    .on_action(cx.listener(Self::clean_all))
4348                    .on_action(cx.listener(Self::generate_commit_message_action))
4349                    .on_action(cx.listener(Self::stash_all))
4350                    .on_action(cx.listener(Self::stash_pop))
4351            })
4352            .on_action(cx.listener(Self::select_first))
4353            .on_action(cx.listener(Self::select_next))
4354            .on_action(cx.listener(Self::select_previous))
4355            .on_action(cx.listener(Self::select_last))
4356            .on_action(cx.listener(Self::close_panel))
4357            .on_action(cx.listener(Self::open_diff))
4358            .on_action(cx.listener(Self::open_file))
4359            .on_action(cx.listener(Self::focus_changes_list))
4360            .on_action(cx.listener(Self::focus_editor))
4361            .on_action(cx.listener(Self::expand_commit_editor))
4362            .when(has_write_access && has_co_authors, |git_panel| {
4363                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4364            })
4365            .on_action(cx.listener(Self::toggle_sort_by_path))
4366            .size_full()
4367            .overflow_hidden()
4368            .bg(cx.theme().colors().panel_background)
4369            .child(
4370                v_flex()
4371                    .size_full()
4372                    .children(self.render_panel_header(window, cx))
4373                    .map(|this| {
4374                        if has_entries {
4375                            this.child(self.render_entries(has_write_access, window, cx))
4376                        } else {
4377                            this.child(self.render_empty_state(cx).into_any_element())
4378                        }
4379                    })
4380                    .children(self.render_footer(window, cx))
4381                    .when(self.amend_pending, |this| {
4382                        this.child(self.render_pending_amend(cx))
4383                    })
4384                    .when(!self.amend_pending, |this| {
4385                        this.children(self.render_previous_commit(cx))
4386                    })
4387                    .into_any_element(),
4388            )
4389            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4390                deferred(
4391                    anchored()
4392                        .position(*position)
4393                        .anchor(Corner::TopLeft)
4394                        .child(menu.clone()),
4395                )
4396                .with_priority(1)
4397            }))
4398    }
4399}
4400
4401impl Focusable for GitPanel {
4402    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4403        if self.entries.is_empty() {
4404            self.commit_editor.focus_handle(cx)
4405        } else {
4406            self.focus_handle.clone()
4407        }
4408    }
4409}
4410
4411impl EventEmitter<Event> for GitPanel {}
4412
4413impl EventEmitter<PanelEvent> for GitPanel {}
4414
4415pub(crate) struct GitPanelAddon {
4416    pub(crate) workspace: WeakEntity<Workspace>,
4417}
4418
4419impl editor::Addon for GitPanelAddon {
4420    fn to_any(&self) -> &dyn std::any::Any {
4421        self
4422    }
4423
4424    fn render_buffer_header_controls(
4425        &self,
4426        excerpt_info: &ExcerptInfo,
4427        window: &Window,
4428        cx: &App,
4429    ) -> Option<AnyElement> {
4430        let file = excerpt_info.buffer.file()?;
4431        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4432
4433        git_panel
4434            .read(cx)
4435            .render_buffer_header_controls(&git_panel, file, window, cx)
4436    }
4437}
4438
4439impl Panel for GitPanel {
4440    fn persistent_name() -> &'static str {
4441        "GitPanel"
4442    }
4443
4444    fn panel_key() -> &'static str {
4445        GIT_PANEL_KEY
4446    }
4447
4448    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4449        GitPanelSettings::get_global(cx).dock
4450    }
4451
4452    fn position_is_valid(&self, position: DockPosition) -> bool {
4453        matches!(position, DockPosition::Left | DockPosition::Right)
4454    }
4455
4456    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4457        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
4458            settings.git_panel.get_or_insert_default().dock = Some(position.into())
4459        });
4460    }
4461
4462    fn size(&self, _: &Window, cx: &App) -> Pixels {
4463        self.width
4464            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4465    }
4466
4467    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4468        self.width = size;
4469        self.serialize(cx);
4470        cx.notify();
4471    }
4472
4473    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4474        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4475    }
4476
4477    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4478        Some("Git Panel")
4479    }
4480
4481    fn toggle_action(&self) -> Box<dyn Action> {
4482        Box::new(ToggleFocus)
4483    }
4484
4485    fn activation_priority(&self) -> u32 {
4486        2
4487    }
4488}
4489
4490impl PanelHeader for GitPanel {}
4491
4492struct GitPanelMessageTooltip {
4493    commit_tooltip: Option<Entity<CommitTooltip>>,
4494}
4495
4496impl GitPanelMessageTooltip {
4497    fn new(
4498        git_panel: Entity<GitPanel>,
4499        sha: SharedString,
4500        repository: Entity<Repository>,
4501        window: &mut Window,
4502        cx: &mut App,
4503    ) -> Entity<Self> {
4504        cx.new(|cx| {
4505            cx.spawn_in(window, async move |this, cx| {
4506                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4507                    (
4508                        git_panel.load_commit_details(sha.to_string(), cx),
4509                        git_panel.workspace.clone(),
4510                    )
4511                })?;
4512                let details = details.await?;
4513
4514                let commit_details = crate::commit_tooltip::CommitDetails {
4515                    sha: details.sha.clone(),
4516                    author_name: details.author_name.clone(),
4517                    author_email: details.author_email.clone(),
4518                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4519                    message: Some(ParsedCommitMessage {
4520                        message: details.message,
4521                        ..Default::default()
4522                    }),
4523                };
4524
4525                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4526                    this.commit_tooltip = Some(cx.new(move |cx| {
4527                        CommitTooltip::new(commit_details, repository, workspace, cx)
4528                    }));
4529                    cx.notify();
4530                })
4531            })
4532            .detach();
4533
4534            Self {
4535                commit_tooltip: None,
4536            }
4537        })
4538    }
4539}
4540
4541impl Render for GitPanelMessageTooltip {
4542    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4543        if let Some(commit_tooltip) = &self.commit_tooltip {
4544            commit_tooltip.clone().into_any_element()
4545        } else {
4546            gpui::Empty.into_any_element()
4547        }
4548    }
4549}
4550
4551#[derive(IntoElement, RegisterComponent)]
4552pub struct PanelRepoFooter {
4553    active_repository: SharedString,
4554    branch: Option<Branch>,
4555    head_commit: Option<CommitDetails>,
4556
4557    // Getting a GitPanel in previews will be difficult.
4558    //
4559    // For now just take an option here, and we won't bind handlers to buttons in previews.
4560    git_panel: Option<Entity<GitPanel>>,
4561}
4562
4563impl PanelRepoFooter {
4564    pub fn new(
4565        active_repository: SharedString,
4566        branch: Option<Branch>,
4567        head_commit: Option<CommitDetails>,
4568        git_panel: Option<Entity<GitPanel>>,
4569    ) -> Self {
4570        Self {
4571            active_repository,
4572            branch,
4573            head_commit,
4574            git_panel,
4575        }
4576    }
4577
4578    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4579        Self {
4580            active_repository,
4581            branch,
4582            head_commit: None,
4583            git_panel: None,
4584        }
4585    }
4586}
4587
4588impl RenderOnce for PanelRepoFooter {
4589    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4590        let project = self
4591            .git_panel
4592            .as_ref()
4593            .map(|panel| panel.read(cx).project.clone());
4594
4595        let repo = self
4596            .git_panel
4597            .as_ref()
4598            .and_then(|panel| panel.read(cx).active_repository.clone());
4599
4600        let single_repo = project
4601            .as_ref()
4602            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4603            .unwrap_or(true);
4604
4605        const MAX_BRANCH_LEN: usize = 16;
4606        const MAX_REPO_LEN: usize = 16;
4607        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4608        const MAX_SHORT_SHA_LEN: usize = 8;
4609
4610        let branch_name = self
4611            .branch
4612            .as_ref()
4613            .map(|branch| branch.name().to_owned())
4614            .or_else(|| {
4615                self.head_commit.as_ref().map(|commit| {
4616                    commit
4617                        .sha
4618                        .chars()
4619                        .take(MAX_SHORT_SHA_LEN)
4620                        .collect::<String>()
4621                })
4622            })
4623            .unwrap_or_else(|| " (no branch)".to_owned());
4624        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4625
4626        let active_repo_name = self.active_repository.clone();
4627
4628        let branch_actual_len = branch_name.len();
4629        let repo_actual_len = active_repo_name.len();
4630
4631        // ideally, show the whole branch and repo names but
4632        // when we can't, use a budget to allocate space between the two
4633        let (repo_display_len, branch_display_len) =
4634            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4635                (repo_actual_len, branch_actual_len)
4636            } else if branch_actual_len <= MAX_BRANCH_LEN {
4637                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4638                (repo_space, branch_actual_len)
4639            } else if repo_actual_len <= MAX_REPO_LEN {
4640                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4641                (repo_actual_len, branch_space)
4642            } else {
4643                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4644            };
4645
4646        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4647            active_repo_name.to_string()
4648        } else {
4649            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4650        };
4651
4652        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4653            branch_name
4654        } else {
4655            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4656        };
4657
4658        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4659            .size(ButtonSize::None)
4660            .label_size(LabelSize::Small)
4661            .color(Color::Muted);
4662
4663        let repo_selector = PopoverMenu::new("repository-switcher")
4664            .menu({
4665                let project = project;
4666                move |window, cx| {
4667                    let project = project.clone()?;
4668                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4669                }
4670            })
4671            .trigger_with_tooltip(
4672                repo_selector_trigger.disabled(single_repo).truncate(true),
4673                Tooltip::text("Switch Active Repository"),
4674            )
4675            .anchor(Corner::BottomLeft)
4676            .into_any_element();
4677
4678        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4679            .size(ButtonSize::None)
4680            .label_size(LabelSize::Small)
4681            .truncate(true)
4682            .on_click(|_, window, cx| {
4683                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4684            });
4685
4686        let branch_selector = PopoverMenu::new("popover-button")
4687            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4688            .trigger_with_tooltip(
4689                branch_selector_button,
4690                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4691            )
4692            .anchor(Corner::BottomLeft)
4693            .offset(gpui::Point {
4694                x: px(0.0),
4695                y: px(-2.0),
4696            });
4697
4698        h_flex()
4699            .h(px(36.))
4700            .w_full()
4701            .px_2()
4702            .justify_between()
4703            .gap_1()
4704            .child(
4705                h_flex()
4706                    .flex_1()
4707                    .overflow_hidden()
4708                    .gap_px()
4709                    .child(
4710                        Icon::new(IconName::GitBranchAlt)
4711                            .size(IconSize::Small)
4712                            .color(if single_repo {
4713                                Color::Disabled
4714                            } else {
4715                                Color::Muted
4716                            }),
4717                    )
4718                    .child(repo_selector)
4719                    .when(show_separator, |this| {
4720                        this.child(
4721                            div()
4722                                .text_sm()
4723                                .text_color(cx.theme().colors().icon_muted.opacity(0.5))
4724                                .child("/"),
4725                        )
4726                    })
4727                    .child(branch_selector),
4728            )
4729            .children(if let Some(git_panel) = self.git_panel {
4730                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4731            } else {
4732                None
4733            })
4734    }
4735}
4736
4737impl Component for PanelRepoFooter {
4738    fn scope() -> ComponentScope {
4739        ComponentScope::VersionControl
4740    }
4741
4742    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4743        let unknown_upstream = None;
4744        let no_remote_upstream = Some(UpstreamTracking::Gone);
4745        let ahead_of_upstream = Some(
4746            UpstreamTrackingStatus {
4747                ahead: 2,
4748                behind: 0,
4749            }
4750            .into(),
4751        );
4752        let behind_upstream = Some(
4753            UpstreamTrackingStatus {
4754                ahead: 0,
4755                behind: 2,
4756            }
4757            .into(),
4758        );
4759        let ahead_and_behind_upstream = Some(
4760            UpstreamTrackingStatus {
4761                ahead: 3,
4762                behind: 1,
4763            }
4764            .into(),
4765        );
4766
4767        let not_ahead_or_behind_upstream = Some(
4768            UpstreamTrackingStatus {
4769                ahead: 0,
4770                behind: 0,
4771            }
4772            .into(),
4773        );
4774
4775        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4776            Branch {
4777                is_head: true,
4778                ref_name: "some-branch".into(),
4779                upstream: upstream.map(|tracking| Upstream {
4780                    ref_name: "origin/some-branch".into(),
4781                    tracking,
4782                }),
4783                most_recent_commit: Some(CommitSummary {
4784                    sha: "abc123".into(),
4785                    subject: "Modify stuff".into(),
4786                    commit_timestamp: 1710932954,
4787                    author_name: "John Doe".into(),
4788                    has_parent: true,
4789                }),
4790            }
4791        }
4792
4793        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4794            Branch {
4795                is_head: true,
4796                ref_name: branch_name.to_string().into(),
4797                upstream: upstream.map(|tracking| Upstream {
4798                    ref_name: format!("zed/{}", branch_name).into(),
4799                    tracking,
4800                }),
4801                most_recent_commit: Some(CommitSummary {
4802                    sha: "abc123".into(),
4803                    subject: "Modify stuff".into(),
4804                    commit_timestamp: 1710932954,
4805                    author_name: "John Doe".into(),
4806                    has_parent: true,
4807                }),
4808            }
4809        }
4810
4811        fn active_repository(id: usize) -> SharedString {
4812            format!("repo-{}", id).into()
4813        }
4814
4815        let example_width = px(340.);
4816        Some(
4817            v_flex()
4818                .gap_6()
4819                .w_full()
4820                .flex_none()
4821                .children(vec![
4822                    example_group_with_title(
4823                        "Action Button States",
4824                        vec![
4825                            single_example(
4826                                "No Branch",
4827                                div()
4828                                    .w(example_width)
4829                                    .overflow_hidden()
4830                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
4831                                    .into_any_element(),
4832                            ),
4833                            single_example(
4834                                "Remote status unknown",
4835                                div()
4836                                    .w(example_width)
4837                                    .overflow_hidden()
4838                                    .child(PanelRepoFooter::new_preview(
4839                                        active_repository(2),
4840                                        Some(branch(unknown_upstream)),
4841                                    ))
4842                                    .into_any_element(),
4843                            ),
4844                            single_example(
4845                                "No Remote Upstream",
4846                                div()
4847                                    .w(example_width)
4848                                    .overflow_hidden()
4849                                    .child(PanelRepoFooter::new_preview(
4850                                        active_repository(3),
4851                                        Some(branch(no_remote_upstream)),
4852                                    ))
4853                                    .into_any_element(),
4854                            ),
4855                            single_example(
4856                                "Not Ahead or Behind",
4857                                div()
4858                                    .w(example_width)
4859                                    .overflow_hidden()
4860                                    .child(PanelRepoFooter::new_preview(
4861                                        active_repository(4),
4862                                        Some(branch(not_ahead_or_behind_upstream)),
4863                                    ))
4864                                    .into_any_element(),
4865                            ),
4866                            single_example(
4867                                "Behind remote",
4868                                div()
4869                                    .w(example_width)
4870                                    .overflow_hidden()
4871                                    .child(PanelRepoFooter::new_preview(
4872                                        active_repository(5),
4873                                        Some(branch(behind_upstream)),
4874                                    ))
4875                                    .into_any_element(),
4876                            ),
4877                            single_example(
4878                                "Ahead of remote",
4879                                div()
4880                                    .w(example_width)
4881                                    .overflow_hidden()
4882                                    .child(PanelRepoFooter::new_preview(
4883                                        active_repository(6),
4884                                        Some(branch(ahead_of_upstream)),
4885                                    ))
4886                                    .into_any_element(),
4887                            ),
4888                            single_example(
4889                                "Ahead and behind remote",
4890                                div()
4891                                    .w(example_width)
4892                                    .overflow_hidden()
4893                                    .child(PanelRepoFooter::new_preview(
4894                                        active_repository(7),
4895                                        Some(branch(ahead_and_behind_upstream)),
4896                                    ))
4897                                    .into_any_element(),
4898                            ),
4899                        ],
4900                    )
4901                    .grow()
4902                    .vertical(),
4903                ])
4904                .children(vec![
4905                    example_group_with_title(
4906                        "Labels",
4907                        vec![
4908                            single_example(
4909                                "Short Branch & Repo",
4910                                div()
4911                                    .w(example_width)
4912                                    .overflow_hidden()
4913                                    .child(PanelRepoFooter::new_preview(
4914                                        SharedString::from("zed"),
4915                                        Some(custom("main", behind_upstream)),
4916                                    ))
4917                                    .into_any_element(),
4918                            ),
4919                            single_example(
4920                                "Long Branch",
4921                                div()
4922                                    .w(example_width)
4923                                    .overflow_hidden()
4924                                    .child(PanelRepoFooter::new_preview(
4925                                        SharedString::from("zed"),
4926                                        Some(custom(
4927                                            "redesign-and-update-git-ui-list-entry-style",
4928                                            behind_upstream,
4929                                        )),
4930                                    ))
4931                                    .into_any_element(),
4932                            ),
4933                            single_example(
4934                                "Long Repo",
4935                                div()
4936                                    .w(example_width)
4937                                    .overflow_hidden()
4938                                    .child(PanelRepoFooter::new_preview(
4939                                        SharedString::from("zed-industries-community-examples"),
4940                                        Some(custom("gpui", ahead_of_upstream)),
4941                                    ))
4942                                    .into_any_element(),
4943                            ),
4944                            single_example(
4945                                "Long Repo & Branch",
4946                                div()
4947                                    .w(example_width)
4948                                    .overflow_hidden()
4949                                    .child(PanelRepoFooter::new_preview(
4950                                        SharedString::from("zed-industries-community-examples"),
4951                                        Some(custom(
4952                                            "redesign-and-update-git-ui-list-entry-style",
4953                                            behind_upstream,
4954                                        )),
4955                                    ))
4956                                    .into_any_element(),
4957                            ),
4958                            single_example(
4959                                "Uppercase Repo",
4960                                div()
4961                                    .w(example_width)
4962                                    .overflow_hidden()
4963                                    .child(PanelRepoFooter::new_preview(
4964                                        SharedString::from("LICENSES"),
4965                                        Some(custom("main", ahead_of_upstream)),
4966                                    ))
4967                                    .into_any_element(),
4968                            ),
4969                            single_example(
4970                                "Uppercase Branch",
4971                                div()
4972                                    .w(example_width)
4973                                    .overflow_hidden()
4974                                    .child(PanelRepoFooter::new_preview(
4975                                        SharedString::from("zed"),
4976                                        Some(custom("update-README", behind_upstream)),
4977                                    ))
4978                                    .into_any_element(),
4979                            ),
4980                        ],
4981                    )
4982                    .grow()
4983                    .vertical(),
4984                ])
4985                .into_any_element(),
4986        )
4987    }
4988}
4989
4990#[cfg(test)]
4991mod tests {
4992    use git::{
4993        repository::repo_path,
4994        status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
4995    };
4996    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
4997    use project::{FakeFs, WorktreeSettings};
4998    use serde_json::json;
4999    use settings::SettingsStore;
5000    use theme::LoadThemes;
5001    use util::path;
5002    use util::rel_path::rel_path;
5003
5004    use super::*;
5005
5006    fn init_test(cx: &mut gpui::TestAppContext) {
5007        zlog::init_test();
5008
5009        cx.update(|cx| {
5010            let settings_store = SettingsStore::test(cx);
5011            cx.set_global(settings_store);
5012            AgentSettings::register(cx);
5013            WorktreeSettings::register(cx);
5014            workspace::init_settings(cx);
5015            theme::init(LoadThemes::JustBase, cx);
5016            language::init(cx);
5017            editor::init(cx);
5018            Project::init_settings(cx);
5019            crate::init(cx);
5020        });
5021    }
5022
5023    #[gpui::test]
5024    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5025        init_test(cx);
5026        let fs = FakeFs::new(cx.background_executor.clone());
5027        fs.insert_tree(
5028            "/root",
5029            json!({
5030                "zed": {
5031                    ".git": {},
5032                    "crates": {
5033                        "gpui": {
5034                            "gpui.rs": "fn main() {}"
5035                        },
5036                        "util": {
5037                            "util.rs": "fn do_it() {}"
5038                        }
5039                    }
5040                },
5041            }),
5042        )
5043        .await;
5044
5045        fs.set_status_for_repo(
5046            Path::new(path!("/root/zed/.git")),
5047            &[
5048                ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
5049                ("crates/util/util.rs", StatusCode::Modified.worktree()),
5050            ],
5051        );
5052
5053        let project =
5054            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5055        let workspace =
5056            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5057        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5058
5059        cx.read(|cx| {
5060            project
5061                .read(cx)
5062                .worktrees(cx)
5063                .next()
5064                .unwrap()
5065                .read(cx)
5066                .as_local()
5067                .unwrap()
5068                .scan_complete()
5069        })
5070        .await;
5071
5072        cx.executor().run_until_parked();
5073
5074        let panel = workspace.update(cx, GitPanel::new).unwrap();
5075
5076        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5077            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5078        });
5079        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5080        handle.await;
5081
5082        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5083        pretty_assertions::assert_eq!(
5084            entries,
5085            [
5086                GitListEntry::Header(GitHeaderEntry {
5087                    header: Section::Tracked
5088                }),
5089                GitListEntry::Status(GitStatusEntry {
5090                    repo_path: repo_path("crates/gpui/gpui.rs"),
5091                    status: StatusCode::Modified.worktree(),
5092                    staging: StageStatus::Unstaged,
5093                }),
5094                GitListEntry::Status(GitStatusEntry {
5095                    repo_path: repo_path("crates/util/util.rs"),
5096                    status: StatusCode::Modified.worktree(),
5097                    staging: StageStatus::Unstaged,
5098                },),
5099            ],
5100        );
5101
5102        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5103            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5104        });
5105        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5106        handle.await;
5107        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5108        pretty_assertions::assert_eq!(
5109            entries,
5110            [
5111                GitListEntry::Header(GitHeaderEntry {
5112                    header: Section::Tracked
5113                }),
5114                GitListEntry::Status(GitStatusEntry {
5115                    repo_path: repo_path("crates/gpui/gpui.rs"),
5116                    status: StatusCode::Modified.worktree(),
5117                    staging: StageStatus::Unstaged,
5118                }),
5119                GitListEntry::Status(GitStatusEntry {
5120                    repo_path: repo_path("crates/util/util.rs"),
5121                    status: StatusCode::Modified.worktree(),
5122                    staging: StageStatus::Unstaged,
5123                },),
5124            ],
5125        );
5126    }
5127
5128    #[gpui::test]
5129    async fn test_bulk_staging(cx: &mut TestAppContext) {
5130        use GitListEntry::*;
5131
5132        init_test(cx);
5133        let fs = FakeFs::new(cx.background_executor.clone());
5134        fs.insert_tree(
5135            "/root",
5136            json!({
5137                "project": {
5138                    ".git": {},
5139                    "src": {
5140                        "main.rs": "fn main() {}",
5141                        "lib.rs": "pub fn hello() {}",
5142                        "utils.rs": "pub fn util() {}"
5143                    },
5144                    "tests": {
5145                        "test.rs": "fn test() {}"
5146                    },
5147                    "new_file.txt": "new content",
5148                    "another_new.rs": "// new file",
5149                    "conflict.txt": "conflicted content"
5150                }
5151            }),
5152        )
5153        .await;
5154
5155        fs.set_status_for_repo(
5156            Path::new(path!("/root/project/.git")),
5157            &[
5158                ("src/main.rs", StatusCode::Modified.worktree()),
5159                ("src/lib.rs", StatusCode::Modified.worktree()),
5160                ("tests/test.rs", StatusCode::Modified.worktree()),
5161                ("new_file.txt", FileStatus::Untracked),
5162                ("another_new.rs", FileStatus::Untracked),
5163                ("src/utils.rs", FileStatus::Untracked),
5164                (
5165                    "conflict.txt",
5166                    UnmergedStatus {
5167                        first_head: UnmergedStatusCode::Updated,
5168                        second_head: UnmergedStatusCode::Updated,
5169                    }
5170                    .into(),
5171                ),
5172            ],
5173        );
5174
5175        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5176        let workspace =
5177            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5178        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5179
5180        cx.read(|cx| {
5181            project
5182                .read(cx)
5183                .worktrees(cx)
5184                .next()
5185                .unwrap()
5186                .read(cx)
5187                .as_local()
5188                .unwrap()
5189                .scan_complete()
5190        })
5191        .await;
5192
5193        cx.executor().run_until_parked();
5194
5195        let panel = workspace.update(cx, GitPanel::new).unwrap();
5196
5197        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5198            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5199        });
5200        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5201        handle.await;
5202
5203        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5204        #[rustfmt::skip]
5205        pretty_assertions::assert_matches!(
5206            entries.as_slice(),
5207            &[
5208                Header(GitHeaderEntry { header: Section::Conflict }),
5209                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5210                Header(GitHeaderEntry { header: Section::Tracked }),
5211                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5212                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5213                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5214                Header(GitHeaderEntry { header: Section::New }),
5215                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5216                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5217                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5218            ],
5219        );
5220
5221        let second_status_entry = entries[3].clone();
5222        panel.update_in(cx, |panel, window, cx| {
5223            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5224        });
5225
5226        panel.update_in(cx, |panel, window, cx| {
5227            panel.selected_entry = Some(7);
5228            panel.stage_range(&git::StageRange, window, cx);
5229        });
5230
5231        cx.read(|cx| {
5232            project
5233                .read(cx)
5234                .worktrees(cx)
5235                .next()
5236                .unwrap()
5237                .read(cx)
5238                .as_local()
5239                .unwrap()
5240                .scan_complete()
5241        })
5242        .await;
5243
5244        cx.executor().run_until_parked();
5245
5246        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5247            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5248        });
5249        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5250        handle.await;
5251
5252        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5253        #[rustfmt::skip]
5254        pretty_assertions::assert_matches!(
5255            entries.as_slice(),
5256            &[
5257                Header(GitHeaderEntry { header: Section::Conflict }),
5258                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5259                Header(GitHeaderEntry { header: Section::Tracked }),
5260                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5261                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5262                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5263                Header(GitHeaderEntry { header: Section::New }),
5264                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5265                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5266                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5267            ],
5268        );
5269
5270        let third_status_entry = entries[4].clone();
5271        panel.update_in(cx, |panel, window, cx| {
5272            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5273        });
5274
5275        panel.update_in(cx, |panel, window, cx| {
5276            panel.selected_entry = Some(9);
5277            panel.stage_range(&git::StageRange, window, cx);
5278        });
5279
5280        cx.read(|cx| {
5281            project
5282                .read(cx)
5283                .worktrees(cx)
5284                .next()
5285                .unwrap()
5286                .read(cx)
5287                .as_local()
5288                .unwrap()
5289                .scan_complete()
5290        })
5291        .await;
5292
5293        cx.executor().run_until_parked();
5294
5295        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5296            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5297        });
5298        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5299        handle.await;
5300
5301        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5302        #[rustfmt::skip]
5303        pretty_assertions::assert_matches!(
5304            entries.as_slice(),
5305            &[
5306                Header(GitHeaderEntry { header: Section::Conflict }),
5307                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5308                Header(GitHeaderEntry { header: Section::Tracked }),
5309                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5310                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5311                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5312                Header(GitHeaderEntry { header: Section::New }),
5313                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5314                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5315                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5316            ],
5317        );
5318    }
5319
5320    #[gpui::test]
5321    async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
5322        use GitListEntry::*;
5323
5324        init_test(cx);
5325        let fs = FakeFs::new(cx.background_executor.clone());
5326        fs.insert_tree(
5327            "/root",
5328            json!({
5329                "project": {
5330                    ".git": {},
5331                    "src": {
5332                        "main.rs": "fn main() {}",
5333                        "lib.rs": "pub fn hello() {}",
5334                        "utils.rs": "pub fn util() {}"
5335                    },
5336                    "tests": {
5337                        "test.rs": "fn test() {}"
5338                    },
5339                    "new_file.txt": "new content",
5340                    "another_new.rs": "// new file",
5341                    "conflict.txt": "conflicted content"
5342                }
5343            }),
5344        )
5345        .await;
5346
5347        fs.set_status_for_repo(
5348            Path::new(path!("/root/project/.git")),
5349            &[
5350                ("src/main.rs", StatusCode::Modified.worktree()),
5351                ("src/lib.rs", StatusCode::Modified.worktree()),
5352                ("tests/test.rs", StatusCode::Modified.worktree()),
5353                ("new_file.txt", FileStatus::Untracked),
5354                ("another_new.rs", FileStatus::Untracked),
5355                ("src/utils.rs", FileStatus::Untracked),
5356                (
5357                    "conflict.txt",
5358                    UnmergedStatus {
5359                        first_head: UnmergedStatusCode::Updated,
5360                        second_head: UnmergedStatusCode::Updated,
5361                    }
5362                    .into(),
5363                ),
5364            ],
5365        );
5366
5367        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5368        let workspace =
5369            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5370        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5371
5372        cx.read(|cx| {
5373            project
5374                .read(cx)
5375                .worktrees(cx)
5376                .next()
5377                .unwrap()
5378                .read(cx)
5379                .as_local()
5380                .unwrap()
5381                .scan_complete()
5382        })
5383        .await;
5384
5385        cx.executor().run_until_parked();
5386
5387        let panel = workspace.update(cx, GitPanel::new).unwrap();
5388
5389        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5390            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5391        });
5392        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5393        handle.await;
5394
5395        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5396        #[rustfmt::skip]
5397        pretty_assertions::assert_matches!(
5398            entries.as_slice(),
5399            &[
5400                Header(GitHeaderEntry { header: Section::Conflict }),
5401                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5402                Header(GitHeaderEntry { header: Section::Tracked }),
5403                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5404                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5405                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5406                Header(GitHeaderEntry { header: Section::New }),
5407                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5408                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5409                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5410            ],
5411        );
5412
5413        assert_entry_paths(
5414            &entries,
5415            &[
5416                None,
5417                Some("conflict.txt"),
5418                None,
5419                Some("src/lib.rs"),
5420                Some("src/main.rs"),
5421                Some("tests/test.rs"),
5422                None,
5423                Some("another_new.rs"),
5424                Some("new_file.txt"),
5425                Some("src/utils.rs"),
5426            ],
5427        );
5428
5429        let second_status_entry = entries[3].clone();
5430        panel.update_in(cx, |panel, window, cx| {
5431            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5432        });
5433
5434        cx.update(|_window, cx| {
5435            SettingsStore::update_global(cx, |store, cx| {
5436                store.update_user_settings(cx, |settings| {
5437                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5438                })
5439            });
5440        });
5441
5442        panel.update_in(cx, |panel, window, cx| {
5443            panel.selected_entry = Some(7);
5444            panel.stage_range(&git::StageRange, window, cx);
5445        });
5446
5447        cx.read(|cx| {
5448            project
5449                .read(cx)
5450                .worktrees(cx)
5451                .next()
5452                .unwrap()
5453                .read(cx)
5454                .as_local()
5455                .unwrap()
5456                .scan_complete()
5457        })
5458        .await;
5459
5460        cx.executor().run_until_parked();
5461
5462        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5463            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5464        });
5465        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5466        handle.await;
5467
5468        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5469        #[rustfmt::skip]
5470        pretty_assertions::assert_matches!(
5471            entries.as_slice(),
5472            &[
5473                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5474                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5475                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5476                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5477                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5478                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5479                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5480            ],
5481        );
5482
5483        assert_entry_paths(
5484            &entries,
5485            &[
5486                Some("another_new.rs"),
5487                Some("conflict.txt"),
5488                Some("new_file.txt"),
5489                Some("src/lib.rs"),
5490                Some("src/main.rs"),
5491                Some("src/utils.rs"),
5492                Some("tests/test.rs"),
5493            ],
5494        );
5495
5496        let third_status_entry = entries[4].clone();
5497        panel.update_in(cx, |panel, window, cx| {
5498            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5499        });
5500
5501        panel.update_in(cx, |panel, window, cx| {
5502            panel.selected_entry = Some(9);
5503            panel.stage_range(&git::StageRange, window, cx);
5504        });
5505
5506        cx.read(|cx| {
5507            project
5508                .read(cx)
5509                .worktrees(cx)
5510                .next()
5511                .unwrap()
5512                .read(cx)
5513                .as_local()
5514                .unwrap()
5515                .scan_complete()
5516        })
5517        .await;
5518
5519        cx.executor().run_until_parked();
5520
5521        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5522            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5523        });
5524        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5525        handle.await;
5526
5527        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5528        #[rustfmt::skip]
5529        pretty_assertions::assert_matches!(
5530            entries.as_slice(),
5531            &[
5532                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5533                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5534                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5535                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5536                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5537                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5538                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5539            ],
5540        );
5541
5542        assert_entry_paths(
5543            &entries,
5544            &[
5545                Some("another_new.rs"),
5546                Some("conflict.txt"),
5547                Some("new_file.txt"),
5548                Some("src/lib.rs"),
5549                Some("src/main.rs"),
5550                Some("src/utils.rs"),
5551                Some("tests/test.rs"),
5552            ],
5553        );
5554    }
5555
5556    #[gpui::test]
5557    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5558        init_test(cx);
5559        let fs = FakeFs::new(cx.background_executor.clone());
5560        fs.insert_tree(
5561            "/root",
5562            json!({
5563                "project": {
5564                    ".git": {},
5565                    "src": {
5566                        "main.rs": "fn main() {}"
5567                    }
5568                }
5569            }),
5570        )
5571        .await;
5572
5573        fs.set_status_for_repo(
5574            Path::new(path!("/root/project/.git")),
5575            &[("src/main.rs", StatusCode::Modified.worktree())],
5576        );
5577
5578        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5579        let workspace =
5580            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5581        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5582
5583        let panel = workspace.update(cx, GitPanel::new).unwrap();
5584
5585        // Test: User has commit message, enables amend (saves message), then disables (restores message)
5586        panel.update(cx, |panel, cx| {
5587            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5588                let start = buffer.anchor_before(0);
5589                let end = buffer.anchor_after(buffer.len());
5590                buffer.edit([(start..end, "Initial commit message")], None, cx);
5591            });
5592
5593            panel.set_amend_pending(true, cx);
5594            assert!(panel.original_commit_message.is_some());
5595
5596            panel.set_amend_pending(false, cx);
5597            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5598            assert_eq!(current_message, "Initial commit message");
5599            assert!(panel.original_commit_message.is_none());
5600        });
5601
5602        // Test: User has empty commit message, enables amend, then disables (clears message)
5603        panel.update(cx, |panel, cx| {
5604            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5605                let start = buffer.anchor_before(0);
5606                let end = buffer.anchor_after(buffer.len());
5607                buffer.edit([(start..end, "")], None, cx);
5608            });
5609
5610            panel.set_amend_pending(true, cx);
5611            assert!(panel.original_commit_message.is_none());
5612
5613            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5614                let start = buffer.anchor_before(0);
5615                let end = buffer.anchor_after(buffer.len());
5616                buffer.edit([(start..end, "Previous commit message")], None, cx);
5617            });
5618
5619            panel.set_amend_pending(false, cx);
5620            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5621            assert_eq!(current_message, "");
5622        });
5623    }
5624
5625    #[gpui::test]
5626    async fn test_open_diff(cx: &mut TestAppContext) {
5627        init_test(cx);
5628
5629        let fs = FakeFs::new(cx.background_executor.clone());
5630        fs.insert_tree(
5631            path!("/project"),
5632            json!({
5633                ".git": {},
5634                "tracked": "tracked\n",
5635                "untracked": "\n",
5636            }),
5637        )
5638        .await;
5639
5640        fs.set_head_and_index_for_repo(
5641            path!("/project/.git").as_ref(),
5642            &[("tracked", "old tracked\n".into())],
5643        );
5644
5645        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
5646        let workspace =
5647            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5648        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5649        let panel = workspace.update(cx, GitPanel::new).unwrap();
5650
5651        // Enable the `sort_by_path` setting and wait for entries to be updated,
5652        // as there should no longer be separators between Tracked and Untracked
5653        // files.
5654        cx.update(|_window, cx| {
5655            SettingsStore::update_global(cx, |store, cx| {
5656                store.update_user_settings(cx, |settings| {
5657                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5658                })
5659            });
5660        });
5661
5662        cx.update_window_entity(&panel, |panel, _, _| {
5663            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5664        })
5665        .await;
5666
5667        // Confirm that `Open Diff` still works for the untracked file, updating
5668        // the Project Diff's active path.
5669        panel.update_in(cx, |panel, window, cx| {
5670            panel.selected_entry = Some(1);
5671            panel.open_diff(&Confirm, window, cx);
5672        });
5673        cx.run_until_parked();
5674
5675        let _ = workspace.update(cx, |workspace, _window, cx| {
5676            let active_path = workspace
5677                .item_of_type::<ProjectDiff>(cx)
5678                .expect("ProjectDiff should exist")
5679                .read(cx)
5680                .active_path(cx)
5681                .expect("active_path should exist");
5682
5683            assert_eq!(active_path.path, rel_path("untracked").into_arc());
5684        });
5685    }
5686
5687    fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
5688        assert_eq!(entries.len(), expected_paths.len());
5689        for (entry, expected_path) in entries.iter().zip(expected_paths) {
5690            assert_eq!(
5691                entry.status_entry().map(|status| status
5692                    .repo_path
5693                    .0
5694                    .as_std_path()
5695                    .to_string_lossy()
5696                    .to_string()),
5697                expected_path.map(|s| s.to_string())
5698            );
5699        }
5700    }
5701}