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