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