git_panel.rs

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