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