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