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))
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, 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, 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        window: &mut Window,
2532        cx: &mut Context<Self>,
2533    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2534        let repo = self.active_repository.clone();
2535        let workspace = self.workspace.clone();
2536        let mut cx = window.to_async(cx);
2537
2538        async move {
2539            let repo = repo.context("No active repository")?;
2540            let current_remotes: Vec<Remote> = repo
2541                .update(&mut cx, |repo, _| {
2542                    let current_branch = if always_select {
2543                        None
2544                    } else {
2545                        let current_branch = repo.branch.as_ref().context("No active branch")?;
2546                        Some(current_branch.name().to_string())
2547                    };
2548                    anyhow::Ok(repo.get_remotes(current_branch))
2549                })??
2550                .await??;
2551
2552            let current_remotes: Vec<_> = current_remotes
2553                .into_iter()
2554                .map(|remotes| remotes.name)
2555                .collect();
2556            let selection = cx
2557                .update(|window, cx| {
2558                    picker_prompt::prompt(
2559                        "Pick which remote to push to",
2560                        current_remotes.clone(),
2561                        workspace,
2562                        window,
2563                        cx,
2564                    )
2565                })?
2566                .await;
2567
2568            Ok(selection.map(|selection| Remote {
2569                name: current_remotes[selection].clone(),
2570            }))
2571        }
2572    }
2573
2574    pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2575        if self.local_committer_task.is_none() {
2576            self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2577                let committer = get_git_committer(cx).await;
2578                this.update(cx, |this, cx| {
2579                    this.local_committer = Some(committer);
2580                    cx.notify()
2581                })
2582                .ok();
2583            }));
2584        }
2585    }
2586
2587    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2588        let mut new_co_authors = Vec::new();
2589        let project = self.project.read(cx);
2590
2591        let Some(room) = self
2592            .workspace
2593            .upgrade()
2594            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2595        else {
2596            return Vec::default();
2597        };
2598
2599        let room = room.read(cx);
2600
2601        for (peer_id, collaborator) in project.collaborators() {
2602            if collaborator.is_host {
2603                continue;
2604            }
2605
2606            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2607                continue;
2608            };
2609            if !participant.can_write() {
2610                continue;
2611            }
2612            if let Some(email) = &collaborator.committer_email {
2613                let name = collaborator
2614                    .committer_name
2615                    .clone()
2616                    .or_else(|| participant.user.name.clone())
2617                    .unwrap_or_else(|| participant.user.github_login.clone().to_string());
2618                new_co_authors.push((name.clone(), email.clone()))
2619            }
2620        }
2621        if !project.is_local()
2622            && !project.is_read_only(cx)
2623            && let Some(local_committer) = self.local_committer(room, cx)
2624        {
2625            new_co_authors.push(local_committer);
2626        }
2627        new_co_authors
2628    }
2629
2630    fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2631        let user = room.local_participant_user(cx)?;
2632        let committer = self.local_committer.as_ref()?;
2633        let email = committer.email.clone()?;
2634        let name = committer
2635            .name
2636            .clone()
2637            .or_else(|| user.name.clone())
2638            .unwrap_or_else(|| user.github_login.clone().to_string());
2639        Some((name, email))
2640    }
2641
2642    fn toggle_fill_co_authors(
2643        &mut self,
2644        _: &ToggleFillCoAuthors,
2645        _: &mut Window,
2646        cx: &mut Context<Self>,
2647    ) {
2648        self.add_coauthors = !self.add_coauthors;
2649        cx.notify();
2650    }
2651
2652    fn toggle_sort_by_path(
2653        &mut self,
2654        _: &ToggleSortByPath,
2655        _: &mut Window,
2656        cx: &mut Context<Self>,
2657    ) {
2658        let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
2659        if let Some(workspace) = self.workspace.upgrade() {
2660            let workspace = workspace.read(cx);
2661            let fs = workspace.app_state().fs.clone();
2662            cx.update_global::<SettingsStore, _>(|store, _cx| {
2663                store.update_settings_file(fs, move |settings, _cx| {
2664                    settings.git_panel.get_or_insert_default().sort_by_path =
2665                        Some(!current_setting);
2666                });
2667            });
2668        }
2669    }
2670
2671    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2672        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2673
2674        let existing_text = message.to_ascii_lowercase();
2675        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2676        let mut ends_with_co_authors = false;
2677        let existing_co_authors = existing_text
2678            .lines()
2679            .filter_map(|line| {
2680                let line = line.trim();
2681                if line.starts_with(&lowercase_co_author_prefix) {
2682                    ends_with_co_authors = true;
2683                    Some(line)
2684                } else {
2685                    ends_with_co_authors = false;
2686                    None
2687                }
2688            })
2689            .collect::<HashSet<_>>();
2690
2691        let new_co_authors = self
2692            .potential_co_authors(cx)
2693            .into_iter()
2694            .filter(|(_, email)| {
2695                !existing_co_authors
2696                    .iter()
2697                    .any(|existing| existing.contains(email.as_str()))
2698            })
2699            .collect::<Vec<_>>();
2700
2701        if new_co_authors.is_empty() {
2702            return;
2703        }
2704
2705        if !ends_with_co_authors {
2706            message.push('\n');
2707        }
2708        for (name, email) in new_co_authors {
2709            message.push('\n');
2710            message.push_str(CO_AUTHOR_PREFIX);
2711            message.push_str(&name);
2712            message.push_str(" <");
2713            message.push_str(&email);
2714            message.push('>');
2715        }
2716        message.push('\n');
2717    }
2718
2719    fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2720        let handle = cx.entity().downgrade();
2721        self.reopen_commit_buffer(window, cx);
2722        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2723            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2724            if let Some(git_panel) = handle.upgrade() {
2725                git_panel
2726                    .update_in(cx, |git_panel, window, cx| {
2727                        git_panel.update_visible_entries(window, cx);
2728                    })
2729                    .ok();
2730            }
2731        });
2732    }
2733
2734    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2735        let Some(active_repo) = self.active_repository.as_ref() else {
2736            return;
2737        };
2738        let load_buffer = active_repo.update(cx, |active_repo, cx| {
2739            let project = self.project.read(cx);
2740            active_repo.open_commit_buffer(
2741                Some(project.languages().clone()),
2742                project.buffer_store().clone(),
2743                cx,
2744            )
2745        });
2746
2747        cx.spawn_in(window, async move |git_panel, cx| {
2748            let buffer = load_buffer.await?;
2749            git_panel.update_in(cx, |git_panel, window, cx| {
2750                if git_panel
2751                    .commit_editor
2752                    .read(cx)
2753                    .buffer()
2754                    .read(cx)
2755                    .as_singleton()
2756                    .as_ref()
2757                    != Some(&buffer)
2758                {
2759                    git_panel.commit_editor = cx.new(|cx| {
2760                        commit_message_editor(
2761                            buffer,
2762                            git_panel.suggest_commit_message(cx).map(SharedString::from),
2763                            git_panel.project.clone(),
2764                            true,
2765                            window,
2766                            cx,
2767                        )
2768                    });
2769                }
2770            })
2771        })
2772        .detach_and_log_err(cx);
2773    }
2774
2775    fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2776        let path_style = self.project.read(cx).path_style(cx);
2777        let bulk_staging = self.bulk_staging.take();
2778        let last_staged_path_prev_index = bulk_staging
2779            .as_ref()
2780            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2781
2782        self.entries.clear();
2783        self.single_staged_entry.take();
2784        self.single_tracked_entry.take();
2785        self.conflicted_count = 0;
2786        self.conflicted_staged_count = 0;
2787        self.new_count = 0;
2788        self.tracked_count = 0;
2789        self.new_staged_count = 0;
2790        self.tracked_staged_count = 0;
2791        self.entry_count = 0;
2792
2793        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2794
2795        let mut changed_entries = Vec::new();
2796        let mut new_entries = Vec::new();
2797        let mut conflict_entries = Vec::new();
2798        let mut single_staged_entry = None;
2799        let mut staged_count = 0;
2800        let mut max_width_item: Option<(RepoPath, usize)> = None;
2801
2802        let Some(repo) = self.active_repository.as_ref() else {
2803            // Just clear entries if no repository is active.
2804            cx.notify();
2805            return;
2806        };
2807
2808        let repo = repo.read(cx);
2809
2810        self.stash_entries = repo.cached_stash();
2811
2812        for entry in repo.cached_status() {
2813            let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2814            let is_new = entry.status.is_created();
2815            let staging = entry.status.staging();
2816
2817            if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
2818                && pending
2819                    .ops
2820                    .iter()
2821                    .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
2822            {
2823                continue;
2824            }
2825
2826            let entry = GitStatusEntry {
2827                repo_path: entry.repo_path.clone(),
2828                status: entry.status,
2829                staging,
2830            };
2831
2832            if staging.has_staged() {
2833                staged_count += 1;
2834                single_staged_entry = Some(entry.clone());
2835            }
2836
2837            let width_estimate = Self::item_width_estimate(
2838                entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
2839                entry.display_name(path_style).len(),
2840            );
2841
2842            match max_width_item.as_mut() {
2843                Some((repo_path, estimate)) => {
2844                    if width_estimate > *estimate {
2845                        *repo_path = entry.repo_path.clone();
2846                        *estimate = width_estimate;
2847                    }
2848                }
2849                None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2850            }
2851
2852            if sort_by_path {
2853                changed_entries.push(entry);
2854            } else if is_conflict {
2855                conflict_entries.push(entry);
2856            } else if is_new {
2857                new_entries.push(entry);
2858            } else {
2859                changed_entries.push(entry);
2860            }
2861        }
2862
2863        if conflict_entries.is_empty() {
2864            if staged_count == 1
2865                && let Some(entry) = single_staged_entry.as_ref()
2866            {
2867                if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
2868                    if ops.staged() {
2869                        self.single_staged_entry = single_staged_entry;
2870                    }
2871                } else {
2872                    self.single_staged_entry = single_staged_entry;
2873                }
2874            } else if repo.pending_ops_summary().item_summary.staging_count == 1
2875                && let Some(ops) = repo.pending_ops().find(|ops| ops.staging())
2876            {
2877                self.single_staged_entry =
2878                    repo.status_for_path(&ops.repo_path)
2879                        .map(|status| GitStatusEntry {
2880                            repo_path: ops.repo_path.clone(),
2881                            status: status.status,
2882                            staging: StageStatus::Staged,
2883                        });
2884            }
2885        }
2886
2887        if conflict_entries.is_empty() && changed_entries.len() == 1 {
2888            self.single_tracked_entry = changed_entries.first().cloned();
2889        }
2890
2891        if !conflict_entries.is_empty() {
2892            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2893                header: Section::Conflict,
2894            }));
2895            self.entries
2896                .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2897        }
2898
2899        if !changed_entries.is_empty() {
2900            if !sort_by_path {
2901                self.entries.push(GitListEntry::Header(GitHeaderEntry {
2902                    header: Section::Tracked,
2903                }));
2904            }
2905            self.entries
2906                .extend(changed_entries.into_iter().map(GitListEntry::Status));
2907        }
2908        if !new_entries.is_empty() {
2909            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2910                header: Section::New,
2911            }));
2912            self.entries
2913                .extend(new_entries.into_iter().map(GitListEntry::Status));
2914        }
2915
2916        if let Some((repo_path, _)) = max_width_item {
2917            self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2918                GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2919                GitListEntry::Header(_) => false,
2920            });
2921        }
2922
2923        self.update_counts(repo);
2924
2925        let bulk_staging_anchor_new_index = bulk_staging
2926            .as_ref()
2927            .filter(|op| op.repo_id == repo.id)
2928            .and_then(|op| self.entry_by_path(&op.anchor, cx));
2929        if bulk_staging_anchor_new_index == last_staged_path_prev_index
2930            && let Some(index) = bulk_staging_anchor_new_index
2931            && let Some(entry) = self.entries.get(index)
2932            && let Some(entry) = entry.status_entry()
2933            && repo
2934                .pending_ops_for_path(&entry.repo_path)
2935                .map(|ops| ops.staging() || ops.staged())
2936                .unwrap_or(entry.staging.has_staged())
2937        {
2938            self.bulk_staging = bulk_staging;
2939        }
2940
2941        self.select_first_entry_if_none(cx);
2942
2943        let suggested_commit_message = self.suggest_commit_message(cx);
2944        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2945
2946        self.commit_editor.update(cx, |editor, cx| {
2947            editor.set_placeholder_text(&placeholder_text, window, cx)
2948        });
2949
2950        cx.notify();
2951    }
2952
2953    fn header_state(&self, header_type: Section) -> ToggleState {
2954        let (staged_count, count) = match header_type {
2955            Section::New => (self.new_staged_count, self.new_count),
2956            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2957            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2958        };
2959        if staged_count == 0 {
2960            ToggleState::Unselected
2961        } else if count == staged_count {
2962            ToggleState::Selected
2963        } else {
2964            ToggleState::Indeterminate
2965        }
2966    }
2967
2968    fn update_counts(&mut self, repo: &Repository) {
2969        self.show_placeholders = false;
2970        self.conflicted_count = 0;
2971        self.conflicted_staged_count = 0;
2972        self.new_count = 0;
2973        self.tracked_count = 0;
2974        self.new_staged_count = 0;
2975        self.tracked_staged_count = 0;
2976        self.entry_count = 0;
2977        for entry in &self.entries {
2978            let Some(status_entry) = entry.status_entry() else {
2979                continue;
2980            };
2981            self.entry_count += 1;
2982            let is_staging_or_staged = repo
2983                .pending_ops_for_path(&status_entry.repo_path)
2984                .map(|ops| ops.staging() || ops.staged())
2985                .unwrap_or(status_entry.staging.has_staged());
2986            if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2987                self.conflicted_count += 1;
2988                if is_staging_or_staged {
2989                    self.conflicted_staged_count += 1;
2990                }
2991            } else if status_entry.status.is_created() {
2992                self.new_count += 1;
2993                if is_staging_or_staged {
2994                    self.new_staged_count += 1;
2995                }
2996            } else {
2997                self.tracked_count += 1;
2998                if is_staging_or_staged {
2999                    self.tracked_staged_count += 1;
3000                }
3001            }
3002        }
3003    }
3004
3005    pub(crate) fn has_staged_changes(&self) -> bool {
3006        self.tracked_staged_count > 0
3007            || self.new_staged_count > 0
3008            || self.conflicted_staged_count > 0
3009    }
3010
3011    pub(crate) fn has_unstaged_changes(&self) -> bool {
3012        self.tracked_count > self.tracked_staged_count
3013            || self.new_count > self.new_staged_count
3014            || self.conflicted_count > self.conflicted_staged_count
3015    }
3016
3017    fn has_tracked_changes(&self) -> bool {
3018        self.tracked_count > 0
3019    }
3020
3021    pub fn has_unstaged_conflicts(&self) -> bool {
3022        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
3023    }
3024
3025    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
3026        let action = action.into();
3027        let Some(workspace) = self.workspace.upgrade() else {
3028            return;
3029        };
3030
3031        let message = e.to_string().trim().to_string();
3032        if message
3033            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
3034            .next()
3035            .is_some()
3036        { // Hide the cancelled by user message
3037        } else {
3038            workspace.update(cx, |workspace, cx| {
3039                let workspace_weak = cx.weak_entity();
3040                let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
3041                    this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
3042                        .action("View Log", move |window, cx| {
3043                            let message = message.clone();
3044                            let action = action.clone();
3045                            workspace_weak
3046                                .update(cx, move |workspace, cx| {
3047                                    Self::open_output(action, workspace, &message, window, cx)
3048                                })
3049                                .ok();
3050                        })
3051                });
3052                workspace.toggle_status_toast(toast, cx)
3053            });
3054        }
3055    }
3056
3057    fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3058    where
3059        E: std::fmt::Debug + std::fmt::Display,
3060    {
3061        if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3062            let _ = workspace.update(cx, |workspace, cx| {
3063                struct CommitMessageError;
3064                let notification_id = NotificationId::unique::<CommitMessageError>();
3065                workspace.show_notification(notification_id, cx, |cx| {
3066                    cx.new(|cx| {
3067                        ErrorMessagePrompt::new(
3068                            format!("Failed to generate commit message: {err}"),
3069                            cx,
3070                        )
3071                    })
3072                });
3073            });
3074        }
3075    }
3076
3077    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
3078        let Some(workspace) = self.workspace.upgrade() else {
3079            return;
3080        };
3081
3082        workspace.update(cx, |workspace, cx| {
3083            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3084            let workspace_weak = cx.weak_entity();
3085            let operation = action.name();
3086
3087            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3088                use remote_output::SuccessStyle::*;
3089                match style {
3090                    Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3091                    ToastWithLog { output } => this
3092                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3093                        .action("View Log", move |window, cx| {
3094                            let output = output.clone();
3095                            let output =
3096                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3097                            workspace_weak
3098                                .update(cx, move |workspace, cx| {
3099                                    Self::open_output(operation, workspace, &output, window, cx)
3100                                })
3101                                .ok();
3102                        }),
3103                    PushPrLink { text, link } => this
3104                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3105                        .action(text, move |_, cx| cx.open_url(&link)),
3106                }
3107            });
3108            workspace.toggle_status_toast(status_toast, cx)
3109        });
3110    }
3111
3112    fn open_output(
3113        operation: impl Into<SharedString>,
3114        workspace: &mut Workspace,
3115        output: &str,
3116        window: &mut Window,
3117        cx: &mut Context<Workspace>,
3118    ) {
3119        let operation = operation.into();
3120        let buffer = cx.new(|cx| Buffer::local(output, cx));
3121        buffer.update(cx, |buffer, cx| {
3122            buffer.set_capability(language::Capability::ReadOnly, cx);
3123        });
3124        let editor = cx.new(|cx| {
3125            let mut editor = Editor::for_buffer(buffer, None, window, cx);
3126            editor.buffer().update(cx, |buffer, cx| {
3127                buffer.set_title(format!("Output from git {operation}"), cx);
3128            });
3129            editor.set_read_only(true);
3130            editor
3131        });
3132
3133        workspace.add_item_to_center(Box::new(editor), window, cx);
3134    }
3135
3136    pub fn can_commit(&self) -> bool {
3137        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3138    }
3139
3140    pub fn can_stage_all(&self) -> bool {
3141        self.has_unstaged_changes()
3142    }
3143
3144    pub fn can_unstage_all(&self) -> bool {
3145        self.has_staged_changes()
3146    }
3147
3148    // eventually we'll need to take depth into account here
3149    // if we add a tree view
3150    fn item_width_estimate(path: usize, file_name: usize) -> usize {
3151        path + file_name
3152    }
3153
3154    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3155        let focus_handle = self.focus_handle.clone();
3156        let has_tracked_changes = self.has_tracked_changes();
3157        let has_staged_changes = self.has_staged_changes();
3158        let has_unstaged_changes = self.has_unstaged_changes();
3159        let has_new_changes = self.new_count > 0;
3160        let has_stash_items = self.stash_entries.entries.len() > 0;
3161
3162        PopoverMenu::new(id.into())
3163            .trigger(
3164                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3165                    .icon_size(IconSize::Small)
3166                    .icon_color(Color::Muted),
3167            )
3168            .menu(move |window, cx| {
3169                Some(git_panel_context_menu(
3170                    focus_handle.clone(),
3171                    GitMenuState {
3172                        has_tracked_changes,
3173                        has_staged_changes,
3174                        has_unstaged_changes,
3175                        has_new_changes,
3176                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3177                        has_stash_items,
3178                    },
3179                    window,
3180                    cx,
3181                ))
3182            })
3183            .anchor(Corner::TopRight)
3184    }
3185
3186    pub(crate) fn render_generate_commit_message_button(
3187        &self,
3188        cx: &Context<Self>,
3189    ) -> Option<AnyElement> {
3190        if !agent_settings::AgentSettings::get_global(cx).enabled(cx)
3191            || LanguageModelRegistry::read_global(cx)
3192                .commit_message_model()
3193                .is_none()
3194        {
3195            return None;
3196        }
3197
3198        if self.generate_commit_message_task.is_some() {
3199            return Some(
3200                h_flex()
3201                    .gap_1()
3202                    .child(
3203                        Icon::new(IconName::ArrowCircle)
3204                            .size(IconSize::XSmall)
3205                            .color(Color::Info)
3206                            .with_rotate_animation(2),
3207                    )
3208                    .child(
3209                        Label::new("Generating Commit...")
3210                            .size(LabelSize::Small)
3211                            .color(Color::Muted),
3212                    )
3213                    .into_any_element(),
3214            );
3215        }
3216
3217        let can_commit = self.can_commit();
3218        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3219        Some(
3220            IconButton::new("generate-commit-message", IconName::AiEdit)
3221                .shape(ui::IconButtonShape::Square)
3222                .icon_color(Color::Muted)
3223                .tooltip(move |_window, cx| {
3224                    if can_commit {
3225                        Tooltip::for_action_in(
3226                            "Generate Commit Message",
3227                            &git::GenerateCommitMessage,
3228                            &editor_focus_handle,
3229                            cx,
3230                        )
3231                    } else {
3232                        Tooltip::simple("No changes to commit", cx)
3233                    }
3234                })
3235                .disabled(!can_commit)
3236                .on_click(cx.listener(move |this, _event, _window, cx| {
3237                    this.generate_commit_message(cx);
3238                }))
3239                .into_any_element(),
3240        )
3241    }
3242
3243    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3244        let potential_co_authors = self.potential_co_authors(cx);
3245
3246        let (tooltip_label, icon) = if self.add_coauthors {
3247            ("Remove co-authored-by", IconName::Person)
3248        } else {
3249            ("Add co-authored-by", IconName::UserCheck)
3250        };
3251
3252        if potential_co_authors.is_empty() {
3253            None
3254        } else {
3255            Some(
3256                IconButton::new("co-authors", icon)
3257                    .shape(ui::IconButtonShape::Square)
3258                    .icon_color(Color::Disabled)
3259                    .selected_icon_color(Color::Selected)
3260                    .toggle_state(self.add_coauthors)
3261                    .tooltip(move |_, cx| {
3262                        let title = format!(
3263                            "{}:{}{}",
3264                            tooltip_label,
3265                            if potential_co_authors.len() == 1 {
3266                                ""
3267                            } else {
3268                                "\n"
3269                            },
3270                            potential_co_authors
3271                                .iter()
3272                                .map(|(name, email)| format!(" {} <{}>", name, email))
3273                                .join("\n")
3274                        );
3275                        Tooltip::simple(title, cx)
3276                    })
3277                    .on_click(cx.listener(|this, _, _, cx| {
3278                        this.add_coauthors = !this.add_coauthors;
3279                        cx.notify();
3280                    }))
3281                    .into_any_element(),
3282            )
3283        }
3284    }
3285
3286    fn render_git_commit_menu(
3287        &self,
3288        id: impl Into<ElementId>,
3289        keybinding_target: Option<FocusHandle>,
3290        cx: &mut Context<Self>,
3291    ) -> impl IntoElement {
3292        PopoverMenu::new(id.into())
3293            .trigger(
3294                ui::ButtonLike::new_rounded_right("commit-split-button-right")
3295                    .layer(ui::ElevationIndex::ModalSurface)
3296                    .size(ButtonSize::None)
3297                    .child(
3298                        h_flex()
3299                            .px_1()
3300                            .h_full()
3301                            .justify_center()
3302                            .border_l_1()
3303                            .border_color(cx.theme().colors().border)
3304                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3305                    ),
3306            )
3307            .menu({
3308                let git_panel = cx.entity();
3309                let has_previous_commit = self.head_commit(cx).is_some();
3310                let amend = self.amend_pending();
3311                let signoff = self.signoff_enabled;
3312
3313                move |window, cx| {
3314                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3315                        context_menu
3316                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
3317                                el.context(keybinding_target)
3318                            })
3319                            .when(has_previous_commit, |this| {
3320                                this.toggleable_entry(
3321                                    "Amend",
3322                                    amend,
3323                                    IconPosition::Start,
3324                                    Some(Box::new(Amend)),
3325                                    {
3326                                        let git_panel = git_panel.downgrade();
3327                                        move |_, cx| {
3328                                            git_panel
3329                                                .update(cx, |git_panel, cx| {
3330                                                    git_panel.toggle_amend_pending(cx);
3331                                                })
3332                                                .ok();
3333                                        }
3334                                    },
3335                                )
3336                            })
3337                            .toggleable_entry(
3338                                "Signoff",
3339                                signoff,
3340                                IconPosition::Start,
3341                                Some(Box::new(Signoff)),
3342                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3343                            )
3344                    }))
3345                }
3346            })
3347            .anchor(Corner::TopRight)
3348    }
3349
3350    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3351        if self.has_unstaged_conflicts() {
3352            (false, "You must resolve conflicts before committing")
3353        } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
3354            (false, "No changes to commit")
3355        } else if self.pending_commit.is_some() {
3356            (false, "Commit in progress")
3357        } else if !self.has_commit_message(cx) {
3358            (false, "No commit message")
3359        } else if !self.has_write_access(cx) {
3360            (false, "You do not have write access to this project")
3361        } else {
3362            (true, self.commit_button_title())
3363        }
3364    }
3365
3366    pub fn commit_button_title(&self) -> &'static str {
3367        if self.amend_pending {
3368            if self.has_staged_changes() {
3369                "Amend"
3370            } else if self.has_tracked_changes() {
3371                "Amend Tracked"
3372            } else {
3373                "Amend"
3374            }
3375        } else if self.has_staged_changes() {
3376            "Commit"
3377        } else {
3378            "Commit Tracked"
3379        }
3380    }
3381
3382    fn expand_commit_editor(
3383        &mut self,
3384        _: &git::ExpandCommitEditor,
3385        window: &mut Window,
3386        cx: &mut Context<Self>,
3387    ) {
3388        let workspace = self.workspace.clone();
3389        window.defer(cx, move |window, cx| {
3390            workspace
3391                .update(cx, |workspace, cx| {
3392                    CommitModal::toggle(workspace, None, window, cx)
3393                })
3394                .ok();
3395        })
3396    }
3397
3398    fn render_panel_header(
3399        &self,
3400        window: &mut Window,
3401        cx: &mut Context<Self>,
3402    ) -> Option<impl IntoElement> {
3403        self.active_repository.as_ref()?;
3404
3405        let (text, action, stage, tooltip) =
3406            if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3407                ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
3408            } else {
3409                ("Stage All", StageAll.boxed_clone(), true, "git add --all")
3410            };
3411
3412        let change_string = match self.entry_count {
3413            0 => "No Changes".to_string(),
3414            1 => "1 Change".to_string(),
3415            _ => format!("{} Changes", self.entry_count),
3416        };
3417
3418        Some(
3419            self.panel_header_container(window, cx)
3420                .px_2()
3421                .justify_between()
3422                .child(
3423                    panel_button(change_string)
3424                        .color(Color::Muted)
3425                        .tooltip(Tooltip::for_action_title_in(
3426                            "Open Diff",
3427                            &Diff,
3428                            &self.focus_handle,
3429                        ))
3430                        .on_click(|_, _, cx| {
3431                            cx.defer(|cx| {
3432                                cx.dispatch_action(&Diff);
3433                            })
3434                        }),
3435                )
3436                .child(
3437                    h_flex()
3438                        .gap_1()
3439                        .child(self.render_overflow_menu("overflow_menu"))
3440                        .child(
3441                            panel_filled_button(text)
3442                                .tooltip(Tooltip::for_action_title_in(
3443                                    tooltip,
3444                                    action.as_ref(),
3445                                    &self.focus_handle,
3446                                ))
3447                                .disabled(self.entry_count == 0)
3448                                .on_click({
3449                                    let git_panel = cx.weak_entity();
3450                                    move |_, _, cx| {
3451                                        git_panel
3452                                            .update(cx, |git_panel, cx| {
3453                                                git_panel.change_all_files_stage(stage, cx);
3454                                            })
3455                                            .ok();
3456                                    }
3457                                }),
3458                        ),
3459                ),
3460        )
3461    }
3462
3463    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3464        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3465        if !self.can_push_and_pull(cx) {
3466            return None;
3467        }
3468        Some(
3469            h_flex()
3470                .gap_1()
3471                .flex_shrink_0()
3472                .when_some(branch, |this, branch| {
3473                    let focus_handle = Some(self.focus_handle(cx));
3474
3475                    this.children(render_remote_button(
3476                        "remote-button",
3477                        &branch,
3478                        focus_handle,
3479                        true,
3480                    ))
3481                })
3482                .into_any_element(),
3483        )
3484    }
3485
3486    pub fn render_footer(
3487        &self,
3488        window: &mut Window,
3489        cx: &mut Context<Self>,
3490    ) -> Option<impl IntoElement> {
3491        let active_repository = self.active_repository.clone()?;
3492        let panel_editor_style = panel_editor_style(true, window, cx);
3493
3494        let enable_coauthors = self.render_co_authors(cx);
3495
3496        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3497        let expand_tooltip_focus_handle = editor_focus_handle;
3498
3499        let branch = active_repository.read(cx).branch.clone();
3500        let head_commit = active_repository.read(cx).head_commit.clone();
3501
3502        let footer_size = px(32.);
3503        let gap = px(9.0);
3504        let max_height = panel_editor_style
3505            .text
3506            .line_height_in_pixels(window.rem_size())
3507            * MAX_PANEL_EDITOR_LINES
3508            + gap;
3509
3510        let git_panel = cx.entity();
3511        let display_name = SharedString::from(Arc::from(
3512            active_repository
3513                .read(cx)
3514                .display_name()
3515                .trim_end_matches("/"),
3516        ));
3517        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3518            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3519        });
3520
3521        let footer = v_flex()
3522            .child(PanelRepoFooter::new(
3523                display_name,
3524                branch,
3525                head_commit,
3526                Some(git_panel),
3527            ))
3528            .child(
3529                panel_editor_container(window, cx)
3530                    .id("commit-editor-container")
3531                    .relative()
3532                    .w_full()
3533                    .h(max_height + footer_size)
3534                    .border_t_1()
3535                    .border_color(cx.theme().colors().border)
3536                    .cursor_text()
3537                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3538                        window.focus(&this.commit_editor.focus_handle(cx));
3539                    }))
3540                    .child(
3541                        h_flex()
3542                            .id("commit-footer")
3543                            .border_t_1()
3544                            .when(editor_is_long, |el| {
3545                                el.border_color(cx.theme().colors().border_variant)
3546                            })
3547                            .absolute()
3548                            .bottom_0()
3549                            .left_0()
3550                            .w_full()
3551                            .px_2()
3552                            .h(footer_size)
3553                            .flex_none()
3554                            .justify_between()
3555                            .child(
3556                                self.render_generate_commit_message_button(cx)
3557                                    .unwrap_or_else(|| div().into_any_element()),
3558                            )
3559                            .child(
3560                                h_flex()
3561                                    .gap_0p5()
3562                                    .children(enable_coauthors)
3563                                    .child(self.render_commit_button(cx)),
3564                            ),
3565                    )
3566                    .child(
3567                        div()
3568                            .pr_2p5()
3569                            .on_action(|&editor::actions::MoveUp, _, cx| {
3570                                cx.stop_propagation();
3571                            })
3572                            .on_action(|&editor::actions::MoveDown, _, cx| {
3573                                cx.stop_propagation();
3574                            })
3575                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3576                    )
3577                    .child(
3578                        h_flex()
3579                            .absolute()
3580                            .top_2()
3581                            .right_2()
3582                            .opacity(0.5)
3583                            .hover(|this| this.opacity(1.0))
3584                            .child(
3585                                panel_icon_button("expand-commit-editor", IconName::Maximize)
3586                                    .icon_size(IconSize::Small)
3587                                    .size(ui::ButtonSize::Default)
3588                                    .tooltip(move |_window, cx| {
3589                                        Tooltip::for_action_in(
3590                                            "Open Commit Modal",
3591                                            &git::ExpandCommitEditor,
3592                                            &expand_tooltip_focus_handle,
3593                                            cx,
3594                                        )
3595                                    })
3596                                    .on_click(cx.listener({
3597                                        move |_, _, window, cx| {
3598                                            window.dispatch_action(
3599                                                git::ExpandCommitEditor.boxed_clone(),
3600                                                cx,
3601                                            )
3602                                        }
3603                                    })),
3604                            ),
3605                    ),
3606            );
3607
3608        Some(footer)
3609    }
3610
3611    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3612        let (can_commit, tooltip) = self.configure_commit_button(cx);
3613        let title = self.commit_button_title();
3614        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3615        let amend = self.amend_pending();
3616        let signoff = self.signoff_enabled;
3617
3618        let label_color = if self.pending_commit.is_some() {
3619            Color::Disabled
3620        } else {
3621            Color::Default
3622        };
3623
3624        div()
3625            .id("commit-wrapper")
3626            .on_hover(cx.listener(move |this, hovered, _, cx| {
3627                this.show_placeholders =
3628                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3629                cx.notify()
3630            }))
3631            .child(SplitButton::new(
3632                ButtonLike::new_rounded_left(ElementId::Name(
3633                    format!("split-button-left-{}", title).into(),
3634                ))
3635                .layer(ElevationIndex::ModalSurface)
3636                .size(ButtonSize::Compact)
3637                .child(
3638                    Label::new(title)
3639                        .size(LabelSize::Small)
3640                        .color(label_color)
3641                        .mr_0p5(),
3642                )
3643                .on_click({
3644                    let git_panel = cx.weak_entity();
3645                    move |_, window, cx| {
3646                        telemetry::event!("Git Committed", source = "Git Panel");
3647                        git_panel
3648                            .update(cx, |git_panel, cx| {
3649                                git_panel.commit_changes(
3650                                    CommitOptions { amend, signoff },
3651                                    window,
3652                                    cx,
3653                                );
3654                            })
3655                            .ok();
3656                    }
3657                })
3658                .disabled(!can_commit || self.modal_open)
3659                .tooltip({
3660                    let handle = commit_tooltip_focus_handle.clone();
3661                    move |_window, cx| {
3662                        if can_commit {
3663                            Tooltip::with_meta_in(
3664                                tooltip,
3665                                Some(if amend { &git::Amend } else { &git::Commit }),
3666                                format!(
3667                                    "git commit{}{}",
3668                                    if amend { " --amend" } else { "" },
3669                                    if signoff { " --signoff" } else { "" }
3670                                ),
3671                                &handle.clone(),
3672                                cx,
3673                            )
3674                        } else {
3675                            Tooltip::simple(tooltip, cx)
3676                        }
3677                    }
3678                }),
3679                self.render_git_commit_menu(
3680                    ElementId::Name(format!("split-button-right-{}", title).into()),
3681                    Some(commit_tooltip_focus_handle),
3682                    cx,
3683                )
3684                .into_any_element(),
3685            ))
3686    }
3687
3688    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3689        h_flex()
3690            .py_1p5()
3691            .px_2()
3692            .gap_1p5()
3693            .justify_between()
3694            .border_t_1()
3695            .border_color(cx.theme().colors().border.opacity(0.8))
3696            .child(
3697                div()
3698                    .flex_grow()
3699                    .overflow_hidden()
3700                    .max_w(relative(0.85))
3701                    .child(
3702                        Label::new("This will update your most recent commit.")
3703                            .size(LabelSize::Small)
3704                            .truncate(),
3705                    ),
3706            )
3707            .child(
3708                panel_button("Cancel")
3709                    .size(ButtonSize::Default)
3710                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3711            )
3712    }
3713
3714    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3715        let active_repository = self.active_repository.as_ref()?;
3716        let branch = active_repository.read(cx).branch.as_ref()?;
3717        let commit = branch.most_recent_commit.as_ref()?.clone();
3718        let workspace = self.workspace.clone();
3719        let this = cx.entity();
3720
3721        Some(
3722            h_flex()
3723                .py_1p5()
3724                .px_2()
3725                .gap_1p5()
3726                .justify_between()
3727                .border_t_1()
3728                .border_color(cx.theme().colors().border.opacity(0.8))
3729                .child(
3730                    div()
3731                        .cursor_pointer()
3732                        .overflow_hidden()
3733                        .line_clamp(1)
3734                        .child(
3735                            Label::new(commit.subject.clone())
3736                                .size(LabelSize::Small)
3737                                .truncate(),
3738                        )
3739                        .id("commit-msg-hover")
3740                        .on_click({
3741                            let commit = commit.clone();
3742                            let repo = active_repository.downgrade();
3743                            move |_, window, cx| {
3744                                CommitView::open(
3745                                    commit.sha.to_string(),
3746                                    repo.clone(),
3747                                    workspace.clone(),
3748                                    None,
3749                                    window,
3750                                    cx,
3751                                );
3752                            }
3753                        })
3754                        .hoverable_tooltip({
3755                            let repo = active_repository.clone();
3756                            move |window, cx| {
3757                                GitPanelMessageTooltip::new(
3758                                    this.clone(),
3759                                    commit.sha.clone(),
3760                                    repo.clone(),
3761                                    window,
3762                                    cx,
3763                                )
3764                                .into()
3765                            }
3766                        }),
3767                )
3768                .when(commit.has_parent, |this| {
3769                    let has_unstaged = self.has_unstaged_changes();
3770                    this.child(
3771                        panel_icon_button("undo", IconName::Undo)
3772                            .icon_size(IconSize::XSmall)
3773                            .icon_color(Color::Muted)
3774                            .tooltip(move |_window, cx| {
3775                                Tooltip::with_meta(
3776                                    "Uncommit",
3777                                    Some(&git::Uncommit),
3778                                    if has_unstaged {
3779                                        "git reset HEAD^ --soft"
3780                                    } else {
3781                                        "git reset HEAD^"
3782                                    },
3783                                    cx,
3784                                )
3785                            })
3786                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3787                    )
3788                }),
3789        )
3790    }
3791
3792    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3793        h_flex().h_full().flex_grow().justify_center().child(
3794            v_flex()
3795                .gap_2()
3796                .child(h_flex().w_full().justify_around().child(
3797                    if self.active_repository.is_some() {
3798                        "No changes to commit"
3799                    } else {
3800                        "No Git repositories"
3801                    },
3802                ))
3803                .children({
3804                    let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3805                    (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3806                        h_flex().w_full().justify_around().child(
3807                            panel_filled_button("Initialize Repository")
3808                                .tooltip(Tooltip::for_action_title_in(
3809                                    "git init",
3810                                    &git::Init,
3811                                    &self.focus_handle,
3812                                ))
3813                                .on_click(move |_, _, cx| {
3814                                    cx.defer(move |cx| {
3815                                        cx.dispatch_action(&git::Init);
3816                                    })
3817                                }),
3818                        )
3819                    })
3820                })
3821                .text_ui_sm(cx)
3822                .mx_auto()
3823                .text_color(Color::Placeholder.color(cx)),
3824        )
3825    }
3826
3827    fn render_buffer_header_controls(
3828        &self,
3829        entity: &Entity<Self>,
3830        file: &Arc<dyn File>,
3831        _: &Window,
3832        cx: &App,
3833    ) -> Option<AnyElement> {
3834        let repo = self.active_repository.as_ref()?.read(cx);
3835        let project_path = (file.worktree_id(cx), file.path().clone()).into();
3836        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3837        let ix = self.entry_by_path(&repo_path, cx)?;
3838        let entry = self.entries.get(ix)?;
3839
3840        let is_staging_or_staged = repo
3841            .pending_ops_for_path(&repo_path)
3842            .map(|ops| ops.staging() || ops.staged())
3843            .or_else(|| {
3844                repo.status_for_path(&repo_path)
3845                    .and_then(|status| status.status.staging().as_bool())
3846            })
3847            .or_else(|| {
3848                entry
3849                    .status_entry()
3850                    .and_then(|entry| entry.staging.as_bool())
3851            });
3852
3853        let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
3854            .disabled(!self.has_write_access(cx))
3855            .fill()
3856            .elevation(ElevationIndex::Surface)
3857            .on_click({
3858                let entry = entry.clone();
3859                let git_panel = entity.downgrade();
3860                move |_, window, cx| {
3861                    git_panel
3862                        .update(cx, |this, cx| {
3863                            this.toggle_staged_for_entry(&entry, window, cx);
3864                            cx.stop_propagation();
3865                        })
3866                        .ok();
3867                }
3868            });
3869        Some(
3870            h_flex()
3871                .id("start-slot")
3872                .text_lg()
3873                .child(checkbox)
3874                .on_mouse_down(MouseButton::Left, |_, _, cx| {
3875                    // prevent the list item active state triggering when toggling checkbox
3876                    cx.stop_propagation();
3877                })
3878                .into_any_element(),
3879        )
3880    }
3881
3882    fn render_entries(
3883        &self,
3884        has_write_access: bool,
3885        window: &mut Window,
3886        cx: &mut Context<Self>,
3887    ) -> impl IntoElement {
3888        let entry_count = self.entries.len();
3889
3890        v_flex()
3891            .flex_1()
3892            .size_full()
3893            .overflow_hidden()
3894            .relative()
3895            .child(
3896                h_flex()
3897                    .flex_1()
3898                    .size_full()
3899                    .relative()
3900                    .overflow_hidden()
3901                    .child(
3902                        uniform_list(
3903                            "entries",
3904                            entry_count,
3905                            cx.processor(move |this, range: Range<usize>, window, cx| {
3906                                let mut items = Vec::with_capacity(range.end - range.start);
3907
3908                                for ix in range {
3909                                    match &this.entries.get(ix) {
3910                                        Some(GitListEntry::Status(entry)) => {
3911                                            items.push(this.render_entry(
3912                                                ix,
3913                                                entry,
3914                                                has_write_access,
3915                                                window,
3916                                                cx,
3917                                            ));
3918                                        }
3919                                        Some(GitListEntry::Header(header)) => {
3920                                            items.push(this.render_list_header(
3921                                                ix,
3922                                                header,
3923                                                has_write_access,
3924                                                window,
3925                                                cx,
3926                                            ));
3927                                        }
3928                                        None => {}
3929                                    }
3930                                }
3931
3932                                items
3933                            }),
3934                        )
3935                        .size_full()
3936                        .flex_grow()
3937                        .with_sizing_behavior(ListSizingBehavior::Auto)
3938                        .with_horizontal_sizing_behavior(
3939                            ListHorizontalSizingBehavior::Unconstrained,
3940                        )
3941                        .with_width_from_item(self.max_width_item_index)
3942                        .track_scroll(self.scroll_handle.clone()),
3943                    )
3944                    .on_mouse_down(
3945                        MouseButton::Right,
3946                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3947                            this.deploy_panel_context_menu(event.position, window, cx)
3948                        }),
3949                    )
3950                    .custom_scrollbars(
3951                        Scrollbars::for_settings::<GitPanelSettings>()
3952                            .tracked_scroll_handle(self.scroll_handle.clone())
3953                            .with_track_along(
3954                                ScrollAxes::Horizontal,
3955                                cx.theme().colors().panel_background,
3956                            ),
3957                        window,
3958                        cx,
3959                    ),
3960            )
3961    }
3962
3963    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3964        Label::new(label.into()).color(color).single_line()
3965    }
3966
3967    fn list_item_height(&self) -> Rems {
3968        rems(1.75)
3969    }
3970
3971    fn render_list_header(
3972        &self,
3973        ix: usize,
3974        header: &GitHeaderEntry,
3975        _: bool,
3976        _: &Window,
3977        _: &Context<Self>,
3978    ) -> AnyElement {
3979        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3980
3981        h_flex()
3982            .id(id)
3983            .h(self.list_item_height())
3984            .w_full()
3985            .items_end()
3986            .px(rems(0.75)) // ~12px
3987            .pb(rems(0.3125)) // ~ 5px
3988            .child(
3989                Label::new(header.title())
3990                    .color(Color::Muted)
3991                    .size(LabelSize::Small)
3992                    .line_height_style(LineHeightStyle::UiLabel)
3993                    .single_line(),
3994            )
3995            .into_any_element()
3996    }
3997
3998    pub fn load_commit_details(
3999        &self,
4000        sha: String,
4001        cx: &mut Context<Self>,
4002    ) -> Task<anyhow::Result<CommitDetails>> {
4003        let Some(repo) = self.active_repository.clone() else {
4004            return Task::ready(Err(anyhow::anyhow!("no active repo")));
4005        };
4006        repo.update(cx, |repo, cx| {
4007            let show = repo.show(sha);
4008            cx.spawn(async move |_, _| show.await?)
4009        })
4010    }
4011
4012    fn deploy_entry_context_menu(
4013        &mut self,
4014        position: Point<Pixels>,
4015        ix: usize,
4016        window: &mut Window,
4017        cx: &mut Context<Self>,
4018    ) {
4019        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4020            return;
4021        };
4022        let stage_title = if entry.status.staging().is_fully_staged() {
4023            "Unstage File"
4024        } else {
4025            "Stage File"
4026        };
4027        let restore_title = if entry.status.is_created() {
4028            "Trash File"
4029        } else {
4030            "Restore File"
4031        };
4032        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4033            let mut context_menu = context_menu
4034                .context(self.focus_handle.clone())
4035                .action(stage_title, ToggleStaged.boxed_clone())
4036                .action(restore_title, git::RestoreFile::default().boxed_clone());
4037
4038            if entry.status.is_created() {
4039                context_menu =
4040                    context_menu.action("Add to .gitignore", git::AddToGitignore.boxed_clone());
4041            }
4042
4043            context_menu
4044                .separator()
4045                .action("Open Diff", Confirm.boxed_clone())
4046                .action("Open File", SecondaryConfirm.boxed_clone())
4047        });
4048        self.selected_entry = Some(ix);
4049        self.set_context_menu(context_menu, position, window, cx);
4050    }
4051
4052    fn deploy_panel_context_menu(
4053        &mut self,
4054        position: Point<Pixels>,
4055        window: &mut Window,
4056        cx: &mut Context<Self>,
4057    ) {
4058        let context_menu = git_panel_context_menu(
4059            self.focus_handle.clone(),
4060            GitMenuState {
4061                has_tracked_changes: self.has_tracked_changes(),
4062                has_staged_changes: self.has_staged_changes(),
4063                has_unstaged_changes: self.has_unstaged_changes(),
4064                has_new_changes: self.new_count > 0,
4065                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4066                has_stash_items: self.stash_entries.entries.len() > 0,
4067            },
4068            window,
4069            cx,
4070        );
4071        self.set_context_menu(context_menu, position, window, cx);
4072    }
4073
4074    fn set_context_menu(
4075        &mut self,
4076        context_menu: Entity<ContextMenu>,
4077        position: Point<Pixels>,
4078        window: &Window,
4079        cx: &mut Context<Self>,
4080    ) {
4081        let subscription = cx.subscribe_in(
4082            &context_menu,
4083            window,
4084            |this, _, _: &DismissEvent, window, cx| {
4085                if this.context_menu.as_ref().is_some_and(|context_menu| {
4086                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
4087                }) {
4088                    cx.focus_self(window);
4089                }
4090                this.context_menu.take();
4091                cx.notify();
4092            },
4093        );
4094        self.context_menu = Some((context_menu, position, subscription));
4095        cx.notify();
4096    }
4097
4098    fn render_entry(
4099        &self,
4100        ix: usize,
4101        entry: &GitStatusEntry,
4102        has_write_access: bool,
4103        window: &Window,
4104        cx: &Context<Self>,
4105    ) -> AnyElement {
4106        let path_style = self.project.read(cx).path_style(cx);
4107        let git_path_style = ProjectSettings::get_global(cx).git.path_style;
4108        let display_name = entry.display_name(path_style);
4109
4110        let selected = self.selected_entry == Some(ix);
4111        let marked = self.marked_entries.contains(&ix);
4112        let status_style = GitPanelSettings::get_global(cx).status_style;
4113        let status = entry.status;
4114
4115        let has_conflict = status.is_conflicted();
4116        let is_modified = status.is_modified();
4117        let is_deleted = status.is_deleted();
4118
4119        let label_color = if status_style == StatusStyle::LabelColor {
4120            if has_conflict {
4121                Color::VersionControlConflict
4122            } else if is_modified {
4123                Color::VersionControlModified
4124            } else if is_deleted {
4125                // We don't want a bunch of red labels in the list
4126                Color::Disabled
4127            } else {
4128                Color::VersionControlAdded
4129            }
4130        } else {
4131            Color::Default
4132        };
4133
4134        let path_color = if status.is_deleted() {
4135            Color::Disabled
4136        } else {
4137            Color::Muted
4138        };
4139
4140        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4141        let checkbox_wrapper_id: ElementId =
4142            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4143        let checkbox_id: ElementId =
4144            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4145
4146        let active_repo = self
4147            .project
4148            .read(cx)
4149            .active_repository(cx)
4150            .expect("active repository must be set");
4151        let repo = active_repo.read(cx);
4152        // Checking for current staged/unstaged file status is a chained operation:
4153        // 1. first, we check for any pending operation recorded in repository
4154        // 2. if there are no pending ops either running or finished, we then ask the repository
4155        //    for the most up-to-date file status read from disk - we do this since `entry` arg to this function `render_entry`
4156        //    is likely to be staled, and may lead to weird artifacts in the form of subsecond auto-uncheck/check on
4157        //    the checkbox's state (or flickering) which is undesirable.
4158        // 3. finally, if there is no info about this `entry` in the repo, we fall back to whatever status is encoded
4159        //    in `entry` arg.
4160        let is_staging_or_staged = repo
4161            .pending_ops_for_path(&entry.repo_path)
4162            .map(|ops| ops.staging() || ops.staged())
4163            .or_else(|| {
4164                repo.status_for_path(&entry.repo_path)
4165                    .and_then(|status| status.status.staging().as_bool())
4166            })
4167            .or_else(|| entry.staging.as_bool());
4168        let mut is_staged: ToggleState = is_staging_or_staged.into();
4169        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4170            is_staged = ToggleState::Selected;
4171        }
4172
4173        let handle = cx.weak_entity();
4174
4175        let selected_bg_alpha = 0.08;
4176        let marked_bg_alpha = 0.12;
4177        let state_opacity_step = 0.04;
4178
4179        let base_bg = match (selected, marked) {
4180            (true, true) => cx
4181                .theme()
4182                .status()
4183                .info
4184                .alpha(selected_bg_alpha + marked_bg_alpha),
4185            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4186            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4187            _ => cx.theme().colors().ghost_element_background,
4188        };
4189
4190        let hover_bg = if selected {
4191            cx.theme()
4192                .status()
4193                .info
4194                .alpha(selected_bg_alpha + state_opacity_step)
4195        } else {
4196            cx.theme().colors().ghost_element_hover
4197        };
4198
4199        let active_bg = if selected {
4200            cx.theme()
4201                .status()
4202                .info
4203                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4204        } else {
4205            cx.theme().colors().ghost_element_active
4206        };
4207        h_flex()
4208            .id(id)
4209            .h(self.list_item_height())
4210            .w_full()
4211            .items_center()
4212            .border_1()
4213            .when(selected && self.focus_handle.is_focused(window), |el| {
4214                el.border_color(cx.theme().colors().border_focused)
4215            })
4216            .px(rems(0.75)) // ~12px
4217            .overflow_hidden()
4218            .flex_none()
4219            .gap_1p5()
4220            .bg(base_bg)
4221            .hover(|this| this.bg(hover_bg))
4222            .active(|this| this.bg(active_bg))
4223            .on_click({
4224                cx.listener(move |this, event: &ClickEvent, window, cx| {
4225                    this.selected_entry = Some(ix);
4226                    cx.notify();
4227                    if event.modifiers().secondary() {
4228                        this.open_file(&Default::default(), window, cx)
4229                    } else {
4230                        this.open_diff(&Default::default(), window, cx);
4231                        this.focus_handle.focus(window);
4232                    }
4233                })
4234            })
4235            .on_mouse_down(
4236                MouseButton::Right,
4237                move |event: &MouseDownEvent, window, cx| {
4238                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4239                    if event.button != MouseButton::Right {
4240                        return;
4241                    }
4242
4243                    let Some(this) = handle.upgrade() else {
4244                        return;
4245                    };
4246                    this.update(cx, |this, cx| {
4247                        this.deploy_entry_context_menu(event.position, ix, window, cx);
4248                    });
4249                    cx.stop_propagation();
4250                },
4251            )
4252            .child(
4253                div()
4254                    .id(checkbox_wrapper_id)
4255                    .flex_none()
4256                    .occlude()
4257                    .cursor_pointer()
4258                    .child(
4259                        Checkbox::new(checkbox_id, is_staged)
4260                            .disabled(!has_write_access)
4261                            .fill()
4262                            .elevation(ElevationIndex::Surface)
4263                            .on_click_ext({
4264                                let entry = entry.clone();
4265                                let this = cx.weak_entity();
4266                                move |_, click, window, cx| {
4267                                    this.update(cx, |this, cx| {
4268                                        if !has_write_access {
4269                                            return;
4270                                        }
4271                                        if click.modifiers().shift {
4272                                            this.stage_bulk(ix, cx);
4273                                        } else {
4274                                            this.toggle_staged_for_entry(
4275                                                &GitListEntry::Status(entry.clone()),
4276                                                window,
4277                                                cx,
4278                                            );
4279                                        }
4280                                        cx.stop_propagation();
4281                                    })
4282                                    .ok();
4283                                }
4284                            })
4285                            .tooltip(move |_window, cx| {
4286                                // If is_staging_or_staged is None, this implies the file was partially staged, and so
4287                                // we allow the user to stage it in full by displaying `Stage` in the tooltip.
4288                                let action = if is_staging_or_staged.unwrap_or(false) {
4289                                    "Unstage"
4290                                } else {
4291                                    "Stage"
4292                                };
4293                                let tooltip_name = action.to_string();
4294
4295                                Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
4296                            }),
4297                    ),
4298            )
4299            .child(git_status_icon(status))
4300            .child(
4301                h_flex()
4302                    .items_center()
4303                    .flex_1()
4304                    .child(h_flex().items_center().flex_1().map(|this| {
4305                        self.path_formatted(
4306                            this,
4307                            entry.parent_dir(path_style),
4308                            path_color,
4309                            display_name,
4310                            label_color,
4311                            path_style,
4312                            git_path_style,
4313                            status.is_deleted(),
4314                        )
4315                    })),
4316            )
4317            .into_any_element()
4318    }
4319
4320    fn path_formatted(
4321        &self,
4322        parent: Div,
4323        directory: Option<String>,
4324        path_color: Color,
4325        file_name: String,
4326        label_color: Color,
4327        path_style: PathStyle,
4328        git_path_style: GitPathStyle,
4329        strikethrough: bool,
4330    ) -> Div {
4331        parent
4332            .when(git_path_style == GitPathStyle::FileNameFirst, |this| {
4333                this.child(
4334                    self.entry_label(
4335                        match directory.as_ref().is_none_or(|d| d.is_empty()) {
4336                            true => file_name.clone(),
4337                            false => format!("{file_name} "),
4338                        },
4339                        label_color,
4340                    )
4341                    .when(strikethrough, Label::strikethrough),
4342                )
4343            })
4344            .when_some(directory, |this, dir| {
4345                match (
4346                    !dir.is_empty(),
4347                    git_path_style == GitPathStyle::FileNameFirst,
4348                ) {
4349                    (true, true) => this.child(
4350                        self.entry_label(dir, path_color)
4351                            .when(strikethrough, Label::strikethrough),
4352                    ),
4353                    (true, false) => this.child(
4354                        self.entry_label(format!("{dir}{}", path_style.separator()), path_color)
4355                            .when(strikethrough, Label::strikethrough),
4356                    ),
4357                    _ => this,
4358                }
4359            })
4360            .when(git_path_style == GitPathStyle::FilePathFirst, |this| {
4361                this.child(
4362                    self.entry_label(file_name, label_color)
4363                        .when(strikethrough, Label::strikethrough),
4364                )
4365            })
4366    }
4367
4368    fn has_write_access(&self, cx: &App) -> bool {
4369        !self.project.read(cx).is_read_only(cx)
4370    }
4371
4372    pub fn amend_pending(&self) -> bool {
4373        self.amend_pending
4374    }
4375
4376    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4377        if value && !self.amend_pending {
4378            let current_message = self.commit_message_buffer(cx).read(cx).text();
4379            self.original_commit_message = if current_message.trim().is_empty() {
4380                None
4381            } else {
4382                Some(current_message)
4383            };
4384        } else if !value && self.amend_pending {
4385            let message = self.original_commit_message.take().unwrap_or_default();
4386            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4387                let start = buffer.anchor_before(0);
4388                let end = buffer.anchor_after(buffer.len());
4389                buffer.edit([(start..end, message)], None, cx);
4390            });
4391        }
4392
4393        self.amend_pending = value;
4394        self.serialize(cx);
4395        cx.notify();
4396    }
4397
4398    pub fn signoff_enabled(&self) -> bool {
4399        self.signoff_enabled
4400    }
4401
4402    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4403        self.signoff_enabled = value;
4404        self.serialize(cx);
4405        cx.notify();
4406    }
4407
4408    pub fn toggle_signoff_enabled(
4409        &mut self,
4410        _: &Signoff,
4411        _window: &mut Window,
4412        cx: &mut Context<Self>,
4413    ) {
4414        self.set_signoff_enabled(!self.signoff_enabled, cx);
4415    }
4416
4417    pub async fn load(
4418        workspace: WeakEntity<Workspace>,
4419        mut cx: AsyncWindowContext,
4420    ) -> anyhow::Result<Entity<Self>> {
4421        let serialized_panel = match workspace
4422            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4423            .ok()
4424            .flatten()
4425        {
4426            Some(serialization_key) => cx
4427                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4428                .await
4429                .context("loading git panel")
4430                .log_err()
4431                .flatten()
4432                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4433                .transpose()
4434                .log_err()
4435                .flatten(),
4436            None => None,
4437        };
4438
4439        workspace.update_in(&mut cx, |workspace, window, cx| {
4440            let panel = GitPanel::new(workspace, window, cx);
4441
4442            if let Some(serialized_panel) = serialized_panel {
4443                panel.update(cx, |panel, cx| {
4444                    panel.width = serialized_panel.width;
4445                    panel.amend_pending = serialized_panel.amend_pending;
4446                    panel.signoff_enabled = serialized_panel.signoff_enabled;
4447                    cx.notify();
4448                })
4449            }
4450
4451            panel
4452        })
4453    }
4454
4455    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4456        let Some(op) = self.bulk_staging.as_ref() else {
4457            return;
4458        };
4459        let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4460            return;
4461        };
4462        if let Some(entry) = self.entries.get(index)
4463            && let Some(entry) = entry.status_entry()
4464        {
4465            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4466        }
4467        if index < anchor_index {
4468            std::mem::swap(&mut index, &mut anchor_index);
4469        }
4470        let entries = self
4471            .entries
4472            .get(anchor_index..=index)
4473            .unwrap_or_default()
4474            .iter()
4475            .filter_map(|entry| entry.status_entry().cloned())
4476            .collect::<Vec<_>>();
4477        self.change_file_stage(true, entries, cx);
4478    }
4479
4480    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4481        let Some(repo) = self.active_repository.as_ref() else {
4482            return;
4483        };
4484        self.bulk_staging = Some(BulkStaging {
4485            repo_id: repo.read(cx).id,
4486            anchor: path,
4487        });
4488    }
4489
4490    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4491        self.set_amend_pending(!self.amend_pending, cx);
4492        if self.amend_pending {
4493            self.load_last_commit_message_if_empty(cx);
4494        }
4495    }
4496}
4497
4498impl Render for GitPanel {
4499    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4500        let project = self.project.read(cx);
4501        let has_entries = !self.entries.is_empty();
4502        let room = self
4503            .workspace
4504            .upgrade()
4505            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4506
4507        let has_write_access = self.has_write_access(cx);
4508
4509        let has_co_authors = room.is_some_and(|room| {
4510            self.load_local_committer(cx);
4511            let room = room.read(cx);
4512            room.remote_participants()
4513                .values()
4514                .any(|remote_participant| remote_participant.can_write())
4515        });
4516
4517        v_flex()
4518            .id("git_panel")
4519            .key_context(self.dispatch_context(window, cx))
4520            .track_focus(&self.focus_handle)
4521            .when(has_write_access && !project.is_read_only(cx), |this| {
4522                this.on_action(cx.listener(Self::toggle_staged_for_selected))
4523                    .on_action(cx.listener(Self::stage_range))
4524                    .on_action(cx.listener(GitPanel::commit))
4525                    .on_action(cx.listener(GitPanel::amend))
4526                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4527                    .on_action(cx.listener(Self::stage_all))
4528                    .on_action(cx.listener(Self::unstage_all))
4529                    .on_action(cx.listener(Self::stage_selected))
4530                    .on_action(cx.listener(Self::unstage_selected))
4531                    .on_action(cx.listener(Self::restore_tracked_files))
4532                    .on_action(cx.listener(Self::revert_selected))
4533                    .on_action(cx.listener(Self::add_to_gitignore))
4534                    .on_action(cx.listener(Self::clean_all))
4535                    .on_action(cx.listener(Self::generate_commit_message_action))
4536                    .on_action(cx.listener(Self::stash_all))
4537                    .on_action(cx.listener(Self::stash_pop))
4538            })
4539            .on_action(cx.listener(Self::select_first))
4540            .on_action(cx.listener(Self::select_next))
4541            .on_action(cx.listener(Self::select_previous))
4542            .on_action(cx.listener(Self::select_last))
4543            .on_action(cx.listener(Self::close_panel))
4544            .on_action(cx.listener(Self::open_diff))
4545            .on_action(cx.listener(Self::open_file))
4546            .on_action(cx.listener(Self::focus_changes_list))
4547            .on_action(cx.listener(Self::focus_editor))
4548            .on_action(cx.listener(Self::expand_commit_editor))
4549            .when(has_write_access && has_co_authors, |git_panel| {
4550                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4551            })
4552            .on_action(cx.listener(Self::toggle_sort_by_path))
4553            .size_full()
4554            .overflow_hidden()
4555            .bg(cx.theme().colors().panel_background)
4556            .child(
4557                v_flex()
4558                    .size_full()
4559                    .children(self.render_panel_header(window, cx))
4560                    .map(|this| {
4561                        if has_entries {
4562                            this.child(self.render_entries(has_write_access, window, cx))
4563                        } else {
4564                            this.child(self.render_empty_state(cx).into_any_element())
4565                        }
4566                    })
4567                    .children(self.render_footer(window, cx))
4568                    .when(self.amend_pending, |this| {
4569                        this.child(self.render_pending_amend(cx))
4570                    })
4571                    .when(!self.amend_pending, |this| {
4572                        this.children(self.render_previous_commit(cx))
4573                    })
4574                    .into_any_element(),
4575            )
4576            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4577                deferred(
4578                    anchored()
4579                        .position(*position)
4580                        .anchor(Corner::TopLeft)
4581                        .child(menu.clone()),
4582                )
4583                .with_priority(1)
4584            }))
4585    }
4586}
4587
4588impl Focusable for GitPanel {
4589    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4590        if self.entries.is_empty() {
4591            self.commit_editor.focus_handle(cx)
4592        } else {
4593            self.focus_handle.clone()
4594        }
4595    }
4596}
4597
4598impl EventEmitter<Event> for GitPanel {}
4599
4600impl EventEmitter<PanelEvent> for GitPanel {}
4601
4602pub(crate) struct GitPanelAddon {
4603    pub(crate) workspace: WeakEntity<Workspace>,
4604}
4605
4606impl editor::Addon for GitPanelAddon {
4607    fn to_any(&self) -> &dyn std::any::Any {
4608        self
4609    }
4610
4611    fn render_buffer_header_controls(
4612        &self,
4613        excerpt_info: &ExcerptInfo,
4614        window: &Window,
4615        cx: &App,
4616    ) -> Option<AnyElement> {
4617        let file = excerpt_info.buffer.file()?;
4618        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4619
4620        git_panel
4621            .read(cx)
4622            .render_buffer_header_controls(&git_panel, file, window, cx)
4623    }
4624}
4625
4626impl Panel for GitPanel {
4627    fn persistent_name() -> &'static str {
4628        "GitPanel"
4629    }
4630
4631    fn panel_key() -> &'static str {
4632        GIT_PANEL_KEY
4633    }
4634
4635    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4636        GitPanelSettings::get_global(cx).dock
4637    }
4638
4639    fn position_is_valid(&self, position: DockPosition) -> bool {
4640        matches!(position, DockPosition::Left | DockPosition::Right)
4641    }
4642
4643    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4644        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
4645            settings.git_panel.get_or_insert_default().dock = Some(position.into())
4646        });
4647    }
4648
4649    fn size(&self, _: &Window, cx: &App) -> Pixels {
4650        self.width
4651            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4652    }
4653
4654    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4655        self.width = size;
4656        self.serialize(cx);
4657        cx.notify();
4658    }
4659
4660    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4661        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4662    }
4663
4664    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4665        Some("Git Panel")
4666    }
4667
4668    fn toggle_action(&self) -> Box<dyn Action> {
4669        Box::new(ToggleFocus)
4670    }
4671
4672    fn activation_priority(&self) -> u32 {
4673        2
4674    }
4675}
4676
4677impl PanelHeader for GitPanel {}
4678
4679struct GitPanelMessageTooltip {
4680    commit_tooltip: Option<Entity<CommitTooltip>>,
4681}
4682
4683impl GitPanelMessageTooltip {
4684    fn new(
4685        git_panel: Entity<GitPanel>,
4686        sha: SharedString,
4687        repository: Entity<Repository>,
4688        window: &mut Window,
4689        cx: &mut App,
4690    ) -> Entity<Self> {
4691        cx.new(|cx| {
4692            cx.spawn_in(window, async move |this, cx| {
4693                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4694                    (
4695                        git_panel.load_commit_details(sha.to_string(), cx),
4696                        git_panel.workspace.clone(),
4697                    )
4698                })?;
4699                let details = details.await?;
4700
4701                let commit_details = crate::commit_tooltip::CommitDetails {
4702                    sha: details.sha.clone(),
4703                    author_name: details.author_name.clone(),
4704                    author_email: details.author_email.clone(),
4705                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4706                    message: Some(ParsedCommitMessage {
4707                        message: details.message,
4708                        ..Default::default()
4709                    }),
4710                };
4711
4712                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4713                    this.commit_tooltip = Some(cx.new(move |cx| {
4714                        CommitTooltip::new(commit_details, repository, workspace, cx)
4715                    }));
4716                    cx.notify();
4717                })
4718            })
4719            .detach();
4720
4721            Self {
4722                commit_tooltip: None,
4723            }
4724        })
4725    }
4726}
4727
4728impl Render for GitPanelMessageTooltip {
4729    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4730        if let Some(commit_tooltip) = &self.commit_tooltip {
4731            commit_tooltip.clone().into_any_element()
4732        } else {
4733            gpui::Empty.into_any_element()
4734        }
4735    }
4736}
4737
4738#[derive(IntoElement, RegisterComponent)]
4739pub struct PanelRepoFooter {
4740    active_repository: SharedString,
4741    branch: Option<Branch>,
4742    head_commit: Option<CommitDetails>,
4743
4744    // Getting a GitPanel in previews will be difficult.
4745    //
4746    // For now just take an option here, and we won't bind handlers to buttons in previews.
4747    git_panel: Option<Entity<GitPanel>>,
4748}
4749
4750impl PanelRepoFooter {
4751    pub fn new(
4752        active_repository: SharedString,
4753        branch: Option<Branch>,
4754        head_commit: Option<CommitDetails>,
4755        git_panel: Option<Entity<GitPanel>>,
4756    ) -> Self {
4757        Self {
4758            active_repository,
4759            branch,
4760            head_commit,
4761            git_panel,
4762        }
4763    }
4764
4765    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4766        Self {
4767            active_repository,
4768            branch,
4769            head_commit: None,
4770            git_panel: None,
4771        }
4772    }
4773}
4774
4775impl RenderOnce for PanelRepoFooter {
4776    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4777        let project = self
4778            .git_panel
4779            .as_ref()
4780            .map(|panel| panel.read(cx).project.clone());
4781
4782        let repo = self
4783            .git_panel
4784            .as_ref()
4785            .and_then(|panel| panel.read(cx).active_repository.clone());
4786
4787        let single_repo = project
4788            .as_ref()
4789            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4790            .unwrap_or(true);
4791
4792        const MAX_BRANCH_LEN: usize = 16;
4793        const MAX_REPO_LEN: usize = 16;
4794        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4795        const MAX_SHORT_SHA_LEN: usize = 8;
4796
4797        let branch_name = self
4798            .branch
4799            .as_ref()
4800            .map(|branch| branch.name().to_owned())
4801            .or_else(|| {
4802                self.head_commit.as_ref().map(|commit| {
4803                    commit
4804                        .sha
4805                        .chars()
4806                        .take(MAX_SHORT_SHA_LEN)
4807                        .collect::<String>()
4808                })
4809            })
4810            .unwrap_or_else(|| " (no branch)".to_owned());
4811        let show_separator = self.branch.is_some() || self.head_commit.is_some();
4812
4813        let active_repo_name = self.active_repository.clone();
4814
4815        let branch_actual_len = branch_name.len();
4816        let repo_actual_len = active_repo_name.len();
4817
4818        // ideally, show the whole branch and repo names but
4819        // when we can't, use a budget to allocate space between the two
4820        let (repo_display_len, branch_display_len) =
4821            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4822                (repo_actual_len, branch_actual_len)
4823            } else if branch_actual_len <= MAX_BRANCH_LEN {
4824                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4825                (repo_space, branch_actual_len)
4826            } else if repo_actual_len <= MAX_REPO_LEN {
4827                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4828                (repo_actual_len, branch_space)
4829            } else {
4830                (MAX_REPO_LEN, MAX_BRANCH_LEN)
4831            };
4832
4833        let truncated_repo_name = if repo_actual_len <= repo_display_len {
4834            active_repo_name.to_string()
4835        } else {
4836            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4837        };
4838
4839        let truncated_branch_name = if branch_actual_len <= branch_display_len {
4840            branch_name
4841        } else {
4842            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4843        };
4844
4845        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4846            .size(ButtonSize::None)
4847            .label_size(LabelSize::Small)
4848            .color(Color::Muted);
4849
4850        let repo_selector = PopoverMenu::new("repository-switcher")
4851            .menu({
4852                let project = project;
4853                move |window, cx| {
4854                    let project = project.clone()?;
4855                    Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4856                }
4857            })
4858            .trigger_with_tooltip(
4859                repo_selector_trigger.disabled(single_repo).truncate(true),
4860                Tooltip::text("Switch Active Repository"),
4861            )
4862            .anchor(Corner::BottomLeft)
4863            .into_any_element();
4864
4865        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4866            .size(ButtonSize::None)
4867            .label_size(LabelSize::Small)
4868            .truncate(true)
4869            .on_click(|_, window, cx| {
4870                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4871            });
4872
4873        let branch_selector = PopoverMenu::new("popover-button")
4874            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4875            .trigger_with_tooltip(
4876                branch_selector_button,
4877                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4878            )
4879            .anchor(Corner::BottomLeft)
4880            .offset(gpui::Point {
4881                x: px(0.0),
4882                y: px(-2.0),
4883            });
4884
4885        h_flex()
4886            .h(px(36.))
4887            .w_full()
4888            .px_2()
4889            .justify_between()
4890            .gap_1()
4891            .child(
4892                h_flex()
4893                    .flex_1()
4894                    .overflow_hidden()
4895                    .gap_px()
4896                    .child(
4897                        Icon::new(IconName::GitBranchAlt)
4898                            .size(IconSize::Small)
4899                            .color(if single_repo {
4900                                Color::Disabled
4901                            } else {
4902                                Color::Muted
4903                            }),
4904                    )
4905                    .child(repo_selector)
4906                    .when(show_separator, |this| {
4907                        this.child(
4908                            div()
4909                                .text_sm()
4910                                .text_color(cx.theme().colors().icon_muted.opacity(0.5))
4911                                .child("/"),
4912                        )
4913                    })
4914                    .child(branch_selector),
4915            )
4916            .children(if let Some(git_panel) = self.git_panel {
4917                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4918            } else {
4919                None
4920            })
4921    }
4922}
4923
4924impl Component for PanelRepoFooter {
4925    fn scope() -> ComponentScope {
4926        ComponentScope::VersionControl
4927    }
4928
4929    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4930        let unknown_upstream = None;
4931        let no_remote_upstream = Some(UpstreamTracking::Gone);
4932        let ahead_of_upstream = Some(
4933            UpstreamTrackingStatus {
4934                ahead: 2,
4935                behind: 0,
4936            }
4937            .into(),
4938        );
4939        let behind_upstream = Some(
4940            UpstreamTrackingStatus {
4941                ahead: 0,
4942                behind: 2,
4943            }
4944            .into(),
4945        );
4946        let ahead_and_behind_upstream = Some(
4947            UpstreamTrackingStatus {
4948                ahead: 3,
4949                behind: 1,
4950            }
4951            .into(),
4952        );
4953
4954        let not_ahead_or_behind_upstream = Some(
4955            UpstreamTrackingStatus {
4956                ahead: 0,
4957                behind: 0,
4958            }
4959            .into(),
4960        );
4961
4962        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4963            Branch {
4964                is_head: true,
4965                ref_name: "some-branch".into(),
4966                upstream: upstream.map(|tracking| Upstream {
4967                    ref_name: "origin/some-branch".into(),
4968                    tracking,
4969                }),
4970                most_recent_commit: Some(CommitSummary {
4971                    sha: "abc123".into(),
4972                    subject: "Modify stuff".into(),
4973                    commit_timestamp: 1710932954,
4974                    author_name: "John Doe".into(),
4975                    has_parent: true,
4976                }),
4977            }
4978        }
4979
4980        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4981            Branch {
4982                is_head: true,
4983                ref_name: branch_name.to_string().into(),
4984                upstream: upstream.map(|tracking| Upstream {
4985                    ref_name: format!("zed/{}", branch_name).into(),
4986                    tracking,
4987                }),
4988                most_recent_commit: Some(CommitSummary {
4989                    sha: "abc123".into(),
4990                    subject: "Modify stuff".into(),
4991                    commit_timestamp: 1710932954,
4992                    author_name: "John Doe".into(),
4993                    has_parent: true,
4994                }),
4995            }
4996        }
4997
4998        fn active_repository(id: usize) -> SharedString {
4999            format!("repo-{}", id).into()
5000        }
5001
5002        let example_width = px(340.);
5003        Some(
5004            v_flex()
5005                .gap_6()
5006                .w_full()
5007                .flex_none()
5008                .children(vec![
5009                    example_group_with_title(
5010                        "Action Button States",
5011                        vec![
5012                            single_example(
5013                                "No Branch",
5014                                div()
5015                                    .w(example_width)
5016                                    .overflow_hidden()
5017                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
5018                                    .into_any_element(),
5019                            ),
5020                            single_example(
5021                                "Remote status unknown",
5022                                div()
5023                                    .w(example_width)
5024                                    .overflow_hidden()
5025                                    .child(PanelRepoFooter::new_preview(
5026                                        active_repository(2),
5027                                        Some(branch(unknown_upstream)),
5028                                    ))
5029                                    .into_any_element(),
5030                            ),
5031                            single_example(
5032                                "No Remote Upstream",
5033                                div()
5034                                    .w(example_width)
5035                                    .overflow_hidden()
5036                                    .child(PanelRepoFooter::new_preview(
5037                                        active_repository(3),
5038                                        Some(branch(no_remote_upstream)),
5039                                    ))
5040                                    .into_any_element(),
5041                            ),
5042                            single_example(
5043                                "Not Ahead or Behind",
5044                                div()
5045                                    .w(example_width)
5046                                    .overflow_hidden()
5047                                    .child(PanelRepoFooter::new_preview(
5048                                        active_repository(4),
5049                                        Some(branch(not_ahead_or_behind_upstream)),
5050                                    ))
5051                                    .into_any_element(),
5052                            ),
5053                            single_example(
5054                                "Behind remote",
5055                                div()
5056                                    .w(example_width)
5057                                    .overflow_hidden()
5058                                    .child(PanelRepoFooter::new_preview(
5059                                        active_repository(5),
5060                                        Some(branch(behind_upstream)),
5061                                    ))
5062                                    .into_any_element(),
5063                            ),
5064                            single_example(
5065                                "Ahead of remote",
5066                                div()
5067                                    .w(example_width)
5068                                    .overflow_hidden()
5069                                    .child(PanelRepoFooter::new_preview(
5070                                        active_repository(6),
5071                                        Some(branch(ahead_of_upstream)),
5072                                    ))
5073                                    .into_any_element(),
5074                            ),
5075                            single_example(
5076                                "Ahead and behind remote",
5077                                div()
5078                                    .w(example_width)
5079                                    .overflow_hidden()
5080                                    .child(PanelRepoFooter::new_preview(
5081                                        active_repository(7),
5082                                        Some(branch(ahead_and_behind_upstream)),
5083                                    ))
5084                                    .into_any_element(),
5085                            ),
5086                        ],
5087                    )
5088                    .grow()
5089                    .vertical(),
5090                ])
5091                .children(vec![
5092                    example_group_with_title(
5093                        "Labels",
5094                        vec![
5095                            single_example(
5096                                "Short Branch & Repo",
5097                                div()
5098                                    .w(example_width)
5099                                    .overflow_hidden()
5100                                    .child(PanelRepoFooter::new_preview(
5101                                        SharedString::from("zed"),
5102                                        Some(custom("main", behind_upstream)),
5103                                    ))
5104                                    .into_any_element(),
5105                            ),
5106                            single_example(
5107                                "Long Branch",
5108                                div()
5109                                    .w(example_width)
5110                                    .overflow_hidden()
5111                                    .child(PanelRepoFooter::new_preview(
5112                                        SharedString::from("zed"),
5113                                        Some(custom(
5114                                            "redesign-and-update-git-ui-list-entry-style",
5115                                            behind_upstream,
5116                                        )),
5117                                    ))
5118                                    .into_any_element(),
5119                            ),
5120                            single_example(
5121                                "Long Repo",
5122                                div()
5123                                    .w(example_width)
5124                                    .overflow_hidden()
5125                                    .child(PanelRepoFooter::new_preview(
5126                                        SharedString::from("zed-industries-community-examples"),
5127                                        Some(custom("gpui", ahead_of_upstream)),
5128                                    ))
5129                                    .into_any_element(),
5130                            ),
5131                            single_example(
5132                                "Long Repo & Branch",
5133                                div()
5134                                    .w(example_width)
5135                                    .overflow_hidden()
5136                                    .child(PanelRepoFooter::new_preview(
5137                                        SharedString::from("zed-industries-community-examples"),
5138                                        Some(custom(
5139                                            "redesign-and-update-git-ui-list-entry-style",
5140                                            behind_upstream,
5141                                        )),
5142                                    ))
5143                                    .into_any_element(),
5144                            ),
5145                            single_example(
5146                                "Uppercase Repo",
5147                                div()
5148                                    .w(example_width)
5149                                    .overflow_hidden()
5150                                    .child(PanelRepoFooter::new_preview(
5151                                        SharedString::from("LICENSES"),
5152                                        Some(custom("main", ahead_of_upstream)),
5153                                    ))
5154                                    .into_any_element(),
5155                            ),
5156                            single_example(
5157                                "Uppercase Branch",
5158                                div()
5159                                    .w(example_width)
5160                                    .overflow_hidden()
5161                                    .child(PanelRepoFooter::new_preview(
5162                                        SharedString::from("zed"),
5163                                        Some(custom("update-README", behind_upstream)),
5164                                    ))
5165                                    .into_any_element(),
5166                            ),
5167                        ],
5168                    )
5169                    .grow()
5170                    .vertical(),
5171                ])
5172                .into_any_element(),
5173        )
5174    }
5175}
5176
5177#[cfg(test)]
5178mod tests {
5179    use git::{
5180        repository::repo_path,
5181        status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
5182    };
5183    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
5184    use indoc::indoc;
5185    use project::FakeFs;
5186    use serde_json::json;
5187    use settings::SettingsStore;
5188    use theme::LoadThemes;
5189    use util::path;
5190    use util::rel_path::rel_path;
5191
5192    use super::*;
5193
5194    fn init_test(cx: &mut gpui::TestAppContext) {
5195        zlog::init_test();
5196
5197        cx.update(|cx| {
5198            let settings_store = SettingsStore::test(cx);
5199            cx.set_global(settings_store);
5200            theme::init(LoadThemes::JustBase, cx);
5201            editor::init(cx);
5202            crate::init(cx);
5203        });
5204    }
5205
5206    #[gpui::test]
5207    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5208        init_test(cx);
5209        let fs = FakeFs::new(cx.background_executor.clone());
5210        fs.insert_tree(
5211            "/root",
5212            json!({
5213                "zed": {
5214                    ".git": {},
5215                    "crates": {
5216                        "gpui": {
5217                            "gpui.rs": "fn main() {}"
5218                        },
5219                        "util": {
5220                            "util.rs": "fn do_it() {}"
5221                        }
5222                    }
5223                },
5224            }),
5225        )
5226        .await;
5227
5228        fs.set_status_for_repo(
5229            Path::new(path!("/root/zed/.git")),
5230            &[
5231                ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
5232                ("crates/util/util.rs", StatusCode::Modified.worktree()),
5233            ],
5234        );
5235
5236        let project =
5237            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5238        let workspace =
5239            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5240        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5241
5242        cx.read(|cx| {
5243            project
5244                .read(cx)
5245                .worktrees(cx)
5246                .next()
5247                .unwrap()
5248                .read(cx)
5249                .as_local()
5250                .unwrap()
5251                .scan_complete()
5252        })
5253        .await;
5254
5255        cx.executor().run_until_parked();
5256
5257        let panel = workspace.update(cx, GitPanel::new).unwrap();
5258
5259        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5260            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5261        });
5262        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5263        handle.await;
5264
5265        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5266        pretty_assertions::assert_eq!(
5267            entries,
5268            [
5269                GitListEntry::Header(GitHeaderEntry {
5270                    header: Section::Tracked
5271                }),
5272                GitListEntry::Status(GitStatusEntry {
5273                    repo_path: repo_path("crates/gpui/gpui.rs"),
5274                    status: StatusCode::Modified.worktree(),
5275                    staging: StageStatus::Unstaged,
5276                }),
5277                GitListEntry::Status(GitStatusEntry {
5278                    repo_path: repo_path("crates/util/util.rs"),
5279                    status: StatusCode::Modified.worktree(),
5280                    staging: StageStatus::Unstaged,
5281                },),
5282            ],
5283        );
5284
5285        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5286            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5287        });
5288        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5289        handle.await;
5290        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5291        pretty_assertions::assert_eq!(
5292            entries,
5293            [
5294                GitListEntry::Header(GitHeaderEntry {
5295                    header: Section::Tracked
5296                }),
5297                GitListEntry::Status(GitStatusEntry {
5298                    repo_path: repo_path("crates/gpui/gpui.rs"),
5299                    status: StatusCode::Modified.worktree(),
5300                    staging: StageStatus::Unstaged,
5301                }),
5302                GitListEntry::Status(GitStatusEntry {
5303                    repo_path: repo_path("crates/util/util.rs"),
5304                    status: StatusCode::Modified.worktree(),
5305                    staging: StageStatus::Unstaged,
5306                },),
5307            ],
5308        );
5309    }
5310
5311    #[gpui::test]
5312    async fn test_bulk_staging(cx: &mut TestAppContext) {
5313        use GitListEntry::*;
5314
5315        init_test(cx);
5316        let fs = FakeFs::new(cx.background_executor.clone());
5317        fs.insert_tree(
5318            "/root",
5319            json!({
5320                "project": {
5321                    ".git": {},
5322                    "src": {
5323                        "main.rs": "fn main() {}",
5324                        "lib.rs": "pub fn hello() {}",
5325                        "utils.rs": "pub fn util() {}"
5326                    },
5327                    "tests": {
5328                        "test.rs": "fn test() {}"
5329                    },
5330                    "new_file.txt": "new content",
5331                    "another_new.rs": "// new file",
5332                    "conflict.txt": "conflicted content"
5333                }
5334            }),
5335        )
5336        .await;
5337
5338        fs.set_status_for_repo(
5339            Path::new(path!("/root/project/.git")),
5340            &[
5341                ("src/main.rs", StatusCode::Modified.worktree()),
5342                ("src/lib.rs", StatusCode::Modified.worktree()),
5343                ("tests/test.rs", StatusCode::Modified.worktree()),
5344                ("new_file.txt", FileStatus::Untracked),
5345                ("another_new.rs", FileStatus::Untracked),
5346                ("src/utils.rs", FileStatus::Untracked),
5347                (
5348                    "conflict.txt",
5349                    UnmergedStatus {
5350                        first_head: UnmergedStatusCode::Updated,
5351                        second_head: UnmergedStatusCode::Updated,
5352                    }
5353                    .into(),
5354                ),
5355            ],
5356        );
5357
5358        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5359        let workspace =
5360            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5361        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5362
5363        cx.read(|cx| {
5364            project
5365                .read(cx)
5366                .worktrees(cx)
5367                .next()
5368                .unwrap()
5369                .read(cx)
5370                .as_local()
5371                .unwrap()
5372                .scan_complete()
5373        })
5374        .await;
5375
5376        cx.executor().run_until_parked();
5377
5378        let panel = workspace.update(cx, GitPanel::new).unwrap();
5379
5380        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5381            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5382        });
5383        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5384        handle.await;
5385
5386        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5387        #[rustfmt::skip]
5388        pretty_assertions::assert_matches!(
5389            entries.as_slice(),
5390            &[
5391                Header(GitHeaderEntry { header: Section::Conflict }),
5392                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5393                Header(GitHeaderEntry { header: Section::Tracked }),
5394                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5395                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5396                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5397                Header(GitHeaderEntry { header: Section::New }),
5398                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5399                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5400                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5401            ],
5402        );
5403
5404        let second_status_entry = entries[3].clone();
5405        panel.update_in(cx, |panel, window, cx| {
5406            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5407        });
5408
5409        panel.update_in(cx, |panel, window, cx| {
5410            panel.selected_entry = Some(7);
5411            panel.stage_range(&git::StageRange, window, cx);
5412        });
5413
5414        cx.read(|cx| {
5415            project
5416                .read(cx)
5417                .worktrees(cx)
5418                .next()
5419                .unwrap()
5420                .read(cx)
5421                .as_local()
5422                .unwrap()
5423                .scan_complete()
5424        })
5425        .await;
5426
5427        cx.executor().run_until_parked();
5428
5429        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5430            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5431        });
5432        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5433        handle.await;
5434
5435        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5436        #[rustfmt::skip]
5437        pretty_assertions::assert_matches!(
5438            entries.as_slice(),
5439            &[
5440                Header(GitHeaderEntry { header: Section::Conflict }),
5441                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5442                Header(GitHeaderEntry { header: Section::Tracked }),
5443                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5444                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5445                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5446                Header(GitHeaderEntry { header: Section::New }),
5447                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5448                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5449                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5450            ],
5451        );
5452
5453        let third_status_entry = entries[4].clone();
5454        panel.update_in(cx, |panel, window, cx| {
5455            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5456        });
5457
5458        panel.update_in(cx, |panel, window, cx| {
5459            panel.selected_entry = Some(9);
5460            panel.stage_range(&git::StageRange, window, cx);
5461        });
5462
5463        cx.read(|cx| {
5464            project
5465                .read(cx)
5466                .worktrees(cx)
5467                .next()
5468                .unwrap()
5469                .read(cx)
5470                .as_local()
5471                .unwrap()
5472                .scan_complete()
5473        })
5474        .await;
5475
5476        cx.executor().run_until_parked();
5477
5478        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5479            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5480        });
5481        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5482        handle.await;
5483
5484        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5485        #[rustfmt::skip]
5486        pretty_assertions::assert_matches!(
5487            entries.as_slice(),
5488            &[
5489                Header(GitHeaderEntry { header: Section::Conflict }),
5490                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5491                Header(GitHeaderEntry { header: Section::Tracked }),
5492                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5493                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5494                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5495                Header(GitHeaderEntry { header: Section::New }),
5496                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5497                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5498                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5499            ],
5500        );
5501    }
5502
5503    #[gpui::test]
5504    async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
5505        use GitListEntry::*;
5506
5507        init_test(cx);
5508        let fs = FakeFs::new(cx.background_executor.clone());
5509        fs.insert_tree(
5510            "/root",
5511            json!({
5512                "project": {
5513                    ".git": {},
5514                    "src": {
5515                        "main.rs": "fn main() {}",
5516                        "lib.rs": "pub fn hello() {}",
5517                        "utils.rs": "pub fn util() {}"
5518                    },
5519                    "tests": {
5520                        "test.rs": "fn test() {}"
5521                    },
5522                    "new_file.txt": "new content",
5523                    "another_new.rs": "// new file",
5524                    "conflict.txt": "conflicted content"
5525                }
5526            }),
5527        )
5528        .await;
5529
5530        fs.set_status_for_repo(
5531            Path::new(path!("/root/project/.git")),
5532            &[
5533                ("src/main.rs", StatusCode::Modified.worktree()),
5534                ("src/lib.rs", StatusCode::Modified.worktree()),
5535                ("tests/test.rs", StatusCode::Modified.worktree()),
5536                ("new_file.txt", FileStatus::Untracked),
5537                ("another_new.rs", FileStatus::Untracked),
5538                ("src/utils.rs", FileStatus::Untracked),
5539                (
5540                    "conflict.txt",
5541                    UnmergedStatus {
5542                        first_head: UnmergedStatusCode::Updated,
5543                        second_head: UnmergedStatusCode::Updated,
5544                    }
5545                    .into(),
5546                ),
5547            ],
5548        );
5549
5550        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5551        let workspace =
5552            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5553        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5554
5555        cx.read(|cx| {
5556            project
5557                .read(cx)
5558                .worktrees(cx)
5559                .next()
5560                .unwrap()
5561                .read(cx)
5562                .as_local()
5563                .unwrap()
5564                .scan_complete()
5565        })
5566        .await;
5567
5568        cx.executor().run_until_parked();
5569
5570        let panel = workspace.update(cx, GitPanel::new).unwrap();
5571
5572        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5573            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5574        });
5575        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5576        handle.await;
5577
5578        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5579        #[rustfmt::skip]
5580        pretty_assertions::assert_matches!(
5581            entries.as_slice(),
5582            &[
5583                Header(GitHeaderEntry { header: Section::Conflict }),
5584                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5585                Header(GitHeaderEntry { header: Section::Tracked }),
5586                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5587                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5588                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5589                Header(GitHeaderEntry { header: Section::New }),
5590                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5591                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5592                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5593            ],
5594        );
5595
5596        assert_entry_paths(
5597            &entries,
5598            &[
5599                None,
5600                Some("conflict.txt"),
5601                None,
5602                Some("src/lib.rs"),
5603                Some("src/main.rs"),
5604                Some("tests/test.rs"),
5605                None,
5606                Some("another_new.rs"),
5607                Some("new_file.txt"),
5608                Some("src/utils.rs"),
5609            ],
5610        );
5611
5612        let second_status_entry = entries[3].clone();
5613        panel.update_in(cx, |panel, window, cx| {
5614            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5615        });
5616
5617        cx.update(|_window, cx| {
5618            SettingsStore::update_global(cx, |store, cx| {
5619                store.update_user_settings(cx, |settings| {
5620                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5621                })
5622            });
5623        });
5624
5625        panel.update_in(cx, |panel, window, cx| {
5626            panel.selected_entry = Some(7);
5627            panel.stage_range(&git::StageRange, window, cx);
5628        });
5629
5630        cx.read(|cx| {
5631            project
5632                .read(cx)
5633                .worktrees(cx)
5634                .next()
5635                .unwrap()
5636                .read(cx)
5637                .as_local()
5638                .unwrap()
5639                .scan_complete()
5640        })
5641        .await;
5642
5643        cx.executor().run_until_parked();
5644
5645        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5646            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5647        });
5648        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5649        handle.await;
5650
5651        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5652        #[rustfmt::skip]
5653        pretty_assertions::assert_matches!(
5654            entries.as_slice(),
5655            &[
5656                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5657                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5658                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5659                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5660                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5661                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5662                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5663            ],
5664        );
5665
5666        assert_entry_paths(
5667            &entries,
5668            &[
5669                Some("another_new.rs"),
5670                Some("conflict.txt"),
5671                Some("new_file.txt"),
5672                Some("src/lib.rs"),
5673                Some("src/main.rs"),
5674                Some("src/utils.rs"),
5675                Some("tests/test.rs"),
5676            ],
5677        );
5678
5679        let third_status_entry = entries[4].clone();
5680        panel.update_in(cx, |panel, window, cx| {
5681            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5682        });
5683
5684        panel.update_in(cx, |panel, window, cx| {
5685            panel.selected_entry = Some(9);
5686            panel.stage_range(&git::StageRange, window, cx);
5687        });
5688
5689        cx.read(|cx| {
5690            project
5691                .read(cx)
5692                .worktrees(cx)
5693                .next()
5694                .unwrap()
5695                .read(cx)
5696                .as_local()
5697                .unwrap()
5698                .scan_complete()
5699        })
5700        .await;
5701
5702        cx.executor().run_until_parked();
5703
5704        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5705            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5706        });
5707        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5708        handle.await;
5709
5710        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5711        #[rustfmt::skip]
5712        pretty_assertions::assert_matches!(
5713            entries.as_slice(),
5714            &[
5715                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5716                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5717                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5718                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5719                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5720                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5721                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5722            ],
5723        );
5724
5725        assert_entry_paths(
5726            &entries,
5727            &[
5728                Some("another_new.rs"),
5729                Some("conflict.txt"),
5730                Some("new_file.txt"),
5731                Some("src/lib.rs"),
5732                Some("src/main.rs"),
5733                Some("src/utils.rs"),
5734                Some("tests/test.rs"),
5735            ],
5736        );
5737    }
5738
5739    #[gpui::test]
5740    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5741        init_test(cx);
5742        let fs = FakeFs::new(cx.background_executor.clone());
5743        fs.insert_tree(
5744            "/root",
5745            json!({
5746                "project": {
5747                    ".git": {},
5748                    "src": {
5749                        "main.rs": "fn main() {}"
5750                    }
5751                }
5752            }),
5753        )
5754        .await;
5755
5756        fs.set_status_for_repo(
5757            Path::new(path!("/root/project/.git")),
5758            &[("src/main.rs", StatusCode::Modified.worktree())],
5759        );
5760
5761        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5762        let workspace =
5763            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5764        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5765
5766        let panel = workspace.update(cx, GitPanel::new).unwrap();
5767
5768        // Test: User has commit message, enables amend (saves message), then disables (restores message)
5769        panel.update(cx, |panel, cx| {
5770            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5771                let start = buffer.anchor_before(0);
5772                let end = buffer.anchor_after(buffer.len());
5773                buffer.edit([(start..end, "Initial commit message")], None, cx);
5774            });
5775
5776            panel.set_amend_pending(true, cx);
5777            assert!(panel.original_commit_message.is_some());
5778
5779            panel.set_amend_pending(false, cx);
5780            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5781            assert_eq!(current_message, "Initial commit message");
5782            assert!(panel.original_commit_message.is_none());
5783        });
5784
5785        // Test: User has empty commit message, enables amend, then disables (clears message)
5786        panel.update(cx, |panel, cx| {
5787            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5788                let start = buffer.anchor_before(0);
5789                let end = buffer.anchor_after(buffer.len());
5790                buffer.edit([(start..end, "")], None, cx);
5791            });
5792
5793            panel.set_amend_pending(true, cx);
5794            assert!(panel.original_commit_message.is_none());
5795
5796            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5797                let start = buffer.anchor_before(0);
5798                let end = buffer.anchor_after(buffer.len());
5799                buffer.edit([(start..end, "Previous commit message")], None, cx);
5800            });
5801
5802            panel.set_amend_pending(false, cx);
5803            let current_message = panel.commit_message_buffer(cx).read(cx).text();
5804            assert_eq!(current_message, "");
5805        });
5806    }
5807
5808    #[gpui::test]
5809    async fn test_open_diff(cx: &mut TestAppContext) {
5810        init_test(cx);
5811
5812        let fs = FakeFs::new(cx.background_executor.clone());
5813        fs.insert_tree(
5814            path!("/project"),
5815            json!({
5816                ".git": {},
5817                "tracked": "tracked\n",
5818                "untracked": "\n",
5819            }),
5820        )
5821        .await;
5822
5823        fs.set_head_and_index_for_repo(
5824            path!("/project/.git").as_ref(),
5825            &[("tracked", "old tracked\n".into())],
5826        );
5827
5828        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
5829        let workspace =
5830            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5831        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5832        let panel = workspace.update(cx, GitPanel::new).unwrap();
5833
5834        // Enable the `sort_by_path` setting and wait for entries to be updated,
5835        // as there should no longer be separators between Tracked and Untracked
5836        // files.
5837        cx.update(|_window, cx| {
5838            SettingsStore::update_global(cx, |store, cx| {
5839                store.update_user_settings(cx, |settings| {
5840                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5841                })
5842            });
5843        });
5844
5845        cx.update_window_entity(&panel, |panel, _, _| {
5846            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5847        })
5848        .await;
5849
5850        // Confirm that `Open Diff` still works for the untracked file, updating
5851        // the Project Diff's active path.
5852        panel.update_in(cx, |panel, window, cx| {
5853            panel.selected_entry = Some(1);
5854            panel.open_diff(&Confirm, window, cx);
5855        });
5856        cx.run_until_parked();
5857
5858        let _ = workspace.update(cx, |workspace, _window, cx| {
5859            let active_path = workspace
5860                .item_of_type::<ProjectDiff>(cx)
5861                .expect("ProjectDiff should exist")
5862                .read(cx)
5863                .active_path(cx)
5864                .expect("active_path should exist");
5865
5866            assert_eq!(active_path.path, rel_path("untracked").into_arc());
5867        });
5868    }
5869
5870    fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
5871        assert_eq!(entries.len(), expected_paths.len());
5872        for (entry, expected_path) in entries.iter().zip(expected_paths) {
5873            assert_eq!(
5874                entry.status_entry().map(|status| status
5875                    .repo_path
5876                    .as_ref()
5877                    .as_std_path()
5878                    .to_string_lossy()
5879                    .to_string()),
5880                expected_path.map(|s| s.to_string())
5881            );
5882        }
5883    }
5884
5885    #[test]
5886    fn test_compress_diff_no_truncation() {
5887        let diff = indoc! {"
5888            --- a/file.txt
5889            +++ b/file.txt
5890            @@ -1,2 +1,2 @@
5891            -old
5892            +new
5893        "};
5894        let result = GitPanel::compress_commit_diff(diff, 1000);
5895        assert_eq!(result, diff);
5896    }
5897
5898    #[test]
5899    fn test_compress_diff_truncate_long_lines() {
5900        let long_line = "a".repeat(300);
5901        let diff = indoc::formatdoc! {"
5902            --- a/file.txt
5903            +++ b/file.txt
5904            @@ -1,2 +1,3 @@
5905             context
5906            +{}
5907             more context
5908        ", long_line};
5909        let result = GitPanel::compress_commit_diff(&diff, 100);
5910        assert!(result.contains("...[truncated]"));
5911        assert!(result.len() < diff.len());
5912    }
5913
5914    #[test]
5915    fn test_compress_diff_truncate_hunks() {
5916        let diff = indoc! {"
5917            --- a/file.txt
5918            +++ b/file.txt
5919            @@ -1,2 +1,2 @@
5920             context
5921            -old1
5922            +new1
5923            @@ -5,2 +5,2 @@
5924             context 2
5925            -old2
5926            +new2
5927            @@ -10,2 +10,2 @@
5928             context 3
5929            -old3
5930            +new3
5931        "};
5932        let result = GitPanel::compress_commit_diff(diff, 100);
5933        let expected = indoc! {"
5934            --- a/file.txt
5935            +++ b/file.txt
5936            @@ -1,2 +1,2 @@
5937             context
5938            -old1
5939            +new1
5940            [...skipped 2 hunks...]
5941        "};
5942        assert_eq!(result, expected);
5943    }
5944
5945    #[gpui::test]
5946    async fn test_suggest_commit_message(cx: &mut TestAppContext) {
5947        init_test(cx);
5948
5949        let fs = FakeFs::new(cx.background_executor.clone());
5950        fs.insert_tree(
5951            path!("/project"),
5952            json!({
5953                ".git": {},
5954                "tracked": "tracked\n",
5955                "untracked": "\n",
5956            }),
5957        )
5958        .await;
5959
5960        fs.set_head_and_index_for_repo(
5961            path!("/project/.git").as_ref(),
5962            &[("tracked", "old tracked\n".into())],
5963        );
5964
5965        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
5966        let workspace =
5967            cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5968        let cx = &mut VisualTestContext::from_window(*workspace, cx);
5969        let panel = workspace.update(cx, GitPanel::new).unwrap();
5970
5971        let handle = cx.update_window_entity(&panel, |panel, _, _| {
5972            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5973        });
5974        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5975        handle.await;
5976
5977        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5978
5979        // GitPanel
5980        // - Tracked:
5981        // - [] tracked
5982        // - Untracked
5983        // - [] untracked
5984        //
5985        // The commit message should now read:
5986        // "Update tracked"
5987        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
5988        assert_eq!(message, Some("Update tracked".to_string()));
5989
5990        let first_status_entry = entries[1].clone();
5991        panel.update_in(cx, |panel, window, cx| {
5992            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
5993        });
5994
5995        cx.read(|cx| {
5996            project
5997                .read(cx)
5998                .worktrees(cx)
5999                .next()
6000                .unwrap()
6001                .read(cx)
6002                .as_local()
6003                .unwrap()
6004                .scan_complete()
6005        })
6006        .await;
6007
6008        cx.executor().run_until_parked();
6009
6010        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6011            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6012        });
6013        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6014        handle.await;
6015
6016        // GitPanel
6017        // - Tracked:
6018        // - [x] tracked
6019        // - Untracked
6020        // - [] untracked
6021        //
6022        // The commit message should still read:
6023        // "Update tracked"
6024        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6025        assert_eq!(message, Some("Update tracked".to_string()));
6026
6027        let second_status_entry = entries[3].clone();
6028        panel.update_in(cx, |panel, window, cx| {
6029            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6030        });
6031
6032        cx.read(|cx| {
6033            project
6034                .read(cx)
6035                .worktrees(cx)
6036                .next()
6037                .unwrap()
6038                .read(cx)
6039                .as_local()
6040                .unwrap()
6041                .scan_complete()
6042        })
6043        .await;
6044
6045        cx.executor().run_until_parked();
6046
6047        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6048            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6049        });
6050        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6051        handle.await;
6052
6053        // GitPanel
6054        // - Tracked:
6055        // - [x] tracked
6056        // - Untracked
6057        // - [x] untracked
6058        //
6059        // The commit message should now read:
6060        // "Enter commit message"
6061        // (which means we should see None returned).
6062        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6063        assert!(message.is_none());
6064
6065        panel.update_in(cx, |panel, window, cx| {
6066            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
6067        });
6068
6069        cx.read(|cx| {
6070            project
6071                .read(cx)
6072                .worktrees(cx)
6073                .next()
6074                .unwrap()
6075                .read(cx)
6076                .as_local()
6077                .unwrap()
6078                .scan_complete()
6079        })
6080        .await;
6081
6082        cx.executor().run_until_parked();
6083
6084        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6085            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6086        });
6087        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6088        handle.await;
6089
6090        // GitPanel
6091        // - Tracked:
6092        // - [] tracked
6093        // - Untracked
6094        // - [x] untracked
6095        //
6096        // The commit message should now read:
6097        // "Update untracked"
6098        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6099        assert_eq!(message, Some("Create untracked".to_string()));
6100
6101        panel.update_in(cx, |panel, window, cx| {
6102            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6103        });
6104
6105        cx.read(|cx| {
6106            project
6107                .read(cx)
6108                .worktrees(cx)
6109                .next()
6110                .unwrap()
6111                .read(cx)
6112                .as_local()
6113                .unwrap()
6114                .scan_complete()
6115        })
6116        .await;
6117
6118        cx.executor().run_until_parked();
6119
6120        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6121            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6122        });
6123        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6124        handle.await;
6125
6126        // GitPanel
6127        // - Tracked:
6128        // - [] tracked
6129        // - Untracked
6130        // - [] untracked
6131        //
6132        // The commit message should now read:
6133        // "Update tracked"
6134        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6135        assert_eq!(message, Some("Update tracked".to_string()));
6136    }
6137}