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