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