git_panel.rs

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