git_panel.rs

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