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::BranchChanged,
 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                },
2159                window,
2160                cx,
2161            );
2162            true
2163        } else {
2164            cx.propagate();
2165            false
2166        }
2167    }
2168
2169    fn on_amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
2170        if self.amend(&self.commit_editor.focus_handle(cx), window, cx) {
2171            telemetry::event!("Git Amended", source = "Git Panel");
2172        }
2173    }
2174
2175    /// Amends the most recent commit with staged changes and/or an updated commit message.
2176    ///
2177    /// Uses a two-stage workflow where the first invocation loads the commit
2178    /// message for editing, second invocation performs the amend. Returns
2179    /// `true` if the amend was executed, `false` otherwise.
2180    pub(crate) fn amend(
2181        &mut self,
2182        commit_editor_focus_handle: &FocusHandle,
2183        window: &mut Window,
2184        cx: &mut Context<Self>,
2185    ) -> bool {
2186        if commit_editor_focus_handle.contains_focused(window, cx) {
2187            if self.head_commit(cx).is_some() {
2188                if !self.amend_pending {
2189                    self.set_amend_pending(true, cx);
2190                    self.load_last_commit_message(cx);
2191
2192                    return false;
2193                } else {
2194                    self.commit_changes(
2195                        CommitOptions {
2196                            amend: true,
2197                            signoff: self.signoff_enabled,
2198                        },
2199                        window,
2200                        cx,
2201                    );
2202
2203                    return true;
2204                }
2205            }
2206            return false;
2207        } else {
2208            cx.propagate();
2209            return false;
2210        }
2211    }
2212    pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
2213        self.active_repository
2214            .as_ref()
2215            .and_then(|repo| repo.read(cx).head_commit.as_ref())
2216            .cloned()
2217    }
2218
2219    pub fn load_last_commit_message(&mut self, cx: &mut Context<Self>) {
2220        let Some(head_commit) = self.head_commit(cx) else {
2221            return;
2222        };
2223
2224        let recent_sha = head_commit.sha.to_string();
2225        let detail_task = self.load_commit_details(recent_sha, cx);
2226        cx.spawn(async move |this, cx| {
2227            if let Ok(message) = detail_task.await.map(|detail| detail.message) {
2228                this.update(cx, |this, cx| {
2229                    this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2230                        let start = buffer.anchor_before(0);
2231                        let end = buffer.anchor_after(buffer.len());
2232                        buffer.edit([(start..end, message)], None, cx);
2233                    });
2234                })
2235                .log_err();
2236            }
2237        })
2238        .detach();
2239    }
2240
2241    fn custom_or_suggested_commit_message(
2242        &self,
2243        window: &mut Window,
2244        cx: &mut Context<Self>,
2245    ) -> Option<String> {
2246        let git_commit_language = self
2247            .commit_editor
2248            .read(cx)
2249            .language_at(MultiBufferOffset(0), cx);
2250        let message = self.commit_editor.read(cx).text(cx);
2251        if message.is_empty() {
2252            return self
2253                .suggest_commit_message(cx)
2254                .filter(|message| !message.trim().is_empty());
2255        } else if message.trim().is_empty() {
2256            return None;
2257        }
2258        let buffer = cx.new(|cx| {
2259            let mut buffer = Buffer::local(message, cx);
2260            buffer.set_language(git_commit_language, cx);
2261            buffer
2262        });
2263        let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
2264        let wrapped_message = editor.update(cx, |editor, cx| {
2265            editor.select_all(&Default::default(), window, cx);
2266            editor.rewrap_impl(
2267                RewrapOptions {
2268                    override_language_settings: false,
2269                    preserve_existing_whitespace: true,
2270                    line_length: None,
2271                },
2272                cx,
2273            );
2274            editor.text(cx)
2275        });
2276        if wrapped_message.trim().is_empty() {
2277            return None;
2278        }
2279        Some(wrapped_message)
2280    }
2281
2282    fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
2283        let text = self.commit_editor.read(cx).text(cx);
2284        if !text.trim().is_empty() {
2285            true
2286        } else if text.is_empty() {
2287            self.suggest_commit_message(cx)
2288                .is_some_and(|text| !text.trim().is_empty())
2289        } else {
2290            false
2291        }
2292    }
2293
2294    pub(crate) fn commit_changes(
2295        &mut self,
2296        options: CommitOptions,
2297        window: &mut Window,
2298        cx: &mut Context<Self>,
2299    ) {
2300        let Some(active_repository) = self.active_repository.clone() else {
2301            return;
2302        };
2303        let error_spawn = |message, window: &mut Window, cx: &mut App| {
2304            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
2305            cx.spawn(async move |_| {
2306                prompt.await.ok();
2307            })
2308            .detach();
2309        };
2310
2311        if self.has_unstaged_conflicts() {
2312            error_spawn(
2313                "There are still conflicts. You must stage these before committing",
2314                window,
2315                cx,
2316            );
2317            return;
2318        }
2319
2320        let askpass = self.askpass_delegate("git commit", window, cx);
2321        let commit_message = self.custom_or_suggested_commit_message(window, cx);
2322
2323        let Some(mut message) = commit_message else {
2324            self.commit_editor
2325                .read(cx)
2326                .focus_handle(cx)
2327                .focus(window, cx);
2328            return;
2329        };
2330
2331        if self.add_coauthors {
2332            self.fill_co_authors(&mut message, cx);
2333        }
2334
2335        let task = if self.has_staged_changes() {
2336            // Repository serializes all git operations, so we can just send a commit immediately
2337            let commit_task = active_repository.update(cx, |repo, cx| {
2338                repo.commit(message.into(), None, options, askpass, cx)
2339            });
2340            cx.background_spawn(async move { commit_task.await? })
2341        } else {
2342            let changed_files = self
2343                .entries
2344                .iter()
2345                .filter_map(|entry| entry.status_entry())
2346                .filter(|status_entry| !status_entry.status.is_created())
2347                .map(|status_entry| status_entry.repo_path.clone())
2348                .collect::<Vec<_>>();
2349
2350            if changed_files.is_empty() && !options.amend {
2351                error_spawn("No changes to commit", window, cx);
2352                return;
2353            }
2354
2355            let stage_task =
2356                active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
2357            cx.spawn(async move |_, cx| {
2358                stage_task.await?;
2359                let commit_task = active_repository.update(cx, |repo, cx| {
2360                    repo.commit(message.into(), None, options, askpass, cx)
2361                });
2362                commit_task.await?
2363            })
2364        };
2365        let task = cx.spawn_in(window, async move |this, cx| {
2366            let result = task.await;
2367            this.update_in(cx, |this, window, cx| {
2368                this.pending_commit.take();
2369
2370                match result {
2371                    Ok(()) => {
2372                        if options.amend {
2373                            this.set_amend_pending(false, cx);
2374                        } else {
2375                            this.commit_editor
2376                                .update(cx, |editor, cx| editor.clear(window, cx));
2377                            this.original_commit_message = None;
2378                        }
2379                    }
2380                    Err(e) => this.show_error_toast("commit", e, cx),
2381                }
2382            })
2383            .ok();
2384        });
2385
2386        self.pending_commit = Some(task);
2387    }
2388
2389    pub(crate) fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2390        let Some(repo) = self.active_repository.clone() else {
2391            return;
2392        };
2393        telemetry::event!("Git Uncommitted");
2394
2395        let confirmation = self.check_for_pushed_commits(window, cx);
2396        let prior_head = self.load_commit_details("HEAD".to_string(), cx);
2397
2398        let task = cx.spawn_in(window, async move |this, cx| {
2399            let result = maybe!(async {
2400                if let Ok(true) = confirmation.await {
2401                    let prior_head = prior_head.await?;
2402
2403                    repo.update(cx, |repo, cx| {
2404                        repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
2405                    })
2406                    .await??;
2407
2408                    Ok(Some(prior_head))
2409                } else {
2410                    Ok(None)
2411                }
2412            })
2413            .await;
2414
2415            this.update_in(cx, |this, window, cx| {
2416                this.pending_commit.take();
2417                match result {
2418                    Ok(None) => {}
2419                    Ok(Some(prior_commit)) => {
2420                        this.commit_editor.update(cx, |editor, cx| {
2421                            editor.set_text(prior_commit.message, window, cx)
2422                        });
2423                    }
2424                    Err(e) => this.show_error_toast("reset", e, cx),
2425                }
2426            })
2427            .ok();
2428        });
2429
2430        self.pending_commit = Some(task);
2431    }
2432
2433    fn check_for_pushed_commits(
2434        &mut self,
2435        window: &mut Window,
2436        cx: &mut Context<Self>,
2437    ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
2438        let repo = self.active_repository.clone();
2439        let mut cx = window.to_async(cx);
2440
2441        async move {
2442            let repo = repo.context("No active repository")?;
2443
2444            let pushed_to: Vec<SharedString> = repo
2445                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())
2446                .await??;
2447
2448            if pushed_to.is_empty() {
2449                Ok(true)
2450            } else {
2451                #[derive(strum::EnumIter, strum::VariantNames)]
2452                #[strum(serialize_all = "title_case")]
2453                enum CancelUncommit {
2454                    Uncommit,
2455                    Cancel,
2456                }
2457                let detail = format!(
2458                    "This commit was already pushed to {}.",
2459                    pushed_to.into_iter().join(", ")
2460                );
2461                let result = cx
2462                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
2463                    .await?;
2464
2465                match result {
2466                    CancelUncommit::Cancel => Ok(false),
2467                    CancelUncommit::Uncommit => Ok(true),
2468                }
2469            }
2470        }
2471    }
2472
2473    /// Suggests a commit message based on the changed files and their statuses
2474    pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
2475        if let Some(merge_message) = self
2476            .active_repository
2477            .as_ref()
2478            .and_then(|repo| repo.read(cx).merge.message.as_ref())
2479        {
2480            return Some(merge_message.to_string());
2481        }
2482
2483        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
2484            Some(staged_entry)
2485        } else if self.total_staged_count() == 0
2486            && let Some(single_tracked_entry) = &self.single_tracked_entry
2487        {
2488            Some(single_tracked_entry)
2489        } else {
2490            None
2491        }?;
2492
2493        let action_text = if git_status_entry.status.is_deleted() {
2494            Some("Delete")
2495        } else if git_status_entry.status.is_created() {
2496            Some("Create")
2497        } else if git_status_entry.status.is_modified() {
2498            Some("Update")
2499        } else {
2500            None
2501        }?;
2502
2503        let file_name = git_status_entry
2504            .repo_path
2505            .file_name()
2506            .unwrap_or_default()
2507            .to_string();
2508
2509        Some(format!("{} {}", action_text, file_name))
2510    }
2511
2512    fn generate_commit_message_action(
2513        &mut self,
2514        _: &git::GenerateCommitMessage,
2515        _window: &mut Window,
2516        cx: &mut Context<Self>,
2517    ) {
2518        self.generate_commit_message(cx);
2519    }
2520
2521    fn split_patch(patch: &str) -> Vec<String> {
2522        let mut result = Vec::new();
2523        let mut current_patch = String::new();
2524
2525        for line in patch.lines() {
2526            if line.starts_with("---") && !current_patch.is_empty() {
2527                result.push(current_patch.trim_end_matches('\n').into());
2528                current_patch = String::new();
2529            }
2530            current_patch.push_str(line);
2531            current_patch.push('\n');
2532        }
2533
2534        if !current_patch.is_empty() {
2535            result.push(current_patch.trim_end_matches('\n').into());
2536        }
2537
2538        result
2539    }
2540    fn truncate_iteratively(patch: &str, max_bytes: usize) -> String {
2541        let mut current_size = patch.len();
2542        if current_size <= max_bytes {
2543            return patch.to_string();
2544        }
2545        let file_patches = Self::split_patch(patch);
2546        let mut file_infos: Vec<TruncatedPatch> = file_patches
2547            .iter()
2548            .filter_map(|patch| TruncatedPatch::from_unified_diff(patch))
2549            .collect();
2550
2551        if file_infos.is_empty() {
2552            return patch.to_string();
2553        }
2554
2555        current_size = file_infos.iter().map(|f| f.calculate_size()).sum::<usize>();
2556        while current_size > max_bytes {
2557            let file_idx = file_infos
2558                .iter()
2559                .enumerate()
2560                .filter(|(_, f)| f.hunks_to_keep > 1)
2561                .max_by_key(|(_, f)| f.hunks_to_keep)
2562                .map(|(idx, _)| idx);
2563            match file_idx {
2564                Some(idx) => {
2565                    let file = &mut file_infos[idx];
2566                    let size_before = file.calculate_size();
2567                    file.hunks_to_keep -= 1;
2568                    let size_after = file.calculate_size();
2569                    let saved = size_before.saturating_sub(size_after);
2570                    current_size = current_size.saturating_sub(saved);
2571                }
2572                None => {
2573                    break;
2574                }
2575            }
2576        }
2577
2578        file_infos
2579            .iter()
2580            .map(|info| info.to_string())
2581            .collect::<Vec<_>>()
2582            .join("\n")
2583    }
2584
2585    pub fn compress_commit_diff(diff_text: &str, max_bytes: usize) -> String {
2586        if diff_text.len() <= max_bytes {
2587            return diff_text.to_string();
2588        }
2589
2590        let mut compressed = diff_text
2591            .lines()
2592            .map(|line| {
2593                if line.len() > 256 {
2594                    format!("{}...[truncated]\n", &line[..line.floor_char_boundary(256)])
2595                } else {
2596                    format!("{}\n", line)
2597                }
2598            })
2599            .collect::<Vec<_>>()
2600            .join("");
2601
2602        if compressed.len() <= max_bytes {
2603            return compressed;
2604        }
2605
2606        compressed = Self::truncate_iteratively(&compressed, max_bytes);
2607
2608        compressed
2609    }
2610
2611    async fn load_project_rules(
2612        project: &Entity<Project>,
2613        repo_work_dir: &Arc<Path>,
2614        cx: &mut AsyncApp,
2615    ) -> Option<String> {
2616        let rules_path = cx.update(|cx| {
2617            for worktree in project.read(cx).worktrees(cx) {
2618                let worktree_abs_path = worktree.read(cx).abs_path();
2619                if !worktree_abs_path.starts_with(&repo_work_dir) {
2620                    continue;
2621                }
2622
2623                let worktree_snapshot = worktree.read(cx).snapshot();
2624                for rules_name in RULES_FILE_NAMES {
2625                    if let Ok(rel_path) = RelPath::unix(rules_name) {
2626                        if let Some(entry) = worktree_snapshot.entry_for_path(rel_path) {
2627                            if entry.is_file() {
2628                                return Some(ProjectPath {
2629                                    worktree_id: worktree.read(cx).id(),
2630                                    path: entry.path.clone(),
2631                                });
2632                            }
2633                        }
2634                    }
2635                }
2636            }
2637            None
2638        })?;
2639
2640        let buffer = project
2641            .update(cx, |project, cx| project.open_buffer(rules_path, cx))
2642            .await
2643            .ok()?;
2644
2645        let content = buffer
2646            .read_with(cx, |buffer, _| buffer.text())
2647            .trim()
2648            .to_string();
2649
2650        if content.is_empty() {
2651            None
2652        } else {
2653            Some(content)
2654        }
2655    }
2656
2657    async fn load_commit_message_prompt(cx: &mut AsyncApp) -> String {
2658        let load = async {
2659            let store = cx.update(|cx| PromptStore::global(cx)).await.ok()?;
2660            store
2661                .update(cx, |s, cx| {
2662                    s.load(PromptId::BuiltIn(BuiltInPrompt::CommitMessage), cx)
2663                })
2664                .await
2665                .ok()
2666        };
2667        load.await
2668            .unwrap_or_else(|| BuiltInPrompt::CommitMessage.default_content().to_string())
2669    }
2670
2671    /// Generates a commit message using an LLM.
2672    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
2673        if !self.can_commit() || !AgentSettings::get_global(cx).enabled(cx) {
2674            return;
2675        }
2676
2677        let Some(ConfiguredModel { provider, model }) =
2678            LanguageModelRegistry::read_global(cx).commit_message_model()
2679        else {
2680            return;
2681        };
2682
2683        let Some(repo) = self.active_repository.as_ref() else {
2684            return;
2685        };
2686
2687        telemetry::event!("Git Commit Message Generated");
2688
2689        let diff = repo.update(cx, |repo, cx| {
2690            if self.has_staged_changes() {
2691                repo.diff(DiffType::HeadToIndex, cx)
2692            } else {
2693                repo.diff(DiffType::HeadToWorktree, cx)
2694            }
2695        });
2696
2697        let temperature = AgentSettings::temperature_for_model(&model, cx);
2698        let project = self.project.clone();
2699        let repo_work_dir = repo.read(cx).work_directory_abs_path.clone();
2700
2701        self.generate_commit_message_task = Some(cx.spawn(async move |this, mut cx| {
2702             async move {
2703                let _defer = cx.on_drop(&this, |this, _cx| {
2704                    this.generate_commit_message_task.take();
2705                });
2706
2707                if let Some(task) = cx.update(|cx| {
2708                    if !provider.is_authenticated(cx) {
2709                        Some(provider.authenticate(cx))
2710                    } else {
2711                        None
2712                    }
2713                }) {
2714                    task.await.log_err();
2715                }
2716
2717                let mut diff_text = match diff.await {
2718                    Ok(result) => match result {
2719                        Ok(text) => text,
2720                        Err(e) => {
2721                            Self::show_commit_message_error(&this, &e, cx);
2722                            return anyhow::Ok(());
2723                        }
2724                    },
2725                    Err(e) => {
2726                        Self::show_commit_message_error(&this, &e, cx);
2727                        return anyhow::Ok(());
2728                    }
2729                };
2730
2731                const MAX_DIFF_BYTES: usize = 20_000;
2732                diff_text = Self::compress_commit_diff(&diff_text, MAX_DIFF_BYTES);
2733
2734                let rules_content = Self::load_project_rules(&project, &repo_work_dir, &mut cx).await;
2735
2736                let prompt = Self::load_commit_message_prompt(&mut cx).await;
2737
2738                let subject = this.update(cx, |this, cx| {
2739                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
2740                })?;
2741
2742                let text_empty = subject.trim().is_empty();
2743
2744                let rules_section = match &rules_content {
2745                    Some(rules) => format!(
2746                        "\n\nThe user has provided the following project rules that you should follow when writing the commit message:\n\
2747                        <project_rules>\n{rules}\n</project_rules>\n"
2748                    ),
2749                    None => String::new(),
2750                };
2751
2752                let subject_section = if text_empty {
2753                    String::new()
2754                } else {
2755                    format!("\nHere is the user's subject line:\n{subject}")
2756                };
2757
2758                let content = format!(
2759                    "{prompt}{rules_section}{subject_section}\nHere are the changes in this commit:\n{diff_text}"
2760                );
2761
2762                let request = LanguageModelRequest {
2763                    thread_id: None,
2764                    prompt_id: None,
2765                    intent: Some(CompletionIntent::GenerateGitCommitMessage),
2766                    messages: vec![LanguageModelRequestMessage {
2767                        role: Role::User,
2768                        content: vec![content.into()],
2769                        cache: false,
2770                        reasoning_details: None,
2771                    }],
2772                    tools: Vec::new(),
2773                    tool_choice: None,
2774                    stop: Vec::new(),
2775                    temperature,
2776                    thinking_allowed: false,
2777                    thinking_effort: None,
2778                    speed: None,
2779                };
2780
2781                let stream = model.stream_completion_text(request, cx);
2782                match stream.await {
2783                    Ok(mut messages) => {
2784                        if !text_empty {
2785                            this.update(cx, |this, cx| {
2786                                this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2787                                    let insert_position = buffer.anchor_before(buffer.len());
2788                                    buffer.edit([(insert_position..insert_position, "\n")], None, cx)
2789                                });
2790                            })?;
2791                        }
2792
2793                        while let Some(message) = messages.stream.next().await {
2794                            match message {
2795                                Ok(text) => {
2796                                    this.update(cx, |this, cx| {
2797                                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2798                                            let insert_position = buffer.anchor_before(buffer.len());
2799                                            buffer.edit([(insert_position..insert_position, text)], None, cx);
2800                                        });
2801                                    })?;
2802                                }
2803                                Err(e) => {
2804                                    Self::show_commit_message_error(&this, &e, cx);
2805                                    break;
2806                                }
2807                            }
2808                        }
2809                    }
2810                    Err(e) => {
2811                        Self::show_commit_message_error(&this, &e, cx);
2812                    }
2813                }
2814
2815                anyhow::Ok(())
2816            }
2817            .log_err().await
2818        }));
2819    }
2820
2821    fn get_fetch_options(
2822        &self,
2823        window: &mut Window,
2824        cx: &mut Context<Self>,
2825    ) -> Task<Option<FetchOptions>> {
2826        let repo = self.active_repository.clone();
2827        let workspace = self.workspace.clone();
2828
2829        cx.spawn_in(window, async move |_, cx| {
2830            let repo = repo?;
2831            let remotes = repo
2832                .update(cx, |repo, _| repo.get_remotes(None, false))
2833                .await
2834                .ok()?
2835                .log_err()?;
2836
2837            let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
2838            if remotes.len() > 1 {
2839                remotes.push(FetchOptions::All);
2840            }
2841            let selection = cx
2842                .update(|window, cx| {
2843                    picker_prompt::prompt(
2844                        "Pick which remote to fetch",
2845                        remotes.iter().map(|r| r.name()).collect(),
2846                        workspace,
2847                        window,
2848                        cx,
2849                    )
2850                })
2851                .ok()?
2852                .await?;
2853            remotes.get(selection).cloned()
2854        })
2855    }
2856
2857    pub(crate) fn fetch(
2858        &mut self,
2859        is_fetch_all: bool,
2860        window: &mut Window,
2861        cx: &mut Context<Self>,
2862    ) {
2863        if !self.can_push_and_pull(cx) {
2864            return;
2865        }
2866
2867        let Some(repo) = self.active_repository.clone() else {
2868            return;
2869        };
2870        telemetry::event!("Git Fetched");
2871        let askpass = self.askpass_delegate("git fetch", window, cx);
2872        let this = cx.weak_entity();
2873
2874        let fetch_options = if is_fetch_all {
2875            Task::ready(Some(FetchOptions::All))
2876        } else {
2877            self.get_fetch_options(window, cx)
2878        };
2879
2880        window
2881            .spawn(cx, async move |cx| {
2882                let Some(fetch_options) = fetch_options.await else {
2883                    return Ok(());
2884                };
2885                let fetch = repo.update(cx, |repo, cx| {
2886                    repo.fetch(fetch_options.clone(), askpass, cx)
2887                });
2888
2889                let remote_message = fetch.await?;
2890                this.update(cx, |this, cx| {
2891                    let action = match fetch_options {
2892                        FetchOptions::All => RemoteAction::Fetch(None),
2893                        FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2894                    };
2895                    match remote_message {
2896                        Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2897                        Err(e) => {
2898                            log::error!("Error while fetching {:?}", e);
2899                            this.show_error_toast(action.name(), e, cx)
2900                        }
2901                    }
2902
2903                    anyhow::Ok(())
2904                })
2905                .ok();
2906                anyhow::Ok(())
2907            })
2908            .detach_and_log_err(cx);
2909    }
2910
2911    pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
2912        let workspace = self.workspace.clone();
2913
2914        crate::clone::clone_and_open(
2915            repo.into(),
2916            workspace,
2917            window,
2918            cx,
2919            Arc::new(|_workspace: &mut workspace::Workspace, _window, _cx| {}),
2920        );
2921    }
2922
2923    pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2924        let worktrees = self
2925            .project
2926            .read(cx)
2927            .visible_worktrees(cx)
2928            .collect::<Vec<_>>();
2929
2930        let worktree = if worktrees.len() == 1 {
2931            Task::ready(Some(worktrees.first().unwrap().clone()))
2932        } else if worktrees.is_empty() {
2933            let result = window.prompt(
2934                PromptLevel::Warning,
2935                "Unable to initialize a git repository",
2936                Some("Open a directory first"),
2937                &["Ok"],
2938                cx,
2939            );
2940            cx.background_executor()
2941                .spawn(async move {
2942                    result.await.ok();
2943                })
2944                .detach();
2945            return;
2946        } else {
2947            let worktree_directories = worktrees
2948                .iter()
2949                .map(|worktree| worktree.read(cx).abs_path())
2950                .map(|worktree_abs_path| {
2951                    if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2952                        Path::new("~")
2953                            .join(path)
2954                            .to_string_lossy()
2955                            .to_string()
2956                            .into()
2957                    } else {
2958                        worktree_abs_path.to_string_lossy().into_owned().into()
2959                    }
2960                })
2961                .collect_vec();
2962            let prompt = picker_prompt::prompt(
2963                "Where would you like to initialize this git repository?",
2964                worktree_directories,
2965                self.workspace.clone(),
2966                window,
2967                cx,
2968            );
2969
2970            cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2971        };
2972
2973        cx.spawn_in(window, async move |this, cx| {
2974            let worktree = match worktree.await {
2975                Some(worktree) => worktree,
2976                None => {
2977                    return;
2978                }
2979            };
2980
2981            let Ok(result) = this.update(cx, |this, cx| {
2982                let fallback_branch_name = GitPanelSettings::get_global(cx)
2983                    .fallback_branch_name
2984                    .clone();
2985                this.project.read(cx).git_init(
2986                    worktree.read(cx).abs_path(),
2987                    fallback_branch_name,
2988                    cx,
2989                )
2990            }) else {
2991                return;
2992            };
2993
2994            let result = result.await;
2995
2996            this.update_in(cx, |this, _, cx| match result {
2997                Ok(()) => {}
2998                Err(e) => this.show_error_toast("init", e, cx),
2999            })
3000            .ok();
3001        })
3002        .detach();
3003    }
3004
3005    pub(crate) fn pull(&mut self, rebase: bool, window: &mut Window, cx: &mut Context<Self>) {
3006        if !self.can_push_and_pull(cx) {
3007            return;
3008        }
3009        let Some(repo) = self.active_repository.clone() else {
3010            return;
3011        };
3012        let Some(branch) = repo.read(cx).branch.as_ref() else {
3013            return;
3014        };
3015        telemetry::event!("Git Pulled");
3016        let branch = branch.clone();
3017        let remote = self.get_remote(false, false, window, cx);
3018        cx.spawn_in(window, async move |this, cx| {
3019            let remote = match remote.await {
3020                Ok(Some(remote)) => remote,
3021                Ok(None) => {
3022                    return Ok(());
3023                }
3024                Err(e) => {
3025                    log::error!("Failed to get current remote: {}", e);
3026                    this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
3027                        .ok();
3028                    return Ok(());
3029                }
3030            };
3031
3032            let askpass = this.update_in(cx, |this, window, cx| {
3033                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
3034            })?;
3035
3036            let branch_name = branch
3037                .upstream
3038                .is_none()
3039                .then(|| branch.name().to_owned().into());
3040
3041            let pull = repo.update(cx, |repo, cx| {
3042                repo.pull(branch_name, remote.name.clone(), rebase, askpass, cx)
3043            });
3044
3045            let remote_message = pull.await?;
3046
3047            let action = RemoteAction::Pull(remote);
3048            this.update(cx, |this, cx| match remote_message {
3049                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3050                Err(e) => {
3051                    log::error!("Error while pulling {:?}", e);
3052                    this.show_error_toast(action.name(), e, cx)
3053                }
3054            })
3055            .ok();
3056
3057            anyhow::Ok(())
3058        })
3059        .detach_and_log_err(cx);
3060    }
3061
3062    pub(crate) fn push(
3063        &mut self,
3064        force_push: bool,
3065        select_remote: bool,
3066        window: &mut Window,
3067        cx: &mut Context<Self>,
3068    ) {
3069        if !self.can_push_and_pull(cx) {
3070            return;
3071        }
3072        let Some(repo) = self.active_repository.clone() else {
3073            return;
3074        };
3075        let Some(branch) = repo.read(cx).branch.as_ref() else {
3076            return;
3077        };
3078        telemetry::event!("Git Pushed");
3079        let branch = branch.clone();
3080
3081        let options = if force_push {
3082            Some(PushOptions::Force)
3083        } else {
3084            match branch.upstream {
3085                Some(Upstream {
3086                    tracking: UpstreamTracking::Gone,
3087                    ..
3088                })
3089                | None => Some(PushOptions::SetUpstream),
3090                _ => None,
3091            }
3092        };
3093        let remote = self.get_remote(select_remote, true, window, cx);
3094
3095        cx.spawn_in(window, async move |this, cx| {
3096            let remote = match remote.await {
3097                Ok(Some(remote)) => remote,
3098                Ok(None) => {
3099                    return Ok(());
3100                }
3101                Err(e) => {
3102                    log::error!("Failed to get current remote: {}", e);
3103                    this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
3104                        .ok();
3105                    return Ok(());
3106                }
3107            };
3108
3109            let askpass_delegate = this.update_in(cx, |this, window, cx| {
3110                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
3111            })?;
3112
3113            let push = repo.update(cx, |repo, cx| {
3114                repo.push(
3115                    branch.name().to_owned().into(),
3116                    branch
3117                        .upstream
3118                        .as_ref()
3119                        .filter(|u| matches!(u.tracking, UpstreamTracking::Tracked(_)))
3120                        .and_then(|u| u.branch_name())
3121                        .unwrap_or_else(|| branch.name())
3122                        .to_owned()
3123                        .into(),
3124                    remote.name.clone(),
3125                    options,
3126                    askpass_delegate,
3127                    cx,
3128                )
3129            });
3130
3131            let remote_output = push.await?;
3132
3133            let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
3134            this.update(cx, |this, cx| match remote_output {
3135                Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3136                Err(e) => {
3137                    log::error!("Error while pushing {:?}", e);
3138                    this.show_error_toast(action.name(), e, cx)
3139                }
3140            })?;
3141
3142            anyhow::Ok(())
3143        })
3144        .detach_and_log_err(cx);
3145    }
3146
3147    pub fn create_pull_request(&self, window: &mut Window, cx: &mut Context<Self>) {
3148        let result = (|| -> anyhow::Result<()> {
3149            let repo = self
3150                .active_repository
3151                .clone()
3152                .ok_or_else(|| anyhow::anyhow!("No active repository"))?;
3153
3154            let (branch, remote_origin, remote_upstream) = {
3155                let repository = repo.read(cx);
3156                (
3157                    repository.branch.clone(),
3158                    repository.remote_origin_url.clone(),
3159                    repository.remote_upstream_url.clone(),
3160                )
3161            };
3162
3163            let branch = branch.ok_or_else(|| anyhow::anyhow!("No active branch"))?;
3164            let source_branch = branch
3165                .upstream
3166                .as_ref()
3167                .filter(|upstream| matches!(upstream.tracking, UpstreamTracking::Tracked(_)))
3168                .and_then(|upstream| upstream.branch_name())
3169                .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3170            let source_branch = source_branch.to_string();
3171
3172            let remote_url = branch
3173                .upstream
3174                .as_ref()
3175                .and_then(|upstream| match upstream.remote_name() {
3176                    Some("upstream") => remote_upstream.as_deref(),
3177                    Some(_) => remote_origin.as_deref(),
3178                    None => None,
3179                })
3180                .or(remote_origin.as_deref())
3181                .or(remote_upstream.as_deref())
3182                .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3183            let remote_url = remote_url.to_string();
3184
3185            let provider_registry = GitHostingProviderRegistry::global(cx);
3186            let Some((provider, parsed_remote)) =
3187                git::parse_git_remote_url(provider_registry, &remote_url)
3188            else {
3189                return Err(anyhow::anyhow!("Unsupported remote URL: {}", remote_url));
3190            };
3191
3192            let Some(url) = provider.build_create_pull_request_url(&parsed_remote, &source_branch)
3193            else {
3194                return Err(anyhow::anyhow!("Unable to construct pull request URL"));
3195            };
3196
3197            cx.open_url(url.as_str());
3198            Ok(())
3199        })();
3200
3201        if let Err(err) = result {
3202            log::error!("Error while creating pull request {:?}", err);
3203            cx.defer_in(window, |panel, _window, cx| {
3204                panel.show_error_toast("create pull request", err, cx);
3205            });
3206        }
3207    }
3208
3209    fn askpass_delegate(
3210        &self,
3211        operation: impl Into<SharedString>,
3212        window: &mut Window,
3213        cx: &mut Context<Self>,
3214    ) -> AskPassDelegate {
3215        let workspace = self.workspace.clone();
3216        let operation = operation.into();
3217        let window = window.window_handle();
3218        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
3219            window
3220                .update(cx, |_, window, cx| {
3221                    workspace.update(cx, |workspace, cx| {
3222                        workspace.toggle_modal(window, cx, |window, cx| {
3223                            AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
3224                        });
3225                    })
3226                })
3227                .ok();
3228        })
3229    }
3230
3231    fn can_push_and_pull(&self, cx: &App) -> bool {
3232        !self.project.read(cx).is_via_collab()
3233    }
3234
3235    fn get_remote(
3236        &mut self,
3237        always_select: bool,
3238        is_push: bool,
3239        window: &mut Window,
3240        cx: &mut Context<Self>,
3241    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
3242        let repo = self.active_repository.clone();
3243        let workspace = self.workspace.clone();
3244        let mut cx = window.to_async(cx);
3245
3246        async move {
3247            let repo = repo.context("No active repository")?;
3248            let current_remotes: Vec<Remote> = repo
3249                .update(&mut cx, |repo, _| {
3250                    let current_branch = if always_select {
3251                        None
3252                    } else {
3253                        let current_branch = repo.branch.as_ref().context("No active branch")?;
3254                        Some(current_branch.name().to_string())
3255                    };
3256                    anyhow::Ok(repo.get_remotes(current_branch, is_push))
3257                })?
3258                .await??;
3259
3260            let current_remotes: Vec<_> = current_remotes
3261                .into_iter()
3262                .map(|remotes| remotes.name)
3263                .collect();
3264            let selection = cx
3265                .update(|window, cx| {
3266                    picker_prompt::prompt(
3267                        "Pick which remote to push to",
3268                        current_remotes.clone(),
3269                        workspace,
3270                        window,
3271                        cx,
3272                    )
3273                })?
3274                .await;
3275
3276            Ok(selection.map(|selection| Remote {
3277                name: current_remotes[selection].clone(),
3278            }))
3279        }
3280    }
3281
3282    pub fn load_local_committer(&mut self, cx: &Context<Self>) {
3283        if self.local_committer_task.is_none() {
3284            self.local_committer_task = Some(cx.spawn(async move |this, cx| {
3285                let committer = get_git_committer(cx).await;
3286                this.update(cx, |this, cx| {
3287                    this.local_committer = Some(committer);
3288                    cx.notify()
3289                })
3290                .ok();
3291            }));
3292        }
3293    }
3294
3295    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
3296        let mut new_co_authors = Vec::new();
3297        let project = self.project.read(cx);
3298
3299        let Some(room) =
3300            call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
3301        else {
3302            return Vec::default();
3303        };
3304
3305        let room = room.read(cx);
3306
3307        for (peer_id, collaborator) in project.collaborators() {
3308            if collaborator.is_host {
3309                continue;
3310            }
3311
3312            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
3313                continue;
3314            };
3315            if !participant.can_write() {
3316                continue;
3317            }
3318            if let Some(email) = &collaborator.committer_email {
3319                let name = collaborator
3320                    .committer_name
3321                    .clone()
3322                    .or_else(|| participant.user.name.clone())
3323                    .unwrap_or_else(|| participant.user.github_login.clone().to_string());
3324                new_co_authors.push((name.clone(), email.clone()))
3325            }
3326        }
3327        if !project.is_local()
3328            && !project.is_read_only(cx)
3329            && let Some(local_committer) = self.local_committer(room, cx)
3330        {
3331            new_co_authors.push(local_committer);
3332        }
3333        new_co_authors
3334    }
3335
3336    fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
3337        let user = room.local_participant_user(cx)?;
3338        let committer = self.local_committer.as_ref()?;
3339        let email = committer.email.clone()?;
3340        let name = committer
3341            .name
3342            .clone()
3343            .or_else(|| user.name.clone())
3344            .unwrap_or_else(|| user.github_login.clone().to_string());
3345        Some((name, email))
3346    }
3347
3348    fn toggle_fill_co_authors(
3349        &mut self,
3350        _: &ToggleFillCoAuthors,
3351        _: &mut Window,
3352        cx: &mut Context<Self>,
3353    ) {
3354        self.add_coauthors = !self.add_coauthors;
3355        cx.notify();
3356    }
3357
3358    fn toggle_sort_by_path(
3359        &mut self,
3360        _: &ToggleSortByPath,
3361        _: &mut Window,
3362        cx: &mut Context<Self>,
3363    ) {
3364        let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
3365        if let Some(workspace) = self.workspace.upgrade() {
3366            let workspace = workspace.read(cx);
3367            let fs = workspace.app_state().fs.clone();
3368            cx.update_global::<SettingsStore, _>(|store, _cx| {
3369                store.update_settings_file(fs, move |settings, _cx| {
3370                    settings.git_panel.get_or_insert_default().sort_by_path =
3371                        Some(!current_setting);
3372                });
3373            });
3374        }
3375    }
3376
3377    fn toggle_tree_view(&mut self, _: &ToggleTreeView, _: &mut Window, cx: &mut Context<Self>) {
3378        let current_setting = GitPanelSettings::get_global(cx).tree_view;
3379        if let Some(workspace) = self.workspace.upgrade() {
3380            let workspace = workspace.read(cx);
3381            let fs = workspace.app_state().fs.clone();
3382            cx.update_global::<SettingsStore, _>(|store, _cx| {
3383                store.update_settings_file(fs, move |settings, _cx| {
3384                    settings.git_panel.get_or_insert_default().tree_view = Some(!current_setting);
3385                });
3386            })
3387        }
3388    }
3389
3390    fn toggle_directory(&mut self, key: &TreeKey, window: &mut Window, cx: &mut Context<Self>) {
3391        if let Some(state) = self.view_mode.tree_state_mut() {
3392            let expanded = state.expanded_dirs.entry(key.clone()).or_insert(true);
3393            *expanded = !*expanded;
3394            self.update_visible_entries(window, cx);
3395        } else {
3396            util::debug_panic!("Attempted to toggle directory in flat Git Panel state");
3397        }
3398    }
3399
3400    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
3401        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
3402
3403        let existing_text = message.to_ascii_lowercase();
3404        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
3405        let mut ends_with_co_authors = false;
3406        let existing_co_authors = existing_text
3407            .lines()
3408            .filter_map(|line| {
3409                let line = line.trim();
3410                if line.starts_with(&lowercase_co_author_prefix) {
3411                    ends_with_co_authors = true;
3412                    Some(line)
3413                } else {
3414                    ends_with_co_authors = false;
3415                    None
3416                }
3417            })
3418            .collect::<HashSet<_>>();
3419
3420        let new_co_authors = self
3421            .potential_co_authors(cx)
3422            .into_iter()
3423            .filter(|(_, email)| {
3424                !existing_co_authors
3425                    .iter()
3426                    .any(|existing| existing.contains(email.as_str()))
3427            })
3428            .collect::<Vec<_>>();
3429
3430        if new_co_authors.is_empty() {
3431            return;
3432        }
3433
3434        if !ends_with_co_authors {
3435            message.push('\n');
3436        }
3437        for (name, email) in new_co_authors {
3438            message.push('\n');
3439            message.push_str(CO_AUTHOR_PREFIX);
3440            message.push_str(&name);
3441            message.push_str(" <");
3442            message.push_str(&email);
3443            message.push('>');
3444        }
3445        message.push('\n');
3446    }
3447
3448    fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3449        let handle = cx.entity().downgrade();
3450        self.reopen_commit_buffer(window, cx);
3451        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
3452            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
3453            if let Some(git_panel) = handle.upgrade() {
3454                git_panel
3455                    .update_in(cx, |git_panel, window, cx| {
3456                        git_panel.update_visible_entries(window, cx);
3457                    })
3458                    .ok();
3459            }
3460        });
3461    }
3462
3463    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3464        let Some(active_repo) = self.active_repository.as_ref() else {
3465            return;
3466        };
3467        let load_buffer = active_repo.update(cx, |active_repo, cx| {
3468            let project = self.project.read(cx);
3469            active_repo.open_commit_buffer(
3470                Some(project.languages().clone()),
3471                project.buffer_store().clone(),
3472                cx,
3473            )
3474        });
3475
3476        cx.spawn_in(window, async move |git_panel, cx| {
3477            let buffer = load_buffer.await?;
3478            git_panel.update_in(cx, |git_panel, window, cx| {
3479                if git_panel
3480                    .commit_editor
3481                    .read(cx)
3482                    .buffer()
3483                    .read(cx)
3484                    .as_singleton()
3485                    .as_ref()
3486                    != Some(&buffer)
3487                {
3488                    git_panel.commit_editor = cx.new(|cx| {
3489                        commit_message_editor(
3490                            buffer,
3491                            git_panel.suggest_commit_message(cx).map(SharedString::from),
3492                            git_panel.project.clone(),
3493                            true,
3494                            window,
3495                            cx,
3496                        )
3497                    });
3498                }
3499            })
3500        })
3501        .detach_and_log_err(cx);
3502    }
3503
3504    fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3505        let path_style = self.project.read(cx).path_style(cx);
3506        let bulk_staging = self.bulk_staging.take();
3507        let last_staged_path_prev_index = bulk_staging
3508            .as_ref()
3509            .and_then(|op| self.entry_by_path(&op.anchor));
3510
3511        self.active_repository = self.project.read(cx).active_repository(cx);
3512        self.entries.clear();
3513        self.entries_indices.clear();
3514        self.single_staged_entry.take();
3515        self.single_tracked_entry.take();
3516        self.conflicted_count = 0;
3517        self.conflicted_staged_count = 0;
3518        self.changes_count = 0;
3519        self.new_count = 0;
3520        self.tracked_count = 0;
3521        self.new_staged_count = 0;
3522        self.tracked_staged_count = 0;
3523        self.entry_count = 0;
3524        self.max_width_item_index = None;
3525
3526        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
3527        let is_tree_view = matches!(self.view_mode, GitPanelViewMode::Tree(_));
3528        let group_by_status = is_tree_view || !sort_by_path;
3529
3530        let mut changed_entries = Vec::new();
3531        let mut new_entries = Vec::new();
3532        let mut conflict_entries = Vec::new();
3533        let mut single_staged_entry = None;
3534        let mut staged_count = 0;
3535        let mut seen_directories = HashSet::default();
3536        let mut max_width_estimate = 0usize;
3537        let mut max_width_item_index = None;
3538
3539        let Some(repo) = self.active_repository.as_ref() else {
3540            // Just clear entries if no repository is active.
3541            cx.notify();
3542            return;
3543        };
3544
3545        let repo = repo.read(cx);
3546
3547        self.stash_entries = repo.cached_stash();
3548
3549        for entry in repo.cached_status() {
3550            self.changes_count += 1;
3551            let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
3552            let is_new = entry.status.is_created();
3553            let staging = entry.status.staging();
3554
3555            if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
3556                && pending
3557                    .ops
3558                    .iter()
3559                    .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
3560            {
3561                continue;
3562            }
3563
3564            let entry = GitStatusEntry {
3565                repo_path: entry.repo_path.clone(),
3566                status: entry.status,
3567                staging,
3568                diff_stat: entry.diff_stat,
3569            };
3570
3571            if staging.has_staged() {
3572                staged_count += 1;
3573                single_staged_entry = Some(entry.clone());
3574            }
3575
3576            if group_by_status && is_conflict {
3577                conflict_entries.push(entry);
3578            } else if group_by_status && is_new {
3579                new_entries.push(entry);
3580            } else {
3581                changed_entries.push(entry);
3582            }
3583        }
3584
3585        if conflict_entries.is_empty() {
3586            if staged_count == 1
3587                && let Some(entry) = single_staged_entry.as_ref()
3588            {
3589                if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
3590                    if ops.staged() {
3591                        self.single_staged_entry = single_staged_entry;
3592                    }
3593                } else {
3594                    self.single_staged_entry = single_staged_entry;
3595                }
3596            } else if repo.pending_ops_summary().item_summary.staging_count == 1
3597                && let Some(ops) = repo.pending_ops().find(|ops| ops.staging())
3598            {
3599                self.single_staged_entry =
3600                    repo.status_for_path(&ops.repo_path)
3601                        .map(|status| GitStatusEntry {
3602                            repo_path: ops.repo_path.clone(),
3603                            status: status.status,
3604                            staging: StageStatus::Staged,
3605                            diff_stat: status.diff_stat,
3606                        });
3607            }
3608        }
3609
3610        if conflict_entries.is_empty() && changed_entries.len() == 1 {
3611            self.single_tracked_entry = changed_entries.first().cloned();
3612        }
3613
3614        let mut push_entry =
3615            |this: &mut Self,
3616             entry: GitListEntry,
3617             is_visible: bool,
3618             logical_indices: Option<&mut Vec<usize>>| {
3619                if let Some(estimate) =
3620                    this.width_estimate_for_list_entry(is_tree_view, &entry, path_style)
3621                {
3622                    if estimate > max_width_estimate {
3623                        max_width_estimate = estimate;
3624                        max_width_item_index = Some(this.entries.len());
3625                    }
3626                }
3627
3628                if let Some(repo_path) = entry.status_entry().map(|status| status.repo_path.clone())
3629                {
3630                    this.entries_indices.insert(repo_path, this.entries.len());
3631                }
3632
3633                if let (Some(indices), true) = (logical_indices, is_visible) {
3634                    indices.push(this.entries.len());
3635                }
3636
3637                this.entries.push(entry);
3638            };
3639
3640        macro_rules! take_section_entries {
3641            () => {
3642                [
3643                    (Section::Conflict, std::mem::take(&mut conflict_entries)),
3644                    (Section::Tracked, std::mem::take(&mut changed_entries)),
3645                    (Section::New, std::mem::take(&mut new_entries)),
3646                ]
3647            };
3648        }
3649
3650        match &mut self.view_mode {
3651            GitPanelViewMode::Tree(tree_state) => {
3652                tree_state.logical_indices.clear();
3653                tree_state.directory_descendants.clear();
3654
3655                // This is just to get around the borrow checker
3656                // because push_entry mutably borrows self
3657                let mut tree_state = std::mem::take(tree_state);
3658
3659                for (section, entries) in take_section_entries!() {
3660                    if entries.is_empty() {
3661                        continue;
3662                    }
3663
3664                    push_entry(
3665                        self,
3666                        GitListEntry::Header(GitHeaderEntry { header: section }),
3667                        true,
3668                        Some(&mut tree_state.logical_indices),
3669                    );
3670
3671                    for (entry, is_visible) in
3672                        tree_state.build_tree_entries(section, entries, &mut seen_directories)
3673                    {
3674                        push_entry(
3675                            self,
3676                            entry,
3677                            is_visible,
3678                            Some(&mut tree_state.logical_indices),
3679                        );
3680                    }
3681                }
3682
3683                tree_state
3684                    .expanded_dirs
3685                    .retain(|key, _| seen_directories.contains(key));
3686                self.view_mode = GitPanelViewMode::Tree(tree_state);
3687            }
3688            GitPanelViewMode::Flat => {
3689                for (section, entries) in take_section_entries!() {
3690                    if entries.is_empty() {
3691                        continue;
3692                    }
3693
3694                    if section != Section::Tracked || !sort_by_path {
3695                        push_entry(
3696                            self,
3697                            GitListEntry::Header(GitHeaderEntry { header: section }),
3698                            true,
3699                            None,
3700                        );
3701                    }
3702
3703                    for entry in entries {
3704                        push_entry(self, GitListEntry::Status(entry), true, None);
3705                    }
3706                }
3707            }
3708        }
3709
3710        self.max_width_item_index = max_width_item_index;
3711
3712        self.update_counts(repo);
3713
3714        let bulk_staging_anchor_new_index = bulk_staging
3715            .as_ref()
3716            .filter(|op| op.repo_id == repo.id)
3717            .and_then(|op| self.entry_by_path(&op.anchor));
3718        if bulk_staging_anchor_new_index == last_staged_path_prev_index
3719            && let Some(index) = bulk_staging_anchor_new_index
3720            && let Some(entry) = self.entries.get(index)
3721            && let Some(entry) = entry.status_entry()
3722            && GitPanel::stage_status_for_entry(entry, &repo)
3723                .as_bool()
3724                .unwrap_or(false)
3725        {
3726            self.bulk_staging = bulk_staging;
3727        }
3728
3729        self.select_first_entry_if_none(window, cx);
3730
3731        let suggested_commit_message = self.suggest_commit_message(cx);
3732        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
3733
3734        self.commit_editor.update(cx, |editor, cx| {
3735            editor.set_placeholder_text(&placeholder_text, window, cx)
3736        });
3737
3738        cx.notify();
3739    }
3740
3741    fn header_state(&self, header_type: Section) -> ToggleState {
3742        let (staged_count, count) = match header_type {
3743            Section::New => (self.new_staged_count, self.new_count),
3744            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
3745            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
3746        };
3747        if staged_count == 0 {
3748            ToggleState::Unselected
3749        } else if count == staged_count {
3750            ToggleState::Selected
3751        } else {
3752            ToggleState::Indeterminate
3753        }
3754    }
3755
3756    fn update_counts(&mut self, repo: &Repository) {
3757        self.show_placeholders = false;
3758        self.conflicted_count = 0;
3759        self.conflicted_staged_count = 0;
3760        self.new_count = 0;
3761        self.tracked_count = 0;
3762        self.new_staged_count = 0;
3763        self.tracked_staged_count = 0;
3764        self.entry_count = 0;
3765
3766        for status_entry in self.entries.iter().filter_map(|entry| entry.status_entry()) {
3767            self.entry_count += 1;
3768            let is_staging_or_staged = GitPanel::stage_status_for_entry(status_entry, repo)
3769                .as_bool()
3770                .unwrap_or(true);
3771
3772            if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
3773                self.conflicted_count += 1;
3774                if is_staging_or_staged {
3775                    self.conflicted_staged_count += 1;
3776                }
3777            } else if status_entry.status.is_created() {
3778                self.new_count += 1;
3779                if is_staging_or_staged {
3780                    self.new_staged_count += 1;
3781                }
3782            } else {
3783                self.tracked_count += 1;
3784                if is_staging_or_staged {
3785                    self.tracked_staged_count += 1;
3786                }
3787            }
3788        }
3789    }
3790
3791    pub(crate) fn has_staged_changes(&self) -> bool {
3792        self.tracked_staged_count > 0
3793            || self.new_staged_count > 0
3794            || self.conflicted_staged_count > 0
3795    }
3796
3797    pub(crate) fn has_unstaged_changes(&self) -> bool {
3798        self.tracked_count > self.tracked_staged_count
3799            || self.new_count > self.new_staged_count
3800            || self.conflicted_count > self.conflicted_staged_count
3801    }
3802
3803    fn has_tracked_changes(&self) -> bool {
3804        self.tracked_count > 0
3805    }
3806
3807    pub fn has_unstaged_conflicts(&self) -> bool {
3808        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
3809    }
3810
3811    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
3812        let Some(workspace) = self.workspace.upgrade() else {
3813            return;
3814        };
3815        show_error_toast(workspace, action, e, cx)
3816    }
3817
3818    fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3819    where
3820        E: std::fmt::Debug + std::fmt::Display,
3821    {
3822        if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3823            let _ = workspace.update(cx, |workspace, cx| {
3824                struct CommitMessageError;
3825                let notification_id = NotificationId::unique::<CommitMessageError>();
3826                workspace.show_notification(notification_id, cx, |cx| {
3827                    cx.new(|cx| {
3828                        ErrorMessagePrompt::new(
3829                            format!("Failed to generate commit message: {err}"),
3830                            cx,
3831                        )
3832                    })
3833                });
3834            });
3835        }
3836    }
3837
3838    fn show_remote_output(
3839        &mut self,
3840        action: RemoteAction,
3841        info: RemoteCommandOutput,
3842        cx: &mut Context<Self>,
3843    ) {
3844        let Some(workspace) = self.workspace.upgrade() else {
3845            return;
3846        };
3847
3848        workspace.update(cx, |workspace, cx| {
3849            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3850            let workspace_weak = cx.weak_entity();
3851            let operation = action.name();
3852
3853            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3854                use remote_output::SuccessStyle::*;
3855                match style {
3856                    Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3857                    ToastWithLog { output } => this
3858                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3859                        .action("View Log", move |window, cx| {
3860                            let output = output.clone();
3861                            let output =
3862                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3863                            workspace_weak
3864                                .update(cx, move |workspace, cx| {
3865                                    open_output(operation, workspace, &output, window, cx)
3866                                })
3867                                .ok();
3868                        }),
3869                    PushPrLink { text, link } => this
3870                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3871                        .action(text, move |_, cx| cx.open_url(&link)),
3872                }
3873                .dismiss_button(true)
3874            });
3875            workspace.toggle_status_toast(status_toast, cx)
3876        });
3877    }
3878
3879    pub fn can_commit(&self) -> bool {
3880        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3881    }
3882
3883    pub fn can_stage_all(&self) -> bool {
3884        self.has_unstaged_changes()
3885    }
3886
3887    pub fn can_unstage_all(&self) -> bool {
3888        self.has_staged_changes()
3889    }
3890
3891    /// Computes tree indentation depths for visible entries in the given range.
3892    /// Used by indent guides to render vertical connector lines in tree view.
3893    fn compute_visible_depths(&self, range: Range<usize>) -> SmallVec<[usize; 64]> {
3894        let GitPanelViewMode::Tree(state) = &self.view_mode else {
3895            return SmallVec::new();
3896        };
3897
3898        range
3899            .map(|ix| {
3900                state
3901                    .logical_indices
3902                    .get(ix)
3903                    .and_then(|&entry_ix| self.entries.get(entry_ix))
3904                    .map_or(0, |entry| entry.depth())
3905            })
3906            .collect()
3907    }
3908
3909    fn status_width_estimate(
3910        tree_view: bool,
3911        entry: &GitStatusEntry,
3912        path_style: PathStyle,
3913        depth: usize,
3914    ) -> usize {
3915        if tree_view {
3916            Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3917        } else {
3918            Self::item_width_estimate(
3919                entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3920                entry.display_name(path_style).len(),
3921                0,
3922            )
3923        }
3924    }
3925
3926    fn width_estimate_for_list_entry(
3927        &self,
3928        tree_view: bool,
3929        entry: &GitListEntry,
3930        path_style: PathStyle,
3931    ) -> Option<usize> {
3932        match entry {
3933            GitListEntry::Status(status) => Some(Self::status_width_estimate(
3934                tree_view, status, path_style, 0,
3935            )),
3936            GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3937                tree_view,
3938                &status.entry,
3939                path_style,
3940                status.depth,
3941            )),
3942            GitListEntry::Directory(dir) => {
3943                Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
3944            }
3945            GitListEntry::Header(_) => None,
3946        }
3947    }
3948
3949    fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
3950        path + file_name + depth * 2
3951    }
3952
3953    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3954        let focus_handle = self.focus_handle.clone();
3955        let has_tracked_changes = self.has_tracked_changes();
3956        let has_staged_changes = self.has_staged_changes();
3957        let has_unstaged_changes = self.has_unstaged_changes();
3958        let has_new_changes = self.new_count > 0;
3959        let has_stash_items = self.stash_entries.entries.len() > 0;
3960
3961        PopoverMenu::new(id.into())
3962            .trigger(
3963                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3964                    .icon_size(IconSize::Small)
3965                    .icon_color(Color::Muted),
3966            )
3967            .menu(move |window, cx| {
3968                Some(git_panel_context_menu(
3969                    focus_handle.clone(),
3970                    GitMenuState {
3971                        has_tracked_changes,
3972                        has_staged_changes,
3973                        has_unstaged_changes,
3974                        has_new_changes,
3975                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3976                        has_stash_items,
3977                        tree_view: GitPanelSettings::get_global(cx).tree_view,
3978                    },
3979                    window,
3980                    cx,
3981                ))
3982            })
3983            .anchor(Corner::TopRight)
3984    }
3985
3986    pub(crate) fn render_generate_commit_message_button(
3987        &self,
3988        cx: &Context<Self>,
3989    ) -> Option<AnyElement> {
3990        if !agent_settings::AgentSettings::get_global(cx).enabled(cx) {
3991            return None;
3992        }
3993
3994        if self.generate_commit_message_task.is_some() {
3995            return Some(
3996                h_flex()
3997                    .gap_1()
3998                    .child(
3999                        Icon::new(IconName::ArrowCircle)
4000                            .size(IconSize::XSmall)
4001                            .color(Color::Info)
4002                            .with_rotate_animation(2),
4003                    )
4004                    .child(
4005                        Label::new("Generating Commit…")
4006                            .size(LabelSize::Small)
4007                            .color(Color::Muted),
4008                    )
4009                    .into_any_element(),
4010            );
4011        }
4012
4013        let model_registry = LanguageModelRegistry::read_global(cx);
4014        let has_commit_model_configuration_error = model_registry
4015            .configuration_error(model_registry.commit_message_model(), cx)
4016            .is_some();
4017        let can_commit = self.can_commit();
4018
4019        let editor_focus_handle = self.commit_editor.focus_handle(cx);
4020
4021        Some(
4022            IconButton::new("generate-commit-message", IconName::AiEdit)
4023                .shape(ui::IconButtonShape::Square)
4024                .icon_color(if has_commit_model_configuration_error {
4025                    Color::Disabled
4026                } else {
4027                    Color::Muted
4028                })
4029                .tooltip(move |_window, cx| {
4030                    if !can_commit {
4031                        Tooltip::simple("No Changes to Commit", cx)
4032                    } else if has_commit_model_configuration_error {
4033                        Tooltip::simple("Configure an LLM provider to generate commit messages", cx)
4034                    } else {
4035                        Tooltip::for_action_in(
4036                            "Generate Commit Message",
4037                            &git::GenerateCommitMessage,
4038                            &editor_focus_handle,
4039                            cx,
4040                        )
4041                    }
4042                })
4043                .disabled(!can_commit || has_commit_model_configuration_error)
4044                .on_click(cx.listener(move |this, _event, _window, cx| {
4045                    this.generate_commit_message(cx);
4046                }))
4047                .into_any_element(),
4048        )
4049    }
4050
4051    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
4052        let potential_co_authors = self.potential_co_authors(cx);
4053
4054        let (tooltip_label, icon) = if self.add_coauthors {
4055            ("Remove co-authored-by", IconName::Person)
4056        } else {
4057            ("Add co-authored-by", IconName::UserCheck)
4058        };
4059
4060        if potential_co_authors.is_empty() {
4061            None
4062        } else {
4063            Some(
4064                IconButton::new("co-authors", icon)
4065                    .shape(ui::IconButtonShape::Square)
4066                    .icon_color(Color::Disabled)
4067                    .selected_icon_color(Color::Selected)
4068                    .toggle_state(self.add_coauthors)
4069                    .tooltip(move |_, cx| {
4070                        let title = format!(
4071                            "{}:{}{}",
4072                            tooltip_label,
4073                            if potential_co_authors.len() == 1 {
4074                                ""
4075                            } else {
4076                                "\n"
4077                            },
4078                            potential_co_authors
4079                                .iter()
4080                                .map(|(name, email)| format!(" {} <{}>", name, email))
4081                                .join("\n")
4082                        );
4083                        Tooltip::simple(title, cx)
4084                    })
4085                    .on_click(cx.listener(|this, _, _, cx| {
4086                        this.add_coauthors = !this.add_coauthors;
4087                        cx.notify();
4088                    }))
4089                    .into_any_element(),
4090            )
4091        }
4092    }
4093
4094    fn render_git_commit_menu(
4095        &self,
4096        id: impl Into<ElementId>,
4097        keybinding_target: Option<FocusHandle>,
4098        cx: &mut Context<Self>,
4099    ) -> impl IntoElement {
4100        PopoverMenu::new(id.into())
4101            .trigger(
4102                ui::ButtonLike::new_rounded_right("commit-split-button-right")
4103                    .layer(ui::ElevationIndex::ModalSurface)
4104                    .size(ButtonSize::None)
4105                    .child(
4106                        h_flex()
4107                            .px_1()
4108                            .h_full()
4109                            .justify_center()
4110                            .border_l_1()
4111                            .border_color(cx.theme().colors().border)
4112                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
4113                    ),
4114            )
4115            .menu({
4116                let git_panel = cx.entity();
4117                let has_previous_commit = self.head_commit(cx).is_some();
4118                let amend = self.amend_pending();
4119                let signoff = self.signoff_enabled;
4120
4121                move |window, cx| {
4122                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
4123                        context_menu
4124                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
4125                                el.context(keybinding_target)
4126                            })
4127                            .when(has_previous_commit, |this| {
4128                                this.toggleable_entry(
4129                                    "Amend",
4130                                    amend,
4131                                    IconPosition::Start,
4132                                    Some(Box::new(Amend)),
4133                                    {
4134                                        let git_panel = git_panel.downgrade();
4135                                        move |_, cx| {
4136                                            git_panel
4137                                                .update(cx, |git_panel, cx| {
4138                                                    git_panel.toggle_amend_pending(cx);
4139                                                })
4140                                                .ok();
4141                                        }
4142                                    },
4143                                )
4144                            })
4145                            .toggleable_entry(
4146                                "Signoff",
4147                                signoff,
4148                                IconPosition::Start,
4149                                Some(Box::new(Signoff)),
4150                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
4151                            )
4152                    }))
4153                }
4154            })
4155            .anchor(Corner::TopRight)
4156    }
4157
4158    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
4159        if self.has_unstaged_conflicts() {
4160            (false, "You must resolve conflicts before committing")
4161        } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
4162            (false, "No changes to commit")
4163        } else if self.pending_commit.is_some() {
4164            (false, "Commit in progress")
4165        } else if !self.has_commit_message(cx) {
4166            (false, "No commit message")
4167        } else if !self.has_write_access(cx) {
4168            (false, "You do not have write access to this project")
4169        } else {
4170            (true, self.commit_button_title())
4171        }
4172    }
4173
4174    pub fn commit_button_title(&self) -> &'static str {
4175        if self.amend_pending {
4176            if self.has_staged_changes() {
4177                "Amend"
4178            } else if self.has_tracked_changes() {
4179                "Amend Tracked"
4180            } else {
4181                "Amend"
4182            }
4183        } else if self.has_staged_changes() {
4184            "Commit"
4185        } else {
4186            "Commit Tracked"
4187        }
4188    }
4189
4190    fn expand_commit_editor(
4191        &mut self,
4192        _: &git::ExpandCommitEditor,
4193        window: &mut Window,
4194        cx: &mut Context<Self>,
4195    ) {
4196        let workspace = self.workspace.clone();
4197        window.defer(cx, move |window, cx| {
4198            workspace
4199                .update(cx, |workspace, cx| {
4200                    CommitModal::toggle(workspace, None, window, cx)
4201                })
4202                .ok();
4203        })
4204    }
4205
4206    fn render_panel_header(
4207        &self,
4208        window: &mut Window,
4209        cx: &mut Context<Self>,
4210    ) -> Option<impl IntoElement> {
4211        self.active_repository.as_ref()?;
4212
4213        let (text, action, stage, tooltip) =
4214            if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
4215                ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
4216            } else {
4217                ("Stage All", StageAll.boxed_clone(), true, "git add --all")
4218            };
4219
4220        let change_string = match self.changes_count {
4221            0 => "No Changes".to_string(),
4222            1 => "1 Change".to_string(),
4223            count => format!("{} Changes", count),
4224        };
4225
4226        Some(
4227            self.panel_header_container(window, cx)
4228                .px_2()
4229                .justify_between()
4230                .child(
4231                    panel_button(change_string)
4232                        .color(Color::Muted)
4233                        .tooltip(Tooltip::for_action_title_in(
4234                            "Open Diff",
4235                            &Diff,
4236                            &self.focus_handle,
4237                        ))
4238                        .on_click(|_, _, cx| {
4239                            cx.defer(|cx| {
4240                                cx.dispatch_action(&Diff);
4241                            })
4242                        }),
4243                )
4244                .child(
4245                    h_flex()
4246                        .gap_1()
4247                        .child(self.render_overflow_menu("overflow_menu"))
4248                        .child(
4249                            panel_filled_button(text)
4250                                .tooltip(Tooltip::for_action_title_in(
4251                                    tooltip,
4252                                    action.as_ref(),
4253                                    &self.focus_handle,
4254                                ))
4255                                .disabled(self.entry_count == 0)
4256                                .on_click({
4257                                    let git_panel = cx.weak_entity();
4258                                    move |_, _, cx| {
4259                                        git_panel
4260                                            .update(cx, |git_panel, cx| {
4261                                                git_panel.change_all_files_stage(stage, cx);
4262                                            })
4263                                            .ok();
4264                                    }
4265                                }),
4266                        ),
4267                ),
4268        )
4269    }
4270
4271    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4272        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
4273        if !self.can_push_and_pull(cx) {
4274            return None;
4275        }
4276        Some(
4277            h_flex()
4278                .gap_1()
4279                .flex_shrink_0()
4280                .when_some(branch, |this, branch| {
4281                    let focus_handle = Some(self.focus_handle(cx));
4282
4283                    this.children(render_remote_button(
4284                        "remote-button",
4285                        &branch,
4286                        focus_handle,
4287                        true,
4288                    ))
4289                })
4290                .into_any_element(),
4291        )
4292    }
4293
4294    pub fn render_footer(
4295        &self,
4296        window: &mut Window,
4297        cx: &mut Context<Self>,
4298    ) -> Option<impl IntoElement> {
4299        let active_repository = self.active_repository.clone()?;
4300        let panel_editor_style = panel_editor_style(true, window, cx);
4301        let enable_coauthors = self.render_co_authors(cx);
4302
4303        let editor_focus_handle = self.commit_editor.focus_handle(cx);
4304        let expand_tooltip_focus_handle = editor_focus_handle;
4305
4306        let branch = active_repository.read(cx).branch.clone();
4307        let head_commit = active_repository.read(cx).head_commit.clone();
4308
4309        let footer_size = px(32.);
4310        let gap = px(9.0);
4311        let max_height = panel_editor_style
4312            .text
4313            .line_height_in_pixels(window.rem_size())
4314            * MAX_PANEL_EDITOR_LINES
4315            + gap;
4316
4317        let git_panel = cx.entity();
4318        let display_name = SharedString::from(Arc::from(
4319            active_repository
4320                .read(cx)
4321                .display_name()
4322                .trim_end_matches("/"),
4323        ));
4324        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4325            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4326        });
4327
4328        let footer = v_flex()
4329            .child(PanelRepoFooter::new(
4330                display_name,
4331                branch,
4332                head_commit,
4333                Some(git_panel),
4334            ))
4335            .child(
4336                panel_editor_container(window, cx)
4337                    .id("commit-editor-container")
4338                    .relative()
4339                    .w_full()
4340                    .h(max_height + footer_size)
4341                    .border_t_1()
4342                    .border_color(cx.theme().colors().border)
4343                    .cursor_text()
4344                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4345                        window.focus(&this.commit_editor.focus_handle(cx), cx);
4346                    }))
4347                    .child(
4348                        h_flex()
4349                            .id("commit-footer")
4350                            .border_t_1()
4351                            .when(editor_is_long, |el| {
4352                                el.border_color(cx.theme().colors().border_variant)
4353                            })
4354                            .absolute()
4355                            .bottom_0()
4356                            .left_0()
4357                            .w_full()
4358                            .px_2()
4359                            .h(footer_size)
4360                            .flex_none()
4361                            .justify_between()
4362                            .child(
4363                                self.render_generate_commit_message_button(cx)
4364                                    .unwrap_or_else(|| div().into_any_element()),
4365                            )
4366                            .child(
4367                                h_flex()
4368                                    .gap_0p5()
4369                                    .children(enable_coauthors)
4370                                    .child(self.render_commit_button(cx)),
4371                            ),
4372                    )
4373                    .child(
4374                        div()
4375                            .pr_2p5()
4376                            .on_action(|&zed_actions::editor::MoveUp, _, cx| {
4377                                cx.stop_propagation();
4378                            })
4379                            .on_action(|&zed_actions::editor::MoveDown, _, cx| {
4380                                cx.stop_propagation();
4381                            })
4382                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4383                    )
4384                    .child(
4385                        h_flex()
4386                            .absolute()
4387                            .top_2()
4388                            .right_2()
4389                            .opacity(0.5)
4390                            .hover(|this| this.opacity(1.0))
4391                            .child(
4392                                panel_icon_button("expand-commit-editor", IconName::Maximize)
4393                                    .icon_size(IconSize::Small)
4394                                    .size(ui::ButtonSize::Default)
4395                                    .tooltip(move |_window, cx| {
4396                                        Tooltip::for_action_in(
4397                                            "Open Commit Modal",
4398                                            &git::ExpandCommitEditor,
4399                                            &expand_tooltip_focus_handle,
4400                                            cx,
4401                                        )
4402                                    })
4403                                    .on_click(cx.listener({
4404                                        move |_, _, window, cx| {
4405                                            window.dispatch_action(
4406                                                git::ExpandCommitEditor.boxed_clone(),
4407                                                cx,
4408                                            )
4409                                        }
4410                                    })),
4411                            ),
4412                    ),
4413            );
4414
4415        Some(footer)
4416    }
4417
4418    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4419        let (can_commit, tooltip) = self.configure_commit_button(cx);
4420        let title = self.commit_button_title();
4421        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4422        let amend = self.amend_pending();
4423        let signoff = self.signoff_enabled;
4424
4425        let label_color = if self.pending_commit.is_some() {
4426            Color::Disabled
4427        } else {
4428            Color::Default
4429        };
4430
4431        div()
4432            .id("commit-wrapper")
4433            .on_hover(cx.listener(move |this, hovered, _, cx| {
4434                this.show_placeholders =
4435                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4436                cx.notify()
4437            }))
4438            .child(SplitButton::new(
4439                ButtonLike::new_rounded_left(ElementId::Name(
4440                    format!("split-button-left-{}", title).into(),
4441                ))
4442                .layer(ElevationIndex::ModalSurface)
4443                .size(ButtonSize::Compact)
4444                .child(
4445                    Label::new(title)
4446                        .size(LabelSize::Small)
4447                        .color(label_color)
4448                        .mr_0p5(),
4449                )
4450                .on_click({
4451                    let git_panel = cx.weak_entity();
4452                    move |_, window, cx| {
4453                        telemetry::event!("Git Committed", source = "Git Panel");
4454                        git_panel
4455                            .update(cx, |git_panel, cx| {
4456                                git_panel.commit_changes(
4457                                    CommitOptions { amend, signoff },
4458                                    window,
4459                                    cx,
4460                                );
4461                            })
4462                            .ok();
4463                    }
4464                })
4465                .disabled(!can_commit || self.modal_open)
4466                .tooltip({
4467                    let handle = commit_tooltip_focus_handle.clone();
4468                    move |_window, cx| {
4469                        if can_commit {
4470                            Tooltip::with_meta_in(
4471                                tooltip,
4472                                Some(if amend { &git::Amend } else { &git::Commit }),
4473                                format!(
4474                                    "git commit{}{}",
4475                                    if amend { " --amend" } else { "" },
4476                                    if signoff { " --signoff" } else { "" }
4477                                ),
4478                                &handle.clone(),
4479                                cx,
4480                            )
4481                        } else {
4482                            Tooltip::simple(tooltip, cx)
4483                        }
4484                    }
4485                }),
4486                self.render_git_commit_menu(
4487                    ElementId::Name(format!("split-button-right-{}", title).into()),
4488                    Some(commit_tooltip_focus_handle),
4489                    cx,
4490                )
4491                .into_any_element(),
4492            ))
4493    }
4494
4495    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4496        h_flex()
4497            .py_1p5()
4498            .px_2()
4499            .gap_1p5()
4500            .justify_between()
4501            .border_t_1()
4502            .border_color(cx.theme().colors().border.opacity(0.8))
4503            .child(
4504                div()
4505                    .flex_grow()
4506                    .overflow_hidden()
4507                    .max_w(relative(0.85))
4508                    .child(
4509                        Label::new("This will update your most recent commit.")
4510                            .size(LabelSize::Small)
4511                            .truncate(),
4512                    ),
4513            )
4514            .child(
4515                panel_button("Cancel")
4516                    .size(ButtonSize::Default)
4517                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4518            )
4519    }
4520
4521    fn render_previous_commit(
4522        &self,
4523        _window: &mut Window,
4524        cx: &mut Context<Self>,
4525    ) -> Option<impl IntoElement> {
4526        let active_repository = self.active_repository.as_ref()?;
4527        let branch = active_repository.read(cx).branch.as_ref()?;
4528        let commit = branch.most_recent_commit.as_ref()?.clone();
4529        let workspace = self.workspace.clone();
4530        let this = cx.entity();
4531
4532        Some(
4533            h_flex()
4534                .p_1p5()
4535                .gap_1p5()
4536                .justify_between()
4537                .border_t_1()
4538                .border_color(cx.theme().colors().border.opacity(0.8))
4539                .child(
4540                    div()
4541                        .id("commit-msg-hover")
4542                        .cursor_pointer()
4543                        .px_1()
4544                        .rounded_sm()
4545                        .line_clamp(1)
4546                        .hover(|s| s.bg(cx.theme().colors().element_hover))
4547                        .child(
4548                            Label::new(commit.subject.clone())
4549                                .size(LabelSize::Small)
4550                                .truncate(),
4551                        )
4552                        .on_click({
4553                            let commit = commit.clone();
4554                            let repo = active_repository.downgrade();
4555                            move |_, window, cx| {
4556                                CommitView::open(
4557                                    commit.sha.to_string(),
4558                                    repo.clone(),
4559                                    workspace.clone(),
4560                                    None,
4561                                    None,
4562                                    None,
4563                                    window,
4564                                    cx,
4565                                );
4566                            }
4567                        })
4568                        .hoverable_tooltip({
4569                            let repo = active_repository.clone();
4570                            move |window, cx| {
4571                                GitPanelMessageTooltip::new(
4572                                    this.clone(),
4573                                    commit.sha.clone(),
4574                                    repo.clone(),
4575                                    window,
4576                                    cx,
4577                                )
4578                                .into()
4579                            }
4580                        }),
4581                )
4582                .child(
4583                    h_flex()
4584                        .gap_0p5()
4585                        .when(commit.has_parent, |this| {
4586                            let has_unstaged = self.has_unstaged_changes();
4587                            this.child(
4588                                panel_icon_button("undo", IconName::Undo)
4589                                    .icon_size(IconSize::Small)
4590                                    .tooltip(move |_window, cx| {
4591                                        Tooltip::with_meta(
4592                                            "Uncommit",
4593                                            Some(&git::Uncommit),
4594                                            if has_unstaged {
4595                                                "git reset HEAD^ --soft"
4596                                            } else {
4597                                                "git reset HEAD^"
4598                                            },
4599                                            cx,
4600                                        )
4601                                    })
4602                                    .on_click(
4603                                        cx.listener(|this, _, window, cx| {
4604                                            this.uncommit(window, cx)
4605                                        }),
4606                                    ),
4607                            )
4608                        })
4609                        .child(
4610                            panel_icon_button("git-graph-button", IconName::GitGraph)
4611                                .icon_size(IconSize::Small)
4612                                .tooltip(|_window, cx| {
4613                                    Tooltip::for_action("Open Git Graph", &Open, cx)
4614                                })
4615                                .on_click(|_, window, cx| {
4616                                    window.dispatch_action(Open.boxed_clone(), cx)
4617                                }),
4618                        ),
4619                ),
4620        )
4621    }
4622
4623    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4624        let has_repo = self.active_repository.is_some();
4625        let has_no_repo = self.active_repository.is_none();
4626        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4627
4628        let should_show_branch_diff =
4629            has_repo && self.changes_count == 0 && !self.is_on_main_branch(cx);
4630
4631        let label = if has_repo {
4632            "No changes to commit"
4633        } else {
4634            "No Git repositories"
4635        };
4636
4637        v_flex()
4638            .gap_1p5()
4639            .flex_1()
4640            .items_center()
4641            .justify_center()
4642            .child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
4643            .when(has_no_repo && worktree_count > 0, |this| {
4644                this.child(
4645                    panel_filled_button("Initialize Repository")
4646                        .tooltip(Tooltip::for_action_title_in(
4647                            "git init",
4648                            &git::Init,
4649                            &self.focus_handle,
4650                        ))
4651                        .on_click(move |_, _, cx| {
4652                            cx.defer(move |cx| {
4653                                cx.dispatch_action(&git::Init);
4654                            })
4655                        }),
4656                )
4657            })
4658            .when(should_show_branch_diff, |this| {
4659                this.child(
4660                    panel_filled_button("View Branch Diff")
4661                        .tooltip(move |_, cx| {
4662                            Tooltip::with_meta(
4663                                "Branch Diff",
4664                                Some(&BranchDiff),
4665                                "Show diff between working directory and default branch",
4666                                cx,
4667                            )
4668                        })
4669                        .on_click(move |_, _, cx| {
4670                            cx.defer(move |cx| {
4671                                cx.dispatch_action(&BranchDiff);
4672                            })
4673                        }),
4674                )
4675            })
4676    }
4677
4678    fn is_on_main_branch(&self, cx: &Context<Self>) -> bool {
4679        let Some(repo) = self.active_repository.as_ref() else {
4680            return false;
4681        };
4682
4683        let Some(branch) = repo.read(cx).branch.as_ref() else {
4684            return false;
4685        };
4686
4687        let branch_name = branch.name();
4688        matches!(branch_name, "main" | "master")
4689    }
4690
4691    fn render_buffer_header_controls(
4692        &self,
4693        entity: &Entity<Self>,
4694        file: &Arc<dyn File>,
4695        _: &Window,
4696        cx: &App,
4697    ) -> Option<AnyElement> {
4698        let repo = self.active_repository.as_ref()?.read(cx);
4699        let project_path = (file.worktree_id(cx), file.path().clone()).into();
4700        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4701        let ix = self.entry_by_path(&repo_path)?;
4702        let entry = self.entries.get(ix)?;
4703
4704        let is_staging_or_staged = repo
4705            .pending_ops_for_path(&repo_path)
4706            .map(|ops| ops.staging() || ops.staged())
4707            .or_else(|| {
4708                repo.status_for_path(&repo_path)
4709                    .and_then(|status| status.status.staging().as_bool())
4710            })
4711            .or_else(|| {
4712                entry
4713                    .status_entry()
4714                    .and_then(|entry| entry.staging.as_bool())
4715            });
4716
4717        let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4718            .disabled(!self.has_write_access(cx))
4719            .fill()
4720            .elevation(ElevationIndex::Surface)
4721            .on_click({
4722                let entry = entry.clone();
4723                let git_panel = entity.downgrade();
4724                move |_, window, cx| {
4725                    git_panel
4726                        .update(cx, |this, cx| {
4727                            this.toggle_staged_for_entry(&entry, window, cx);
4728                            cx.stop_propagation();
4729                        })
4730                        .ok();
4731                }
4732            });
4733        Some(
4734            h_flex()
4735                .id("start-slot")
4736                .text_lg()
4737                .child(checkbox)
4738                .on_mouse_down(MouseButton::Left, |_, _, cx| {
4739                    // prevent the list item active state triggering when toggling checkbox
4740                    cx.stop_propagation();
4741                })
4742                .into_any_element(),
4743        )
4744    }
4745
4746    fn render_entries(
4747        &self,
4748        has_write_access: bool,
4749        repo: Entity<Repository>,
4750        window: &mut Window,
4751        cx: &mut Context<Self>,
4752    ) -> impl IntoElement {
4753        let (is_tree_view, entry_count) = match &self.view_mode {
4754            GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4755            GitPanelViewMode::Flat => (false, self.entries.len()),
4756        };
4757        let repo = repo.downgrade();
4758
4759        v_flex()
4760            .flex_1()
4761            .size_full()
4762            .overflow_hidden()
4763            .relative()
4764            .child(
4765                h_flex()
4766                    .flex_1()
4767                    .size_full()
4768                    .relative()
4769                    .overflow_hidden()
4770                    .child(
4771                        uniform_list(
4772                            "entries",
4773                            entry_count,
4774                            cx.processor(move |this, range: Range<usize>, window, cx| {
4775                                let Some(repo) = repo.upgrade() else {
4776                                    return Vec::new();
4777                                };
4778                                let repo = repo.read(cx);
4779
4780                                let mut items = Vec::with_capacity(range.end - range.start);
4781
4782                                for ix in range.into_iter().map(|ix| match &this.view_mode {
4783                                    GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4784                                    GitPanelViewMode::Flat => ix,
4785                                }) {
4786                                    match &this.entries.get(ix) {
4787                                        Some(GitListEntry::Status(entry)) => {
4788                                            items.push(this.render_status_entry(
4789                                                ix,
4790                                                entry,
4791                                                0,
4792                                                has_write_access,
4793                                                repo,
4794                                                window,
4795                                                cx,
4796                                            ));
4797                                        }
4798                                        Some(GitListEntry::TreeStatus(entry)) => {
4799                                            items.push(this.render_status_entry(
4800                                                ix,
4801                                                &entry.entry,
4802                                                entry.depth,
4803                                                has_write_access,
4804                                                repo,
4805                                                window,
4806                                                cx,
4807                                            ));
4808                                        }
4809                                        Some(GitListEntry::Directory(entry)) => {
4810                                            items.push(this.render_directory_entry(
4811                                                ix,
4812                                                entry,
4813                                                has_write_access,
4814                                                window,
4815                                                cx,
4816                                            ));
4817                                        }
4818                                        Some(GitListEntry::Header(header)) => {
4819                                            items.push(this.render_list_header(
4820                                                ix,
4821                                                header,
4822                                                has_write_access,
4823                                                window,
4824                                                cx,
4825                                            ));
4826                                        }
4827                                        None => {}
4828                                    }
4829                                }
4830
4831                                items
4832                            }),
4833                        )
4834                        .when(is_tree_view, |list| {
4835                            let indent_size = px(TREE_INDENT);
4836                            list.with_decoration(
4837                                ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4838                                    .with_compute_indents_fn(
4839                                        cx.entity(),
4840                                        |this, range, _window, _cx| {
4841                                            this.compute_visible_depths(range)
4842                                        },
4843                                    )
4844                                    .with_render_fn(cx.entity(), |_, params, _, _| {
4845                                        // Magic number to align the tree item is 3 here
4846                                        // because we're using 12px as the left-side padding
4847                                        // and 3 makes the alignment work with the bounding box of the icon
4848                                        let left_offset = px(TREE_INDENT + 3_f32);
4849                                        let indent_size = params.indent_size;
4850                                        let item_height = params.item_height;
4851
4852                                        params
4853                                            .indent_guides
4854                                            .into_iter()
4855                                            .map(|layout| {
4856                                                let bounds = Bounds::new(
4857                                                    point(
4858                                                        layout.offset.x * indent_size + left_offset,
4859                                                        layout.offset.y * item_height,
4860                                                    ),
4861                                                    size(px(1.), layout.length * item_height),
4862                                                );
4863                                                RenderedIndentGuide {
4864                                                    bounds,
4865                                                    layout,
4866                                                    is_active: false,
4867                                                    hitbox: None,
4868                                                }
4869                                            })
4870                                            .collect()
4871                                    }),
4872                            )
4873                        })
4874                        .size_full()
4875                        .flex_grow()
4876                        .with_width_from_item(self.max_width_item_index)
4877                        .track_scroll(&self.scroll_handle),
4878                    )
4879                    .on_mouse_down(
4880                        MouseButton::Right,
4881                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4882                            this.deploy_panel_context_menu(event.position, window, cx)
4883                        }),
4884                    )
4885                    .custom_scrollbars(
4886                        Scrollbars::for_settings::<GitPanelScrollbarAccessor>()
4887                            .tracked_scroll_handle(&self.scroll_handle)
4888                            .with_track_along(
4889                                ScrollAxes::Horizontal,
4890                                cx.theme().colors().panel_background,
4891                            ),
4892                        window,
4893                        cx,
4894                    ),
4895            )
4896    }
4897
4898    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4899        Label::new(label.into()).color(color)
4900    }
4901
4902    fn list_item_height(&self) -> Rems {
4903        rems(1.75)
4904    }
4905
4906    fn render_list_header(
4907        &self,
4908        ix: usize,
4909        header: &GitHeaderEntry,
4910        _: bool,
4911        _: &Window,
4912        _: &Context<Self>,
4913    ) -> AnyElement {
4914        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4915
4916        h_flex()
4917            .id(id)
4918            .h(self.list_item_height())
4919            .w_full()
4920            .items_end()
4921            .px_3()
4922            .pb_1()
4923            .child(
4924                Label::new(header.title())
4925                    .color(Color::Muted)
4926                    .size(LabelSize::Small)
4927                    .line_height_style(LineHeightStyle::UiLabel)
4928                    .single_line(),
4929            )
4930            .into_any_element()
4931    }
4932
4933    pub fn load_commit_details(
4934        &self,
4935        sha: String,
4936        cx: &mut Context<Self>,
4937    ) -> Task<anyhow::Result<CommitDetails>> {
4938        let Some(repo) = self.active_repository.clone() else {
4939            return Task::ready(Err(anyhow::anyhow!("no active repo")));
4940        };
4941        repo.update(cx, |repo, cx| {
4942            let show = repo.show(sha);
4943            cx.spawn(async move |_, _| show.await?)
4944        })
4945    }
4946
4947    fn deploy_entry_context_menu(
4948        &mut self,
4949        position: Point<Pixels>,
4950        ix: usize,
4951        window: &mut Window,
4952        cx: &mut Context<Self>,
4953    ) {
4954        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4955            return;
4956        };
4957        let stage_title = if entry.status.staging().is_fully_staged() {
4958            "Unstage File"
4959        } else {
4960            "Stage File"
4961        };
4962        let restore_title = if entry.status.is_created() {
4963            "Trash File"
4964        } else {
4965            "Discard Changes"
4966        };
4967        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4968            let is_created = entry.status.is_created();
4969            context_menu
4970                .context(self.focus_handle.clone())
4971                .action(stage_title, ToggleStaged.boxed_clone())
4972                .action(restore_title, git::RestoreFile::default().boxed_clone())
4973                .action_disabled_when(
4974                    !is_created,
4975                    "Add to .gitignore",
4976                    git::AddToGitignore.boxed_clone(),
4977                )
4978                .separator()
4979                .action("Open Diff", menu::Confirm.boxed_clone())
4980                .action("Open File", menu::SecondaryConfirm.boxed_clone())
4981                .separator()
4982                .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
4983        });
4984        self.selected_entry = Some(ix);
4985        self.set_context_menu(context_menu, position, window, cx);
4986    }
4987
4988    fn deploy_panel_context_menu(
4989        &mut self,
4990        position: Point<Pixels>,
4991        window: &mut Window,
4992        cx: &mut Context<Self>,
4993    ) {
4994        let context_menu = git_panel_context_menu(
4995            self.focus_handle.clone(),
4996            GitMenuState {
4997                has_tracked_changes: self.has_tracked_changes(),
4998                has_staged_changes: self.has_staged_changes(),
4999                has_unstaged_changes: self.has_unstaged_changes(),
5000                has_new_changes: self.new_count > 0,
5001                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
5002                has_stash_items: self.stash_entries.entries.len() > 0,
5003                tree_view: GitPanelSettings::get_global(cx).tree_view,
5004            },
5005            window,
5006            cx,
5007        );
5008        self.set_context_menu(context_menu, position, window, cx);
5009    }
5010
5011    fn set_context_menu(
5012        &mut self,
5013        context_menu: Entity<ContextMenu>,
5014        position: Point<Pixels>,
5015        window: &Window,
5016        cx: &mut Context<Self>,
5017    ) {
5018        let subscription = cx.subscribe_in(
5019            &context_menu,
5020            window,
5021            |this, _, _: &DismissEvent, window, cx| {
5022                if this.context_menu.as_ref().is_some_and(|context_menu| {
5023                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
5024                }) {
5025                    cx.focus_self(window);
5026                }
5027                this.context_menu.take();
5028                cx.notify();
5029            },
5030        );
5031        self.context_menu = Some((context_menu, position, subscription));
5032        cx.notify();
5033    }
5034
5035    fn render_status_entry(
5036        &self,
5037        ix: usize,
5038        entry: &GitStatusEntry,
5039        depth: usize,
5040        has_write_access: bool,
5041        repo: &Repository,
5042        window: &Window,
5043        cx: &Context<Self>,
5044    ) -> AnyElement {
5045        let settings = GitPanelSettings::get_global(cx);
5046        let tree_view = settings.tree_view;
5047        let path_style = self.project.read(cx).path_style(cx);
5048        let git_path_style = ProjectSettings::get_global(cx).git.path_style;
5049        let display_name = entry.display_name(path_style);
5050
5051        let selected = self.selected_entry == Some(ix);
5052        let marked = self.marked_entries.contains(&ix);
5053        let status_style = settings.status_style;
5054        let status = entry.status;
5055        let file_icon = if settings.file_icons {
5056            FileIcons::get_icon(entry.repo_path.as_std_path(), cx)
5057        } else {
5058            None
5059        };
5060
5061        let has_conflict = status.is_conflicted();
5062        let is_modified = status.is_modified();
5063        let is_deleted = status.is_deleted();
5064        let is_created = status.is_created();
5065
5066        let label_color = if status_style == StatusStyle::LabelColor {
5067            if has_conflict {
5068                Color::VersionControlConflict
5069            } else if is_created {
5070                Color::VersionControlAdded
5071            } else if is_modified {
5072                Color::VersionControlModified
5073            } else if is_deleted {
5074                // We don't want a bunch of red labels in the list
5075                Color::Disabled
5076            } else {
5077                Color::VersionControlAdded
5078            }
5079        } else {
5080            Color::Default
5081        };
5082
5083        let path_color = if status.is_deleted() {
5084            Color::Disabled
5085        } else {
5086            Color::Muted
5087        };
5088
5089        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
5090        let checkbox_wrapper_id: ElementId =
5091            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
5092        let checkbox_id: ElementId =
5093            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
5094
5095        let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
5096        let mut is_staged: ToggleState = match stage_status {
5097            StageStatus::Staged => ToggleState::Selected,
5098            StageStatus::Unstaged => ToggleState::Unselected,
5099            StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5100        };
5101        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
5102            is_staged = ToggleState::Selected;
5103        }
5104
5105        let handle = cx.weak_entity();
5106
5107        let selected_bg_alpha = 0.08;
5108        let marked_bg_alpha = 0.12;
5109        let state_opacity_step = 0.04;
5110
5111        let info_color = cx.theme().status().info;
5112
5113        let base_bg = match (selected, marked) {
5114            (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
5115            (true, false) => info_color.alpha(selected_bg_alpha),
5116            (false, true) => info_color.alpha(marked_bg_alpha),
5117            _ => cx.theme().colors().ghost_element_background,
5118        };
5119
5120        let (hover_bg, active_bg) = if selected {
5121            (
5122                info_color.alpha(selected_bg_alpha + state_opacity_step),
5123                info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5124            )
5125        } else {
5126            (
5127                cx.theme().colors().ghost_element_hover,
5128                cx.theme().colors().ghost_element_active,
5129            )
5130        };
5131
5132        let name_row = h_flex()
5133            .min_w_0()
5134            .flex_1()
5135            .gap_1()
5136            .when(settings.file_icons, |this| {
5137                this.child(
5138                    file_icon
5139                        .map(|file_icon| {
5140                            Icon::from_path(file_icon)
5141                                .size(IconSize::Small)
5142                                .color(Color::Muted)
5143                        })
5144                        .unwrap_or_else(|| {
5145                            Icon::new(IconName::File)
5146                                .size(IconSize::Small)
5147                                .color(Color::Muted)
5148                        }),
5149                )
5150            })
5151            .when(status_style != StatusStyle::LabelColor, |el| {
5152                el.child(git_status_icon(status))
5153            })
5154            .map(|this| {
5155                if tree_view {
5156                    this.pl(px(depth as f32 * TREE_INDENT)).child(
5157                        self.entry_label(display_name, label_color)
5158                            .when(status.is_deleted(), Label::strikethrough)
5159                            .truncate(),
5160                    )
5161                } else {
5162                    this.child(self.path_formatted(
5163                        entry.parent_dir(path_style),
5164                        path_color,
5165                        display_name,
5166                        label_color,
5167                        path_style,
5168                        git_path_style,
5169                        status.is_deleted(),
5170                    ))
5171                }
5172            });
5173
5174        let id_for_diff_stat = id.clone();
5175
5176        h_flex()
5177            .id(id)
5178            .h(self.list_item_height())
5179            .w_full()
5180            .pl_3()
5181            .pr_1()
5182            .gap_1p5()
5183            .border_1()
5184            .border_r_2()
5185            .when(selected && self.focus_handle.is_focused(window), |el| {
5186                el.border_color(cx.theme().colors().panel_focused_border)
5187            })
5188            .bg(base_bg)
5189            .hover(|s| s.bg(hover_bg))
5190            .active(|s| s.bg(active_bg))
5191            .child(name_row)
5192            .when(GitPanelSettings::get_global(cx).diff_stats, |el| {
5193                el.when_some(entry.diff_stat, move |this, stat| {
5194                    let id = format!("diff-stat-{}", id_for_diff_stat);
5195                    this.child(ui::DiffStat::new(
5196                        id,
5197                        stat.added as usize,
5198                        stat.deleted as usize,
5199                    ))
5200                })
5201            })
5202            .child(
5203                div()
5204                    .id(checkbox_wrapper_id)
5205                    .flex_none()
5206                    .occlude()
5207                    .cursor_pointer()
5208                    .child(
5209                        Checkbox::new(checkbox_id, is_staged)
5210                            .disabled(!has_write_access)
5211                            .fill()
5212                            .elevation(ElevationIndex::Surface)
5213                            .on_click_ext({
5214                                let entry = entry.clone();
5215                                let this = cx.weak_entity();
5216                                move |_, click, window, cx| {
5217                                    this.update(cx, |this, cx| {
5218                                        if !has_write_access {
5219                                            return;
5220                                        }
5221                                        if click.modifiers().shift {
5222                                            this.stage_bulk(ix, cx);
5223                                        } else {
5224                                            let list_entry =
5225                                                if GitPanelSettings::get_global(cx).tree_view {
5226                                                    GitListEntry::TreeStatus(GitTreeStatusEntry {
5227                                                        entry: entry.clone(),
5228                                                        depth,
5229                                                    })
5230                                                } else {
5231                                                    GitListEntry::Status(entry.clone())
5232                                                };
5233                                            this.toggle_staged_for_entry(&list_entry, window, cx);
5234                                        }
5235                                        cx.stop_propagation();
5236                                    })
5237                                    .ok();
5238                                }
5239                            })
5240                            .tooltip(move |_window, cx| {
5241                                let action = match stage_status {
5242                                    StageStatus::Staged => "Unstage",
5243                                    StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5244                                };
5245                                let tooltip_name = action.to_string();
5246
5247                                Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5248                            }),
5249                    ),
5250            )
5251            .on_click({
5252                cx.listener(move |this, event: &ClickEvent, window, cx| {
5253                    this.selected_entry = Some(ix);
5254                    cx.notify();
5255                    if event.click_count() > 1 || event.modifiers().secondary() {
5256                        this.open_file(&Default::default(), window, cx)
5257                    } else {
5258                        this.open_diff(&Default::default(), window, cx);
5259                        this.focus_handle.focus(window, cx);
5260                    }
5261                })
5262            })
5263            .on_mouse_down(
5264                MouseButton::Right,
5265                move |event: &MouseDownEvent, window, cx| {
5266                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5267                    if event.button != MouseButton::Right {
5268                        return;
5269                    }
5270
5271                    let Some(this) = handle.upgrade() else {
5272                        return;
5273                    };
5274                    this.update(cx, |this, cx| {
5275                        this.deploy_entry_context_menu(event.position, ix, window, cx);
5276                    });
5277                    cx.stop_propagation();
5278                },
5279            )
5280            .into_any_element()
5281    }
5282
5283    fn render_directory_entry(
5284        &self,
5285        ix: usize,
5286        entry: &GitTreeDirEntry,
5287        has_write_access: bool,
5288        window: &Window,
5289        cx: &Context<Self>,
5290    ) -> AnyElement {
5291        // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5292        let selected = self.selected_entry == Some(ix);
5293        let label_color = Color::Muted;
5294
5295        let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5296        let checkbox_id: ElementId =
5297            ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5298        let checkbox_wrapper_id: ElementId =
5299            ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5300
5301        let selected_bg_alpha = 0.08;
5302        let state_opacity_step = 0.04;
5303
5304        let info_color = cx.theme().status().info;
5305        let colors = cx.theme().colors();
5306
5307        let (base_bg, hover_bg, active_bg) = if selected {
5308            (
5309                info_color.alpha(selected_bg_alpha),
5310                info_color.alpha(selected_bg_alpha + state_opacity_step),
5311                info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5312            )
5313        } else {
5314            (
5315                colors.ghost_element_background,
5316                colors.ghost_element_hover,
5317                colors.ghost_element_active,
5318            )
5319        };
5320
5321        let settings = GitPanelSettings::get_global(cx);
5322        let folder_icon = if settings.folder_icons {
5323            FileIcons::get_folder_icon(entry.expanded, entry.key.path.as_std_path(), cx)
5324        } else {
5325            FileIcons::get_chevron_icon(entry.expanded, cx)
5326        };
5327        let fallback_folder_icon = if settings.folder_icons {
5328            if entry.expanded {
5329                IconName::FolderOpen
5330            } else {
5331                IconName::Folder
5332            }
5333        } else {
5334            if entry.expanded {
5335                IconName::ChevronDown
5336            } else {
5337                IconName::ChevronRight
5338            }
5339        };
5340
5341        let stage_status = if let Some(repo) = &self.active_repository {
5342            self.stage_status_for_directory(entry, repo.read(cx))
5343        } else {
5344            util::debug_panic!(
5345                "Won't have entries to render without an active repository in Git Panel"
5346            );
5347            StageStatus::PartiallyStaged
5348        };
5349
5350        let toggle_state: ToggleState = match stage_status {
5351            StageStatus::Staged => ToggleState::Selected,
5352            StageStatus::Unstaged => ToggleState::Unselected,
5353            StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5354        };
5355
5356        let name_row = h_flex()
5357            .min_w_0()
5358            .gap_1()
5359            .pl(px(entry.depth as f32 * TREE_INDENT))
5360            .child(
5361                folder_icon
5362                    .map(|folder_icon| {
5363                        Icon::from_path(folder_icon)
5364                            .size(IconSize::Small)
5365                            .color(Color::Muted)
5366                    })
5367                    .unwrap_or_else(|| {
5368                        Icon::new(fallback_folder_icon)
5369                            .size(IconSize::Small)
5370                            .color(Color::Muted)
5371                    }),
5372            )
5373            .child(self.entry_label(entry.name.clone(), label_color).truncate());
5374
5375        h_flex()
5376            .id(id)
5377            .h(self.list_item_height())
5378            .min_w_0()
5379            .w_full()
5380            .pl_3()
5381            .pr_1()
5382            .gap_1p5()
5383            .justify_between()
5384            .border_1()
5385            .border_r_2()
5386            .when(selected && self.focus_handle.is_focused(window), |el| {
5387                el.border_color(cx.theme().colors().panel_focused_border)
5388            })
5389            .bg(base_bg)
5390            .hover(|s| s.bg(hover_bg))
5391            .active(|s| s.bg(active_bg))
5392            .child(name_row)
5393            .child(
5394                div()
5395                    .id(checkbox_wrapper_id)
5396                    .flex_none()
5397                    .occlude()
5398                    .cursor_pointer()
5399                    .child(
5400                        Checkbox::new(checkbox_id, toggle_state)
5401                            .disabled(!has_write_access)
5402                            .fill()
5403                            .elevation(ElevationIndex::Surface)
5404                            .on_click({
5405                                let entry = entry.clone();
5406                                let this = cx.weak_entity();
5407                                move |_, window, cx| {
5408                                    this.update(cx, |this, cx| {
5409                                        if !has_write_access {
5410                                            return;
5411                                        }
5412                                        this.toggle_staged_for_entry(
5413                                            &GitListEntry::Directory(entry.clone()),
5414                                            window,
5415                                            cx,
5416                                        );
5417                                        cx.stop_propagation();
5418                                    })
5419                                    .ok();
5420                                }
5421                            })
5422                            .tooltip(move |_window, cx| {
5423                                let action = match stage_status {
5424                                    StageStatus::Staged => "Unstage",
5425                                    StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5426                                };
5427                                Tooltip::simple(format!("{action} folder"), cx)
5428                            }),
5429                    ),
5430            )
5431            .on_click({
5432                let key = entry.key.clone();
5433                cx.listener(move |this, _event: &ClickEvent, window, cx| {
5434                    this.selected_entry = Some(ix);
5435                    this.toggle_directory(&key, window, cx);
5436                })
5437            })
5438            .into_any_element()
5439    }
5440
5441    fn path_formatted(
5442        &self,
5443        directory: Option<String>,
5444        path_color: Color,
5445        file_name: String,
5446        label_color: Color,
5447        path_style: PathStyle,
5448        git_path_style: GitPathStyle,
5449        strikethrough: bool,
5450    ) -> Div {
5451        let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5452        let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5453
5454        let file_name = format!("{} ", file_name);
5455
5456        h_flex()
5457            .min_w_0()
5458            .overflow_hidden()
5459            .when(file_path_first, |this| this.flex_row_reverse())
5460            .child(
5461                div().flex_none().child(
5462                    self.entry_label(file_name, label_color)
5463                        .when(strikethrough, Label::strikethrough),
5464                ),
5465            )
5466            .when_some(directory, |this, dir| {
5467                let path_name = if file_name_first {
5468                    dir
5469                } else {
5470                    format!("{dir}{}", path_style.primary_separator())
5471                };
5472
5473                this.child(
5474                    self.entry_label(path_name, path_color)
5475                        .truncate_start()
5476                        .when(strikethrough, Label::strikethrough),
5477                )
5478            })
5479    }
5480
5481    fn has_write_access(&self, cx: &App) -> bool {
5482        !self.project.read(cx).is_read_only(cx)
5483    }
5484
5485    pub fn amend_pending(&self) -> bool {
5486        self.amend_pending
5487    }
5488
5489    /// Sets the pending amend state, ensuring that the original commit message
5490    /// is either saved, when `value` is `true` and there's no pending amend, or
5491    /// restored, when `value` is `false` and there's a pending amend.
5492    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5493        if value && !self.amend_pending {
5494            let current_message = self.commit_message_buffer(cx).read(cx).text();
5495            self.original_commit_message = if current_message.trim().is_empty() {
5496                None
5497            } else {
5498                Some(current_message)
5499            };
5500        } else if !value && self.amend_pending {
5501            let message = self.original_commit_message.take().unwrap_or_default();
5502            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5503                let start = buffer.anchor_before(0);
5504                let end = buffer.anchor_after(buffer.len());
5505                buffer.edit([(start..end, message)], None, cx);
5506            });
5507        }
5508
5509        self.amend_pending = value;
5510        self.serialize(cx);
5511        cx.notify();
5512    }
5513
5514    pub fn signoff_enabled(&self) -> bool {
5515        self.signoff_enabled
5516    }
5517
5518    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5519        self.signoff_enabled = value;
5520        self.serialize(cx);
5521        cx.notify();
5522    }
5523
5524    pub fn toggle_signoff_enabled(
5525        &mut self,
5526        _: &Signoff,
5527        _window: &mut Window,
5528        cx: &mut Context<Self>,
5529    ) {
5530        self.set_signoff_enabled(!self.signoff_enabled, cx);
5531    }
5532
5533    pub async fn load(
5534        workspace: WeakEntity<Workspace>,
5535        mut cx: AsyncWindowContext,
5536    ) -> anyhow::Result<Entity<Self>> {
5537        let serialized_panel = match workspace
5538            .read_with(&cx, |workspace, cx| {
5539                Self::serialization_key(workspace).map(|key| (key, KeyValueStore::global(cx)))
5540            })
5541            .ok()
5542            .flatten()
5543        {
5544            Some((serialization_key, kvp)) => cx
5545                .background_spawn(async move { kvp.read_kvp(&serialization_key) })
5546                .await
5547                .context("loading git panel")
5548                .log_err()
5549                .flatten()
5550                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5551                .transpose()
5552                .log_err()
5553                .flatten(),
5554            None => None,
5555        };
5556
5557        workspace.update_in(&mut cx, |workspace, window, cx| {
5558            let panel = GitPanel::new(workspace, window, cx);
5559
5560            if let Some(serialized_panel) = serialized_panel {
5561                panel.update(cx, |panel, cx| {
5562                    panel.amend_pending = serialized_panel.amend_pending;
5563                    panel.signoff_enabled = serialized_panel.signoff_enabled;
5564                    cx.notify();
5565                })
5566            }
5567
5568            panel
5569        })
5570    }
5571
5572    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5573        let Some(op) = self.bulk_staging.as_ref() else {
5574            return;
5575        };
5576        let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5577            return;
5578        };
5579        if let Some(entry) = self.entries.get(index)
5580            && let Some(entry) = entry.status_entry()
5581        {
5582            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5583        }
5584        if index < anchor_index {
5585            std::mem::swap(&mut index, &mut anchor_index);
5586        }
5587        let entries = self
5588            .entries
5589            .get(anchor_index..=index)
5590            .unwrap_or_default()
5591            .iter()
5592            .filter_map(|entry| entry.status_entry().cloned())
5593            .collect::<Vec<_>>();
5594        self.change_file_stage(true, entries, cx);
5595    }
5596
5597    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5598        let Some(repo) = self.active_repository.as_ref() else {
5599            return;
5600        };
5601        self.bulk_staging = Some(BulkStaging {
5602            repo_id: repo.read(cx).id,
5603            anchor: path,
5604        });
5605    }
5606
5607    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5608        self.set_amend_pending(!self.amend_pending, cx);
5609        if self.amend_pending {
5610            self.load_last_commit_message(cx);
5611        }
5612    }
5613}
5614
5615#[cfg(any(test, feature = "test-support"))]
5616impl GitPanel {
5617    pub fn new_test(
5618        workspace: &mut Workspace,
5619        window: &mut Window,
5620        cx: &mut Context<Workspace>,
5621    ) -> Entity<Self> {
5622        Self::new(workspace, window, cx)
5623    }
5624
5625    pub fn active_repository(&self) -> Option<&Entity<Repository>> {
5626        self.active_repository.as_ref()
5627    }
5628}
5629
5630impl Render for GitPanel {
5631    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5632        let project = self.project.read(cx);
5633        let has_entries = !self.entries.is_empty();
5634        let room = self.workspace.upgrade().and_then(|_workspace| {
5635            call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
5636        });
5637
5638        let has_write_access = self.has_write_access(cx);
5639
5640        let has_co_authors = room.is_some_and(|room| {
5641            self.load_local_committer(cx);
5642            let room = room.read(cx);
5643            room.remote_participants()
5644                .values()
5645                .any(|remote_participant| remote_participant.can_write())
5646        });
5647
5648        v_flex()
5649            .id("git_panel")
5650            .key_context(self.dispatch_context(window, cx))
5651            .track_focus(&self.focus_handle)
5652            .when(has_write_access && !project.is_read_only(cx), |this| {
5653                this.on_action(cx.listener(Self::toggle_staged_for_selected))
5654                    .on_action(cx.listener(Self::stage_range))
5655                    .on_action(cx.listener(GitPanel::on_commit))
5656                    .on_action(cx.listener(GitPanel::on_amend))
5657                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5658                    .on_action(cx.listener(Self::stage_all))
5659                    .on_action(cx.listener(Self::unstage_all))
5660                    .on_action(cx.listener(Self::stage_selected))
5661                    .on_action(cx.listener(Self::unstage_selected))
5662                    .on_action(cx.listener(Self::restore_tracked_files))
5663                    .on_action(cx.listener(Self::revert_selected))
5664                    .on_action(cx.listener(Self::add_to_gitignore))
5665                    .on_action(cx.listener(Self::clean_all))
5666                    .on_action(cx.listener(Self::generate_commit_message_action))
5667                    .on_action(cx.listener(Self::stash_all))
5668                    .on_action(cx.listener(Self::stash_pop))
5669            })
5670            .on_action(cx.listener(Self::collapse_selected_entry))
5671            .on_action(cx.listener(Self::expand_selected_entry))
5672            .on_action(cx.listener(Self::select_first))
5673            .on_action(cx.listener(Self::select_next))
5674            .on_action(cx.listener(Self::select_previous))
5675            .on_action(cx.listener(Self::select_last))
5676            .on_action(cx.listener(Self::first_entry))
5677            .on_action(cx.listener(Self::next_entry))
5678            .on_action(cx.listener(Self::previous_entry))
5679            .on_action(cx.listener(Self::last_entry))
5680            .on_action(cx.listener(Self::close_panel))
5681            .on_action(cx.listener(Self::open_diff))
5682            .on_action(cx.listener(Self::open_file))
5683            .on_action(cx.listener(Self::file_history))
5684            .on_action(cx.listener(Self::focus_changes_list))
5685            .on_action(cx.listener(Self::focus_editor))
5686            .on_action(cx.listener(Self::expand_commit_editor))
5687            .when(has_write_access && has_co_authors, |git_panel| {
5688                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5689            })
5690            .on_action(cx.listener(Self::toggle_sort_by_path))
5691            .on_action(cx.listener(Self::toggle_tree_view))
5692            .size_full()
5693            .overflow_hidden()
5694            .bg(cx.theme().colors().panel_background)
5695            .child(
5696                v_flex()
5697                    .size_full()
5698                    .children(self.render_panel_header(window, cx))
5699                    .map(|this| {
5700                        if let Some(repo) = self.active_repository.clone()
5701                            && has_entries
5702                        {
5703                            this.child(self.render_entries(has_write_access, repo, window, cx))
5704                        } else {
5705                            this.child(self.render_empty_state(cx).into_any_element())
5706                        }
5707                    })
5708                    .children(self.render_footer(window, cx))
5709                    .when(self.amend_pending, |this| {
5710                        this.child(self.render_pending_amend(cx))
5711                    })
5712                    .when(!self.amend_pending, |this| {
5713                        this.children(self.render_previous_commit(window, cx))
5714                    })
5715                    .into_any_element(),
5716            )
5717            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5718                deferred(
5719                    anchored()
5720                        .position(*position)
5721                        .anchor(Corner::TopLeft)
5722                        .child(menu.clone()),
5723                )
5724                .with_priority(1)
5725            }))
5726    }
5727}
5728
5729impl Focusable for GitPanel {
5730    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5731        if self.entries.is_empty() {
5732            self.commit_editor.focus_handle(cx)
5733        } else {
5734            self.focus_handle.clone()
5735        }
5736    }
5737}
5738
5739impl EventEmitter<Event> for GitPanel {}
5740
5741impl EventEmitter<PanelEvent> for GitPanel {}
5742
5743pub(crate) struct GitPanelAddon {
5744    pub(crate) workspace: WeakEntity<Workspace>,
5745}
5746
5747impl editor::Addon for GitPanelAddon {
5748    fn to_any(&self) -> &dyn std::any::Any {
5749        self
5750    }
5751
5752    fn render_buffer_header_controls(
5753        &self,
5754        _excerpt_info: &ExcerptBoundaryInfo,
5755        buffer: &language::BufferSnapshot,
5756        window: &Window,
5757        cx: &App,
5758    ) -> Option<AnyElement> {
5759        let file = buffer.file()?;
5760        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5761
5762        git_panel
5763            .read(cx)
5764            .render_buffer_header_controls(&git_panel, file, window, cx)
5765    }
5766}
5767
5768impl Panel for GitPanel {
5769    fn persistent_name() -> &'static str {
5770        "GitPanel"
5771    }
5772
5773    fn panel_key() -> &'static str {
5774        GIT_PANEL_KEY
5775    }
5776
5777    fn position(&self, _: &Window, cx: &App) -> DockPosition {
5778        GitPanelSettings::get_global(cx).dock
5779    }
5780
5781    fn position_is_valid(&self, position: DockPosition) -> bool {
5782        matches!(position, DockPosition::Left | DockPosition::Right)
5783    }
5784
5785    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5786        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5787            settings.git_panel.get_or_insert_default().dock = Some(position.into())
5788        });
5789    }
5790
5791    fn default_size(&self, _: &Window, cx: &App) -> Pixels {
5792        GitPanelSettings::get_global(cx).default_width
5793    }
5794
5795    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5796        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5797    }
5798
5799    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5800        Some("Git Panel")
5801    }
5802
5803    fn icon_label(&self, _: &Window, cx: &App) -> Option<String> {
5804        if !GitPanelSettings::get_global(cx).show_count_badge {
5805            return None;
5806        }
5807        let total = self.changes_count;
5808        (total > 0).then(|| total.to_string())
5809    }
5810
5811    fn toggle_action(&self) -> Box<dyn Action> {
5812        Box::new(ToggleFocus)
5813    }
5814
5815    fn starts_open(&self, _: &Window, cx: &App) -> bool {
5816        GitPanelSettings::get_global(cx).starts_open
5817    }
5818
5819    fn activation_priority(&self) -> u32 {
5820        3
5821    }
5822}
5823
5824impl PanelHeader for GitPanel {}
5825
5826pub fn panel_editor_container(_window: &mut Window, cx: &mut App) -> Div {
5827    v_flex()
5828        .size_full()
5829        .gap(px(8.))
5830        .p_2()
5831        .bg(cx.theme().colors().editor_background)
5832}
5833
5834pub(crate) fn panel_editor_style(monospace: bool, window: &Window, cx: &App) -> EditorStyle {
5835    let settings = ThemeSettings::get_global(cx);
5836
5837    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
5838
5839    let (font_family, font_fallbacks, font_features, font_weight, line_height) = if monospace {
5840        (
5841            settings.buffer_font.family.clone(),
5842            settings.buffer_font.fallbacks.clone(),
5843            settings.buffer_font.features.clone(),
5844            settings.buffer_font.weight,
5845            font_size * settings.buffer_line_height.value(),
5846        )
5847    } else {
5848        (
5849            settings.ui_font.family.clone(),
5850            settings.ui_font.fallbacks.clone(),
5851            settings.ui_font.features.clone(),
5852            settings.ui_font.weight,
5853            window.line_height(),
5854        )
5855    };
5856
5857    EditorStyle {
5858        background: cx.theme().colors().editor_background,
5859        local_player: cx.theme().players().local(),
5860        text: TextStyle {
5861            color: cx.theme().colors().text,
5862            font_family,
5863            font_fallbacks,
5864            font_features,
5865            font_size: TextSize::Small.rems(cx).into(),
5866            font_weight,
5867            line_height: line_height.into(),
5868            ..Default::default()
5869        },
5870        syntax: cx.theme().syntax().clone(),
5871        ..Default::default()
5872    }
5873}
5874
5875struct GitPanelMessageTooltip {
5876    commit_tooltip: Option<Entity<CommitTooltip>>,
5877}
5878
5879impl GitPanelMessageTooltip {
5880    fn new(
5881        git_panel: Entity<GitPanel>,
5882        sha: SharedString,
5883        repository: Entity<Repository>,
5884        window: &mut Window,
5885        cx: &mut App,
5886    ) -> Entity<Self> {
5887        let remote_url = repository.read(cx).default_remote_url();
5888        cx.new(|cx| {
5889            cx.spawn_in(window, async move |this, cx| {
5890                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5891                    (
5892                        git_panel.load_commit_details(sha.to_string(), cx),
5893                        git_panel.workspace.clone(),
5894                    )
5895                });
5896                let details = details.await?;
5897                let provider_registry = cx
5898                    .update(|_, app| GitHostingProviderRegistry::default_global(app))
5899                    .ok();
5900
5901                let commit_details = crate::commit_tooltip::CommitDetails {
5902                    sha: details.sha.clone(),
5903                    author_name: details.author_name.clone(),
5904                    author_email: details.author_email.clone(),
5905                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5906                    message: Some(ParsedCommitMessage::parse(
5907                        details.sha.to_string(),
5908                        details.message.to_string(),
5909                        remote_url.as_deref(),
5910                        provider_registry,
5911                    )),
5912                };
5913
5914                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5915                    this.commit_tooltip = Some(cx.new(move |cx| {
5916                        CommitTooltip::new(commit_details, repository, workspace, cx)
5917                    }));
5918                    cx.notify();
5919                })
5920            })
5921            .detach();
5922
5923            Self {
5924                commit_tooltip: None,
5925            }
5926        })
5927    }
5928}
5929
5930impl Render for GitPanelMessageTooltip {
5931    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5932        if let Some(commit_tooltip) = &self.commit_tooltip {
5933            commit_tooltip.clone().into_any_element()
5934        } else {
5935            gpui::Empty.into_any_element()
5936        }
5937    }
5938}
5939
5940#[derive(IntoElement, RegisterComponent)]
5941pub struct PanelRepoFooter {
5942    active_repository: SharedString,
5943    branch: Option<Branch>,
5944    head_commit: Option<CommitDetails>,
5945
5946    // Getting a GitPanel in previews will be difficult.
5947    //
5948    // For now just take an option here, and we won't bind handlers to buttons in previews.
5949    git_panel: Option<Entity<GitPanel>>,
5950}
5951
5952impl PanelRepoFooter {
5953    pub fn new(
5954        active_repository: SharedString,
5955        branch: Option<Branch>,
5956        head_commit: Option<CommitDetails>,
5957        git_panel: Option<Entity<GitPanel>>,
5958    ) -> Self {
5959        Self {
5960            active_repository,
5961            branch,
5962            head_commit,
5963            git_panel,
5964        }
5965    }
5966
5967    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5968        Self {
5969            active_repository,
5970            branch,
5971            head_commit: None,
5972            git_panel: None,
5973        }
5974    }
5975}
5976
5977impl RenderOnce for PanelRepoFooter {
5978    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5979        let project = self
5980            .git_panel
5981            .as_ref()
5982            .map(|panel| panel.read(cx).project.clone());
5983
5984        let (workspace, repo) = self
5985            .git_panel
5986            .as_ref()
5987            .map(|panel| {
5988                let panel = panel.read(cx);
5989                (panel.workspace.clone(), panel.active_repository.clone())
5990            })
5991            .unzip();
5992
5993        let single_repo = project
5994            .as_ref()
5995            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5996            .unwrap_or(true);
5997
5998        const MAX_BRANCH_LEN: usize = 16;
5999        const MAX_REPO_LEN: usize = 16;
6000        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
6001        const MAX_SHORT_SHA_LEN: usize = 8;
6002        let branch_name = self
6003            .branch
6004            .as_ref()
6005            .map(|branch| branch.name().to_owned())
6006            .or_else(|| {
6007                self.head_commit.as_ref().map(|commit| {
6008                    commit
6009                        .sha
6010                        .chars()
6011                        .take(MAX_SHORT_SHA_LEN)
6012                        .collect::<String>()
6013                })
6014            })
6015            .unwrap_or_else(|| " (no branch)".to_owned());
6016        let show_separator = self.branch.is_some() || self.head_commit.is_some();
6017
6018        let active_repo_name = self.active_repository.clone();
6019
6020        let branch_actual_len = branch_name.len();
6021        let repo_actual_len = active_repo_name.len();
6022
6023        // ideally, show the whole branch and repo names but
6024        // when we can't, use a budget to allocate space between the two
6025        let (repo_display_len, branch_display_len) =
6026            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
6027                (repo_actual_len, branch_actual_len)
6028            } else if branch_actual_len <= MAX_BRANCH_LEN {
6029                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
6030                (repo_space, branch_actual_len)
6031            } else if repo_actual_len <= MAX_REPO_LEN {
6032                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
6033                (repo_actual_len, branch_space)
6034            } else {
6035                (MAX_REPO_LEN, MAX_BRANCH_LEN)
6036            };
6037
6038        let truncated_repo_name = if repo_actual_len <= repo_display_len {
6039            active_repo_name.to_string()
6040        } else {
6041            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
6042        };
6043
6044        let truncated_branch_name = if branch_actual_len <= branch_display_len {
6045            branch_name
6046        } else {
6047            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
6048        };
6049
6050        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
6051            .size(ButtonSize::None)
6052            .label_size(LabelSize::Small);
6053
6054        let repo_selector = PopoverMenu::new("repository-switcher")
6055            .menu({
6056                let project = project;
6057                move |window, cx| {
6058                    let project = project.clone()?;
6059                    Some(cx.new(|cx| RepositorySelector::new(project, rems(20.), window, cx)))
6060                }
6061            })
6062            .trigger_with_tooltip(
6063                repo_selector_trigger
6064                    .when(single_repo, |this| this.disabled(true).color(Color::Muted))
6065                    .truncate(true),
6066                move |_, cx| {
6067                    if single_repo {
6068                        cx.new(|_| Empty).into()
6069                    } else {
6070                        Tooltip::simple("Switch Active Repository", cx)
6071                    }
6072                },
6073            )
6074            .anchor(Corner::BottomLeft)
6075            .offset(gpui::Point {
6076                x: px(0.0),
6077                y: px(-2.0),
6078            })
6079            .into_any_element();
6080
6081        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
6082            .size(ButtonSize::None)
6083            .label_size(LabelSize::Small)
6084            .truncate(true)
6085            .on_click(|_, window, cx| {
6086                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
6087            });
6088
6089        let branch_selector = PopoverMenu::new("popover-button")
6090            .menu(move |window, cx| {
6091                let workspace = workspace.clone()?;
6092                let repo = repo.clone().flatten();
6093                Some(branch_picker::popover(workspace, false, repo, window, cx))
6094            })
6095            .trigger_with_tooltip(
6096                branch_selector_button,
6097                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
6098            )
6099            .anchor(Corner::BottomLeft)
6100            .offset(gpui::Point {
6101                x: px(0.0),
6102                y: px(-2.0),
6103            });
6104
6105        h_flex()
6106            .h(px(36.))
6107            .w_full()
6108            .px_2()
6109            .justify_between()
6110            .gap_1()
6111            .child(
6112                h_flex()
6113                    .flex_1()
6114                    .overflow_hidden()
6115                    .gap_px()
6116                    .child(
6117                        Icon::new(IconName::GitBranchAlt)
6118                            .size(IconSize::Small)
6119                            .color(if single_repo {
6120                                Color::Disabled
6121                            } else {
6122                                Color::Muted
6123                            }),
6124                    )
6125                    .child(repo_selector)
6126                    .when(show_separator, |this| {
6127                        this.child(
6128                            div()
6129                                .text_sm()
6130                                .text_color(cx.theme().colors().icon_muted.opacity(0.5))
6131                                .child("/"),
6132                        )
6133                    })
6134                    .child(branch_selector),
6135            )
6136            .children(if let Some(git_panel) = self.git_panel {
6137                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
6138            } else {
6139                None
6140            })
6141    }
6142}
6143
6144impl Component for PanelRepoFooter {
6145    fn scope() -> ComponentScope {
6146        ComponentScope::VersionControl
6147    }
6148
6149    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
6150        let unknown_upstream = None;
6151        let no_remote_upstream = Some(UpstreamTracking::Gone);
6152        let ahead_of_upstream = Some(
6153            UpstreamTrackingStatus {
6154                ahead: 2,
6155                behind: 0,
6156            }
6157            .into(),
6158        );
6159        let behind_upstream = Some(
6160            UpstreamTrackingStatus {
6161                ahead: 0,
6162                behind: 2,
6163            }
6164            .into(),
6165        );
6166        let ahead_and_behind_upstream = Some(
6167            UpstreamTrackingStatus {
6168                ahead: 3,
6169                behind: 1,
6170            }
6171            .into(),
6172        );
6173
6174        let not_ahead_or_behind_upstream = Some(
6175            UpstreamTrackingStatus {
6176                ahead: 0,
6177                behind: 0,
6178            }
6179            .into(),
6180        );
6181
6182        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
6183            Branch {
6184                is_head: true,
6185                ref_name: "some-branch".into(),
6186                upstream: upstream.map(|tracking| Upstream {
6187                    ref_name: "origin/some-branch".into(),
6188                    tracking,
6189                }),
6190                most_recent_commit: Some(CommitSummary {
6191                    sha: "abc123".into(),
6192                    subject: "Modify stuff".into(),
6193                    commit_timestamp: 1710932954,
6194                    author_name: "John Doe".into(),
6195                    has_parent: true,
6196                }),
6197            }
6198        }
6199
6200        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
6201            Branch {
6202                is_head: true,
6203                ref_name: branch_name.to_string().into(),
6204                upstream: upstream.map(|tracking| Upstream {
6205                    ref_name: format!("zed/{}", branch_name).into(),
6206                    tracking,
6207                }),
6208                most_recent_commit: Some(CommitSummary {
6209                    sha: "abc123".into(),
6210                    subject: "Modify stuff".into(),
6211                    commit_timestamp: 1710932954,
6212                    author_name: "John Doe".into(),
6213                    has_parent: true,
6214                }),
6215            }
6216        }
6217
6218        fn active_repository(id: usize) -> SharedString {
6219            format!("repo-{}", id).into()
6220        }
6221
6222        let example_width = px(340.);
6223        Some(
6224            v_flex()
6225                .gap_6()
6226                .w_full()
6227                .flex_none()
6228                .children(vec![
6229                    example_group_with_title(
6230                        "Action Button States",
6231                        vec![
6232                            single_example(
6233                                "No Branch",
6234                                div()
6235                                    .w(example_width)
6236                                    .overflow_hidden()
6237                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
6238                                    .into_any_element(),
6239                            ),
6240                            single_example(
6241                                "Remote status unknown",
6242                                div()
6243                                    .w(example_width)
6244                                    .overflow_hidden()
6245                                    .child(PanelRepoFooter::new_preview(
6246                                        active_repository(2),
6247                                        Some(branch(unknown_upstream)),
6248                                    ))
6249                                    .into_any_element(),
6250                            ),
6251                            single_example(
6252                                "No Remote Upstream",
6253                                div()
6254                                    .w(example_width)
6255                                    .overflow_hidden()
6256                                    .child(PanelRepoFooter::new_preview(
6257                                        active_repository(3),
6258                                        Some(branch(no_remote_upstream)),
6259                                    ))
6260                                    .into_any_element(),
6261                            ),
6262                            single_example(
6263                                "Not Ahead or Behind",
6264                                div()
6265                                    .w(example_width)
6266                                    .overflow_hidden()
6267                                    .child(PanelRepoFooter::new_preview(
6268                                        active_repository(4),
6269                                        Some(branch(not_ahead_or_behind_upstream)),
6270                                    ))
6271                                    .into_any_element(),
6272                            ),
6273                            single_example(
6274                                "Behind remote",
6275                                div()
6276                                    .w(example_width)
6277                                    .overflow_hidden()
6278                                    .child(PanelRepoFooter::new_preview(
6279                                        active_repository(5),
6280                                        Some(branch(behind_upstream)),
6281                                    ))
6282                                    .into_any_element(),
6283                            ),
6284                            single_example(
6285                                "Ahead of remote",
6286                                div()
6287                                    .w(example_width)
6288                                    .overflow_hidden()
6289                                    .child(PanelRepoFooter::new_preview(
6290                                        active_repository(6),
6291                                        Some(branch(ahead_of_upstream)),
6292                                    ))
6293                                    .into_any_element(),
6294                            ),
6295                            single_example(
6296                                "Ahead and behind remote",
6297                                div()
6298                                    .w(example_width)
6299                                    .overflow_hidden()
6300                                    .child(PanelRepoFooter::new_preview(
6301                                        active_repository(7),
6302                                        Some(branch(ahead_and_behind_upstream)),
6303                                    ))
6304                                    .into_any_element(),
6305                            ),
6306                        ],
6307                    )
6308                    .grow()
6309                    .vertical(),
6310                ])
6311                .children(vec![
6312                    example_group_with_title(
6313                        "Labels",
6314                        vec![
6315                            single_example(
6316                                "Short Branch & Repo",
6317                                div()
6318                                    .w(example_width)
6319                                    .overflow_hidden()
6320                                    .child(PanelRepoFooter::new_preview(
6321                                        SharedString::from("zed"),
6322                                        Some(custom("main", behind_upstream)),
6323                                    ))
6324                                    .into_any_element(),
6325                            ),
6326                            single_example(
6327                                "Long Branch",
6328                                div()
6329                                    .w(example_width)
6330                                    .overflow_hidden()
6331                                    .child(PanelRepoFooter::new_preview(
6332                                        SharedString::from("zed"),
6333                                        Some(custom(
6334                                            "redesign-and-update-git-ui-list-entry-style",
6335                                            behind_upstream,
6336                                        )),
6337                                    ))
6338                                    .into_any_element(),
6339                            ),
6340                            single_example(
6341                                "Long Repo",
6342                                div()
6343                                    .w(example_width)
6344                                    .overflow_hidden()
6345                                    .child(PanelRepoFooter::new_preview(
6346                                        SharedString::from("zed-industries-community-examples"),
6347                                        Some(custom("gpui", ahead_of_upstream)),
6348                                    ))
6349                                    .into_any_element(),
6350                            ),
6351                            single_example(
6352                                "Long Repo & Branch",
6353                                div()
6354                                    .w(example_width)
6355                                    .overflow_hidden()
6356                                    .child(PanelRepoFooter::new_preview(
6357                                        SharedString::from("zed-industries-community-examples"),
6358                                        Some(custom(
6359                                            "redesign-and-update-git-ui-list-entry-style",
6360                                            behind_upstream,
6361                                        )),
6362                                    ))
6363                                    .into_any_element(),
6364                            ),
6365                            single_example(
6366                                "Uppercase Repo",
6367                                div()
6368                                    .w(example_width)
6369                                    .overflow_hidden()
6370                                    .child(PanelRepoFooter::new_preview(
6371                                        SharedString::from("LICENSES"),
6372                                        Some(custom("main", ahead_of_upstream)),
6373                                    ))
6374                                    .into_any_element(),
6375                            ),
6376                            single_example(
6377                                "Uppercase Branch",
6378                                div()
6379                                    .w(example_width)
6380                                    .overflow_hidden()
6381                                    .child(PanelRepoFooter::new_preview(
6382                                        SharedString::from("zed"),
6383                                        Some(custom("update-README", behind_upstream)),
6384                                    ))
6385                                    .into_any_element(),
6386                            ),
6387                        ],
6388                    )
6389                    .grow()
6390                    .vertical(),
6391                ])
6392                .into_any_element(),
6393        )
6394    }
6395}
6396
6397fn open_output(
6398    operation: impl Into<SharedString>,
6399    workspace: &mut Workspace,
6400    output: &str,
6401    window: &mut Window,
6402    cx: &mut Context<Workspace>,
6403) {
6404    let operation = operation.into();
6405    let buffer = cx.new(|cx| Buffer::local(output, cx));
6406    buffer.update(cx, |buffer, cx| {
6407        buffer.set_capability(language::Capability::ReadOnly, cx);
6408    });
6409    let editor = cx.new(|cx| {
6410        let mut editor = Editor::for_buffer(buffer, None, window, cx);
6411        editor.buffer().update(cx, |buffer, cx| {
6412            buffer.set_title(format!("Output from git {operation}"), cx);
6413        });
6414        editor.set_read_only(true);
6415        editor
6416    });
6417
6418    workspace.add_item_to_center(Box::new(editor), window, cx);
6419}
6420
6421pub(crate) fn show_error_toast(
6422    workspace: Entity<Workspace>,
6423    action: impl Into<SharedString>,
6424    e: anyhow::Error,
6425    cx: &mut App,
6426) {
6427    let action = action.into();
6428    let message = format_git_error_toast_message(&e);
6429    if message
6430        .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6431        .next()
6432        .is_some()
6433    { // Hide the cancelled by user message
6434    } else {
6435        workspace.update(cx, |workspace, cx| {
6436            let workspace_weak = cx.weak_entity();
6437            let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6438                this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
6439                    .action("View Log", move |window, cx| {
6440                        let message = message.clone();
6441                        let action = action.clone();
6442                        workspace_weak
6443                            .update(cx, move |workspace, cx| {
6444                                open_output(action, workspace, &message, window, cx)
6445                            })
6446                            .ok();
6447                    })
6448            });
6449            workspace.toggle_status_toast(toast, cx)
6450        });
6451    }
6452}
6453
6454fn rpc_error_raw_message_from_chain(error: &anyhow::Error) -> Option<&str> {
6455    error
6456        .chain()
6457        .find_map(|cause| cause.downcast_ref::<RpcError>().map(RpcError::raw_message))
6458}
6459
6460fn format_git_error_toast_message(error: &anyhow::Error) -> String {
6461    if let Some(message) = rpc_error_raw_message_from_chain(error) {
6462        message.trim().to_string()
6463    } else {
6464        error.to_string().trim().to_string()
6465    }
6466}
6467
6468#[cfg(test)]
6469mod tests {
6470    use git::{
6471        repository::repo_path,
6472        status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6473    };
6474    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext, px};
6475    use indoc::indoc;
6476    use project::FakeFs;
6477    use serde_json::json;
6478    use settings::SettingsStore;
6479    use theme::LoadThemes;
6480    use util::path;
6481    use util::rel_path::rel_path;
6482
6483    use workspace::MultiWorkspace;
6484
6485    use super::*;
6486
6487    fn init_test(cx: &mut gpui::TestAppContext) {
6488        zlog::init_test();
6489
6490        cx.update(|cx| {
6491            let settings_store = SettingsStore::test(cx);
6492            cx.set_global(settings_store);
6493            theme_settings::init(LoadThemes::JustBase, cx);
6494            editor::init(cx);
6495            crate::init(cx);
6496        });
6497    }
6498
6499    #[test]
6500    fn test_format_git_error_toast_message_prefers_raw_rpc_message() {
6501        let rpc_error = RpcError::from_proto(
6502            &proto::Error {
6503                message:
6504                    "Your local changes to the following files would be overwritten by merge\n"
6505                        .to_string(),
6506                code: proto::ErrorCode::Internal as i32,
6507                tags: Default::default(),
6508            },
6509            "Pull",
6510        );
6511
6512        let message = format_git_error_toast_message(&rpc_error);
6513        assert_eq!(
6514            message,
6515            "Your local changes to the following files would be overwritten by merge"
6516        );
6517    }
6518
6519    #[test]
6520    fn test_format_git_error_toast_message_prefers_raw_rpc_message_when_wrapped() {
6521        let rpc_error = RpcError::from_proto(
6522            &proto::Error {
6523                message:
6524                    "Your local changes to the following files would be overwritten by merge\n"
6525                        .to_string(),
6526                code: proto::ErrorCode::Internal as i32,
6527                tags: Default::default(),
6528            },
6529            "Pull",
6530        );
6531        let wrapped = rpc_error.context("sending pull request");
6532
6533        let message = format_git_error_toast_message(&wrapped);
6534        assert_eq!(
6535            message,
6536            "Your local changes to the following files would be overwritten by merge"
6537        );
6538    }
6539
6540    #[gpui::test]
6541    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6542        init_test(cx);
6543        let fs = FakeFs::new(cx.background_executor.clone());
6544        fs.insert_tree(
6545            "/root",
6546            json!({
6547                "zed": {
6548                    ".git": {},
6549                    "crates": {
6550                        "gpui": {
6551                            "gpui.rs": "fn main() {}"
6552                        },
6553                        "util": {
6554                            "util.rs": "fn do_it() {}"
6555                        }
6556                    }
6557                },
6558            }),
6559        )
6560        .await;
6561
6562        fs.set_status_for_repo(
6563            Path::new(path!("/root/zed/.git")),
6564            &[
6565                ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6566                ("crates/util/util.rs", StatusCode::Modified.worktree()),
6567            ],
6568        );
6569
6570        let project =
6571            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6572        let window_handle =
6573            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6574        let workspace = window_handle
6575            .read_with(cx, |mw, _| mw.workspace().clone())
6576            .unwrap();
6577        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6578
6579        cx.read(|cx| {
6580            project
6581                .read(cx)
6582                .worktrees(cx)
6583                .next()
6584                .unwrap()
6585                .read(cx)
6586                .as_local()
6587                .unwrap()
6588                .scan_complete()
6589        })
6590        .await;
6591
6592        cx.executor().run_until_parked();
6593
6594        let panel = workspace.update_in(cx, GitPanel::new);
6595
6596        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6597            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6598        });
6599        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6600        handle.await;
6601
6602        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6603        pretty_assertions::assert_eq!(
6604            entries,
6605            [
6606                GitListEntry::Header(GitHeaderEntry {
6607                    header: Section::Tracked
6608                }),
6609                GitListEntry::Status(GitStatusEntry {
6610                    repo_path: repo_path("crates/gpui/gpui.rs"),
6611                    status: StatusCode::Modified.worktree(),
6612                    staging: StageStatus::Unstaged,
6613                    diff_stat: Some(DiffStat {
6614                        added: 1,
6615                        deleted: 1,
6616                    }),
6617                }),
6618                GitListEntry::Status(GitStatusEntry {
6619                    repo_path: repo_path("crates/util/util.rs"),
6620                    status: StatusCode::Modified.worktree(),
6621                    staging: StageStatus::Unstaged,
6622                    diff_stat: Some(DiffStat {
6623                        added: 1,
6624                        deleted: 1,
6625                    }),
6626                },),
6627            ],
6628        );
6629
6630        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6631            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6632        });
6633        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6634        handle.await;
6635        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6636        pretty_assertions::assert_eq!(
6637            entries,
6638            [
6639                GitListEntry::Header(GitHeaderEntry {
6640                    header: Section::Tracked
6641                }),
6642                GitListEntry::Status(GitStatusEntry {
6643                    repo_path: repo_path("crates/gpui/gpui.rs"),
6644                    status: StatusCode::Modified.worktree(),
6645                    staging: StageStatus::Unstaged,
6646                    diff_stat: Some(DiffStat {
6647                        added: 1,
6648                        deleted: 1,
6649                    }),
6650                }),
6651                GitListEntry::Status(GitStatusEntry {
6652                    repo_path: repo_path("crates/util/util.rs"),
6653                    status: StatusCode::Modified.worktree(),
6654                    staging: StageStatus::Unstaged,
6655                    diff_stat: Some(DiffStat {
6656                        added: 1,
6657                        deleted: 1,
6658                    }),
6659                },),
6660            ],
6661        );
6662    }
6663
6664    #[gpui::test]
6665    async fn test_bulk_staging(cx: &mut TestAppContext) {
6666        use GitListEntry::*;
6667
6668        init_test(cx);
6669        let fs = FakeFs::new(cx.background_executor.clone());
6670        fs.insert_tree(
6671            "/root",
6672            json!({
6673                "project": {
6674                    ".git": {},
6675                    "src": {
6676                        "main.rs": "fn main() {}",
6677                        "lib.rs": "pub fn hello() {}",
6678                        "utils.rs": "pub fn util() {}"
6679                    },
6680                    "tests": {
6681                        "test.rs": "fn test() {}"
6682                    },
6683                    "new_file.txt": "new content",
6684                    "another_new.rs": "// new file",
6685                    "conflict.txt": "conflicted content"
6686                }
6687            }),
6688        )
6689        .await;
6690
6691        fs.set_status_for_repo(
6692            Path::new(path!("/root/project/.git")),
6693            &[
6694                ("src/main.rs", StatusCode::Modified.worktree()),
6695                ("src/lib.rs", StatusCode::Modified.worktree()),
6696                ("tests/test.rs", StatusCode::Modified.worktree()),
6697                ("new_file.txt", FileStatus::Untracked),
6698                ("another_new.rs", FileStatus::Untracked),
6699                ("src/utils.rs", FileStatus::Untracked),
6700                (
6701                    "conflict.txt",
6702                    UnmergedStatus {
6703                        first_head: UnmergedStatusCode::Updated,
6704                        second_head: UnmergedStatusCode::Updated,
6705                    }
6706                    .into(),
6707                ),
6708            ],
6709        );
6710
6711        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6712        let window_handle =
6713            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6714        let workspace = window_handle
6715            .read_with(cx, |mw, _| mw.workspace().clone())
6716            .unwrap();
6717        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6718
6719        cx.read(|cx| {
6720            project
6721                .read(cx)
6722                .worktrees(cx)
6723                .next()
6724                .unwrap()
6725                .read(cx)
6726                .as_local()
6727                .unwrap()
6728                .scan_complete()
6729        })
6730        .await;
6731
6732        cx.executor().run_until_parked();
6733
6734        let panel = workspace.update_in(cx, GitPanel::new);
6735
6736        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6737            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6738        });
6739        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6740        handle.await;
6741
6742        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6743        #[rustfmt::skip]
6744        pretty_assertions::assert_matches!(
6745            entries.as_slice(),
6746            &[
6747                Header(GitHeaderEntry { header: Section::Conflict }),
6748                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6749                Header(GitHeaderEntry { header: Section::Tracked }),
6750                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6751                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6752                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6753                Header(GitHeaderEntry { header: Section::New }),
6754                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6755                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6756                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6757            ],
6758        );
6759
6760        let second_status_entry = entries[3].clone();
6761        panel.update_in(cx, |panel, window, cx| {
6762            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6763        });
6764
6765        panel.update_in(cx, |panel, window, cx| {
6766            panel.selected_entry = Some(7);
6767            panel.stage_range(&git::StageRange, window, cx);
6768        });
6769
6770        cx.read(|cx| {
6771            project
6772                .read(cx)
6773                .worktrees(cx)
6774                .next()
6775                .unwrap()
6776                .read(cx)
6777                .as_local()
6778                .unwrap()
6779                .scan_complete()
6780        })
6781        .await;
6782
6783        cx.executor().run_until_parked();
6784
6785        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6786            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6787        });
6788        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6789        handle.await;
6790
6791        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6792        #[rustfmt::skip]
6793        pretty_assertions::assert_matches!(
6794            entries.as_slice(),
6795            &[
6796                Header(GitHeaderEntry { header: Section::Conflict }),
6797                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6798                Header(GitHeaderEntry { header: Section::Tracked }),
6799                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6800                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6801                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6802                Header(GitHeaderEntry { header: Section::New }),
6803                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6804                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6805                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6806            ],
6807        );
6808
6809        let third_status_entry = entries[4].clone();
6810        panel.update_in(cx, |panel, window, cx| {
6811            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6812        });
6813
6814        panel.update_in(cx, |panel, window, cx| {
6815            panel.selected_entry = Some(9);
6816            panel.stage_range(&git::StageRange, window, cx);
6817        });
6818
6819        cx.read(|cx| {
6820            project
6821                .read(cx)
6822                .worktrees(cx)
6823                .next()
6824                .unwrap()
6825                .read(cx)
6826                .as_local()
6827                .unwrap()
6828                .scan_complete()
6829        })
6830        .await;
6831
6832        cx.executor().run_until_parked();
6833
6834        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6835            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6836        });
6837        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6838        handle.await;
6839
6840        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6841        #[rustfmt::skip]
6842        pretty_assertions::assert_matches!(
6843            entries.as_slice(),
6844            &[
6845                Header(GitHeaderEntry { header: Section::Conflict }),
6846                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6847                Header(GitHeaderEntry { header: Section::Tracked }),
6848                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6849                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6850                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6851                Header(GitHeaderEntry { header: Section::New }),
6852                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6853                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6854                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6855            ],
6856        );
6857    }
6858
6859    #[gpui::test]
6860    async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6861        use GitListEntry::*;
6862
6863        init_test(cx);
6864        let fs = FakeFs::new(cx.background_executor.clone());
6865        fs.insert_tree(
6866            "/root",
6867            json!({
6868                "project": {
6869                    ".git": {},
6870                    "src": {
6871                        "main.rs": "fn main() {}",
6872                        "lib.rs": "pub fn hello() {}",
6873                        "utils.rs": "pub fn util() {}"
6874                    },
6875                    "tests": {
6876                        "test.rs": "fn test() {}"
6877                    },
6878                    "new_file.txt": "new content",
6879                    "another_new.rs": "// new file",
6880                    "conflict.txt": "conflicted content"
6881                }
6882            }),
6883        )
6884        .await;
6885
6886        fs.set_status_for_repo(
6887            Path::new(path!("/root/project/.git")),
6888            &[
6889                ("src/main.rs", StatusCode::Modified.worktree()),
6890                ("src/lib.rs", StatusCode::Modified.worktree()),
6891                ("tests/test.rs", StatusCode::Modified.worktree()),
6892                ("new_file.txt", FileStatus::Untracked),
6893                ("another_new.rs", FileStatus::Untracked),
6894                ("src/utils.rs", FileStatus::Untracked),
6895                (
6896                    "conflict.txt",
6897                    UnmergedStatus {
6898                        first_head: UnmergedStatusCode::Updated,
6899                        second_head: UnmergedStatusCode::Updated,
6900                    }
6901                    .into(),
6902                ),
6903            ],
6904        );
6905
6906        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6907        let window_handle =
6908            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6909        let workspace = window_handle
6910            .read_with(cx, |mw, _| mw.workspace().clone())
6911            .unwrap();
6912        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6913
6914        cx.read(|cx| {
6915            project
6916                .read(cx)
6917                .worktrees(cx)
6918                .next()
6919                .unwrap()
6920                .read(cx)
6921                .as_local()
6922                .unwrap()
6923                .scan_complete()
6924        })
6925        .await;
6926
6927        cx.executor().run_until_parked();
6928
6929        let panel = workspace.update_in(cx, GitPanel::new);
6930
6931        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6932            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6933        });
6934        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6935        handle.await;
6936
6937        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6938        #[rustfmt::skip]
6939        pretty_assertions::assert_matches!(
6940            entries.as_slice(),
6941            &[
6942                Header(GitHeaderEntry { header: Section::Conflict }),
6943                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6944                Header(GitHeaderEntry { header: Section::Tracked }),
6945                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6946                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6947                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6948                Header(GitHeaderEntry { header: Section::New }),
6949                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6950                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6951                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6952            ],
6953        );
6954
6955        assert_entry_paths(
6956            &entries,
6957            &[
6958                None,
6959                Some("conflict.txt"),
6960                None,
6961                Some("src/lib.rs"),
6962                Some("src/main.rs"),
6963                Some("tests/test.rs"),
6964                None,
6965                Some("another_new.rs"),
6966                Some("new_file.txt"),
6967                Some("src/utils.rs"),
6968            ],
6969        );
6970
6971        let second_status_entry = entries[3].clone();
6972        panel.update_in(cx, |panel, window, cx| {
6973            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6974        });
6975
6976        cx.update(|_window, cx| {
6977            SettingsStore::update_global(cx, |store, cx| {
6978                store.update_user_settings(cx, |settings| {
6979                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6980                })
6981            });
6982        });
6983
6984        panel.update_in(cx, |panel, window, cx| {
6985            panel.selected_entry = Some(7);
6986            panel.stage_range(&git::StageRange, window, cx);
6987        });
6988
6989        cx.read(|cx| {
6990            project
6991                .read(cx)
6992                .worktrees(cx)
6993                .next()
6994                .unwrap()
6995                .read(cx)
6996                .as_local()
6997                .unwrap()
6998                .scan_complete()
6999        })
7000        .await;
7001
7002        cx.executor().run_until_parked();
7003
7004        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7005            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7006        });
7007        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7008        handle.await;
7009
7010        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7011        #[rustfmt::skip]
7012        pretty_assertions::assert_matches!(
7013            entries.as_slice(),
7014            &[
7015                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7016                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7017                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7018                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7019                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7020                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7021                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7022            ],
7023        );
7024
7025        assert_entry_paths(
7026            &entries,
7027            &[
7028                Some("another_new.rs"),
7029                Some("conflict.txt"),
7030                Some("new_file.txt"),
7031                Some("src/lib.rs"),
7032                Some("src/main.rs"),
7033                Some("src/utils.rs"),
7034                Some("tests/test.rs"),
7035            ],
7036        );
7037
7038        let third_status_entry = entries[4].clone();
7039        panel.update_in(cx, |panel, window, cx| {
7040            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
7041        });
7042
7043        panel.update_in(cx, |panel, window, cx| {
7044            panel.selected_entry = Some(9);
7045            panel.stage_range(&git::StageRange, window, cx);
7046        });
7047
7048        cx.read(|cx| {
7049            project
7050                .read(cx)
7051                .worktrees(cx)
7052                .next()
7053                .unwrap()
7054                .read(cx)
7055                .as_local()
7056                .unwrap()
7057                .scan_complete()
7058        })
7059        .await;
7060
7061        cx.executor().run_until_parked();
7062
7063        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7064            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7065        });
7066        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7067        handle.await;
7068
7069        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7070        #[rustfmt::skip]
7071        pretty_assertions::assert_matches!(
7072            entries.as_slice(),
7073            &[
7074                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7075                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7076                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7077                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7078                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7079                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7080                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7081            ],
7082        );
7083
7084        assert_entry_paths(
7085            &entries,
7086            &[
7087                Some("another_new.rs"),
7088                Some("conflict.txt"),
7089                Some("new_file.txt"),
7090                Some("src/lib.rs"),
7091                Some("src/main.rs"),
7092                Some("src/utils.rs"),
7093                Some("tests/test.rs"),
7094            ],
7095        );
7096    }
7097
7098    #[gpui::test]
7099    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
7100        init_test(cx);
7101        let fs = FakeFs::new(cx.background_executor.clone());
7102        fs.insert_tree(
7103            "/root",
7104            json!({
7105                "project": {
7106                    ".git": {},
7107                    "src": {
7108                        "main.rs": "fn main() {}"
7109                    }
7110                }
7111            }),
7112        )
7113        .await;
7114
7115        fs.set_status_for_repo(
7116            Path::new(path!("/root/project/.git")),
7117            &[("src/main.rs", StatusCode::Modified.worktree())],
7118        );
7119
7120        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7121        let window_handle =
7122            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7123        let workspace = window_handle
7124            .read_with(cx, |mw, _| mw.workspace().clone())
7125            .unwrap();
7126        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7127
7128        let panel = workspace.update_in(cx, GitPanel::new);
7129
7130        // Test: User has commit message, enables amend (saves message), then disables (restores message)
7131        panel.update(cx, |panel, cx| {
7132            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7133                let start = buffer.anchor_before(0);
7134                let end = buffer.anchor_after(buffer.len());
7135                buffer.edit([(start..end, "Initial commit message")], None, cx);
7136            });
7137
7138            panel.set_amend_pending(true, cx);
7139            assert!(panel.original_commit_message.is_some());
7140
7141            panel.set_amend_pending(false, cx);
7142            let current_message = panel.commit_message_buffer(cx).read(cx).text();
7143            assert_eq!(current_message, "Initial commit message");
7144            assert!(panel.original_commit_message.is_none());
7145        });
7146
7147        // Test: User has empty commit message, enables amend, then disables (clears message)
7148        panel.update(cx, |panel, cx| {
7149            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7150                let start = buffer.anchor_before(0);
7151                let end = buffer.anchor_after(buffer.len());
7152                buffer.edit([(start..end, "")], None, cx);
7153            });
7154
7155            panel.set_amend_pending(true, cx);
7156            assert!(panel.original_commit_message.is_none());
7157
7158            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7159                let start = buffer.anchor_before(0);
7160                let end = buffer.anchor_after(buffer.len());
7161                buffer.edit([(start..end, "Previous commit message")], None, cx);
7162            });
7163
7164            panel.set_amend_pending(false, cx);
7165            let current_message = panel.commit_message_buffer(cx).read(cx).text();
7166            assert_eq!(current_message, "");
7167        });
7168    }
7169
7170    #[gpui::test]
7171    async fn test_amend(cx: &mut TestAppContext) {
7172        init_test(cx);
7173        let fs = FakeFs::new(cx.background_executor.clone());
7174        fs.insert_tree(
7175            "/root",
7176            json!({
7177                "project": {
7178                    ".git": {},
7179                    "src": {
7180                        "main.rs": "fn main() {}"
7181                    }
7182                }
7183            }),
7184        )
7185        .await;
7186
7187        fs.set_status_for_repo(
7188            Path::new(path!("/root/project/.git")),
7189            &[("src/main.rs", StatusCode::Modified.worktree())],
7190        );
7191
7192        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7193        let window_handle =
7194            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7195        let workspace = window_handle
7196            .read_with(cx, |mw, _| mw.workspace().clone())
7197            .unwrap();
7198        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7199
7200        // Wait for the project scanning to finish so that `head_commit(cx)` is
7201        // actually set, otherwise no head commit would be available from which
7202        // to fetch the latest commit message from.
7203        cx.executor().run_until_parked();
7204
7205        let panel = workspace.update_in(cx, GitPanel::new);
7206        panel.read_with(cx, |panel, cx| {
7207            assert!(panel.active_repository.is_some());
7208            assert!(panel.head_commit(cx).is_some());
7209        });
7210
7211        panel.update_in(cx, |panel, window, cx| {
7212            // Update the commit editor's message to ensure that its contents
7213            // are later restored, after amending is finished.
7214            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7215                buffer.set_text("refactor: update main.rs", cx);
7216            });
7217
7218            // Start amending the previous commit.
7219            panel.focus_editor(&Default::default(), window, cx);
7220            panel.on_amend(&Amend, window, cx);
7221        });
7222
7223        // Since `GitPanel.amend` attempts to fetch the latest commit message in
7224        // a background task, we need to wait for it to complete before being
7225        // able to assert that the commit message editor's state has been
7226        // updated.
7227        cx.run_until_parked();
7228
7229        panel.update_in(cx, |panel, window, cx| {
7230            assert_eq!(
7231                panel.commit_message_buffer(cx).read(cx).text(),
7232                "initial commit"
7233            );
7234            assert_eq!(
7235                panel.original_commit_message,
7236                Some("refactor: update main.rs".to_string())
7237            );
7238
7239            // Finish amending the previous commit.
7240            panel.focus_editor(&Default::default(), window, cx);
7241            panel.on_amend(&Amend, window, cx);
7242        });
7243
7244        // Since the actual commit logic is run in a background task, we need to
7245        // await its completion to actually ensure that the commit message
7246        // editor's contents are set to the original message and haven't been
7247        // cleared.
7248        cx.run_until_parked();
7249
7250        panel.update_in(cx, |panel, _window, cx| {
7251            // After amending, the commit editor's message should be restored to
7252            // the original message.
7253            assert_eq!(
7254                panel.commit_message_buffer(cx).read(cx).text(),
7255                "refactor: update main.rs"
7256            );
7257            assert!(panel.original_commit_message.is_none());
7258        });
7259    }
7260
7261    #[gpui::test]
7262    async fn test_open_diff(cx: &mut TestAppContext) {
7263        init_test(cx);
7264
7265        let fs = FakeFs::new(cx.background_executor.clone());
7266        fs.insert_tree(
7267            path!("/project"),
7268            json!({
7269                ".git": {},
7270                "tracked": "tracked\n",
7271                "untracked": "\n",
7272            }),
7273        )
7274        .await;
7275
7276        fs.set_head_and_index_for_repo(
7277            path!("/project/.git").as_ref(),
7278            &[("tracked", "old tracked\n".into())],
7279        );
7280
7281        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7282        let window_handle =
7283            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7284        let workspace = window_handle
7285            .read_with(cx, |mw, _| mw.workspace().clone())
7286            .unwrap();
7287        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7288        let panel = workspace.update_in(cx, GitPanel::new);
7289
7290        // Enable the `sort_by_path` setting and wait for entries to be updated,
7291        // as there should no longer be separators between Tracked and Untracked
7292        // files.
7293        cx.update(|_window, cx| {
7294            SettingsStore::update_global(cx, |store, cx| {
7295                store.update_user_settings(cx, |settings| {
7296                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7297                })
7298            });
7299        });
7300
7301        cx.update_window_entity(&panel, |panel, _, _| {
7302            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7303        })
7304        .await;
7305
7306        // Confirm that `Open Diff` still works for the untracked file, updating
7307        // the Project Diff's active path.
7308        panel.update_in(cx, |panel, window, cx| {
7309            panel.selected_entry = Some(1);
7310            panel.open_diff(&menu::Confirm, window, cx);
7311        });
7312        cx.run_until_parked();
7313
7314        workspace.update_in(cx, |workspace, _window, cx| {
7315            let active_path = workspace
7316                .item_of_type::<ProjectDiff>(cx)
7317                .expect("ProjectDiff should exist")
7318                .read(cx)
7319                .active_path(cx)
7320                .expect("active_path should exist");
7321
7322            assert_eq!(active_path.path, rel_path("untracked").into_arc());
7323        });
7324    }
7325
7326    #[gpui::test]
7327    async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
7328        cx: &mut TestAppContext,
7329    ) {
7330        init_test(cx);
7331
7332        let fs = FakeFs::new(cx.background_executor.clone());
7333        fs.insert_tree(
7334            path!("/project"),
7335            json!({
7336                ".git": {},
7337                "src": {
7338                    "a": {
7339                        "foo.rs": "fn foo() {}",
7340                    },
7341                    "b": {
7342                        "bar.rs": "fn bar() {}",
7343                    },
7344                },
7345            }),
7346        )
7347        .await;
7348
7349        fs.set_status_for_repo(
7350            path!("/project/.git").as_ref(),
7351            &[
7352                ("src/a/foo.rs", StatusCode::Modified.worktree()),
7353                ("src/b/bar.rs", StatusCode::Modified.worktree()),
7354            ],
7355        );
7356
7357        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7358        let window_handle =
7359            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7360        let workspace = window_handle
7361            .read_with(cx, |mw, _| mw.workspace().clone())
7362            .unwrap();
7363        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7364
7365        cx.read(|cx| {
7366            project
7367                .read(cx)
7368                .worktrees(cx)
7369                .next()
7370                .unwrap()
7371                .read(cx)
7372                .as_local()
7373                .unwrap()
7374                .scan_complete()
7375        })
7376        .await;
7377
7378        cx.executor().run_until_parked();
7379
7380        cx.update(|_window, cx| {
7381            SettingsStore::update_global(cx, |store, cx| {
7382                store.update_user_settings(cx, |settings| {
7383                    settings.git_panel.get_or_insert_default().tree_view = Some(true);
7384                })
7385            });
7386        });
7387
7388        let panel = workspace.update_in(cx, GitPanel::new);
7389
7390        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7391            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7392        });
7393        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7394        handle.await;
7395
7396        let src_key = panel.read_with(cx, |panel, _| {
7397            panel
7398                .entries
7399                .iter()
7400                .find_map(|entry| match entry {
7401                    GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7402                        Some(dir.key.clone())
7403                    }
7404                    _ => None,
7405                })
7406                .expect("src directory should exist in tree view")
7407        });
7408
7409        panel.update_in(cx, |panel, window, cx| {
7410            panel.toggle_directory(&src_key, window, cx);
7411        });
7412
7413        panel.read_with(cx, |panel, _| {
7414            let state = panel
7415                .view_mode
7416                .tree_state()
7417                .expect("tree view state should exist");
7418            assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7419        });
7420
7421        let worktree_id =
7422            cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7423        let project_path = ProjectPath {
7424            worktree_id,
7425            path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7426        };
7427
7428        panel.update_in(cx, |panel, window, cx| {
7429            panel.select_entry_by_path(project_path, window, cx);
7430        });
7431
7432        panel.read_with(cx, |panel, _| {
7433            let state = panel
7434                .view_mode
7435                .tree_state()
7436                .expect("tree view state should exist");
7437            assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7438
7439            let selected_ix = panel.selected_entry.expect("selection should be set");
7440            assert!(state.logical_indices.contains(&selected_ix));
7441
7442            let selected_entry = panel
7443                .entries
7444                .get(selected_ix)
7445                .and_then(|entry| entry.status_entry())
7446                .expect("selected entry should be a status entry");
7447            assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7448        });
7449    }
7450
7451    #[gpui::test]
7452    async fn test_tree_view_select_next_at_last_visible_collapsed_directory(
7453        cx: &mut TestAppContext,
7454    ) {
7455        init_test(cx);
7456
7457        let fs = FakeFs::new(cx.background_executor.clone());
7458        fs.insert_tree(
7459            path!("/project"),
7460            json!({
7461                ".git": {},
7462                "bar": {
7463                    "bar1.py": "print('bar1')",
7464                    "bar2.py": "print('bar2')",
7465                },
7466                "foo": {
7467                    "foo1.py": "print('foo1')",
7468                    "foo2.py": "print('foo2')",
7469                },
7470                "foobar.py": "print('foobar')",
7471            }),
7472        )
7473        .await;
7474
7475        fs.set_status_for_repo(
7476            path!("/project/.git").as_ref(),
7477            &[
7478                ("bar/bar1.py", StatusCode::Modified.worktree()),
7479                ("bar/bar2.py", StatusCode::Modified.worktree()),
7480                ("foo/foo1.py", StatusCode::Modified.worktree()),
7481                ("foo/foo2.py", StatusCode::Modified.worktree()),
7482                ("foobar.py", FileStatus::Untracked),
7483            ],
7484        );
7485
7486        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7487        let window_handle =
7488            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7489        let workspace = window_handle
7490            .read_with(cx, |mw, _| mw.workspace().clone())
7491            .unwrap();
7492        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7493
7494        cx.read(|cx| {
7495            project
7496                .read(cx)
7497                .worktrees(cx)
7498                .next()
7499                .unwrap()
7500                .read(cx)
7501                .as_local()
7502                .unwrap()
7503                .scan_complete()
7504        })
7505        .await;
7506
7507        cx.executor().run_until_parked();
7508        cx.update(|_window, cx| {
7509            SettingsStore::update_global(cx, |store, cx| {
7510                store.update_user_settings(cx, |settings| {
7511                    settings.git_panel.get_or_insert_default().tree_view = Some(true);
7512                })
7513            });
7514        });
7515
7516        let panel = workspace.update_in(cx, GitPanel::new);
7517        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7518            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7519        });
7520
7521        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7522        handle.await;
7523
7524        let foo_key = panel.read_with(cx, |panel, _| {
7525            panel
7526                .entries
7527                .iter()
7528                .find_map(|entry| match entry {
7529                    GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => {
7530                        Some(dir.key.clone())
7531                    }
7532                    _ => None,
7533                })
7534                .expect("foo directory should exist in tree view")
7535        });
7536
7537        panel.update_in(cx, |panel, window, cx| {
7538            panel.toggle_directory(&foo_key, window, cx);
7539        });
7540
7541        let foo_idx = panel.read_with(cx, |panel, _| {
7542            let state = panel
7543                .view_mode
7544                .tree_state()
7545                .expect("tree view state should exist");
7546            assert_eq!(state.expanded_dirs.get(&foo_key).copied(), Some(false));
7547
7548            let foo_idx = panel
7549                .entries
7550                .iter()
7551                .enumerate()
7552                .find_map(|(index, entry)| match entry {
7553                    GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => Some(index),
7554                    _ => None,
7555                })
7556                .expect("foo directory should exist in tree view");
7557
7558            let foo_logical_idx = state
7559                .logical_indices
7560                .iter()
7561                .position(|&index| index == foo_idx)
7562                .expect("foo directory should be visible");
7563            let next_logical_idx = state.logical_indices[foo_logical_idx + 1];
7564            assert!(matches!(
7565                panel.entries.get(next_logical_idx),
7566                Some(GitListEntry::Header(GitHeaderEntry {
7567                    header: Section::New
7568                }))
7569            ));
7570
7571            foo_idx
7572        });
7573
7574        panel.update_in(cx, |panel, window, cx| {
7575            panel.selected_entry = Some(foo_idx);
7576            panel.select_next(&menu::SelectNext, window, cx);
7577        });
7578
7579        panel.read_with(cx, |panel, _| {
7580            let selected_idx = panel.selected_entry.expect("selection should be set");
7581            let selected_entry = panel
7582                .entries
7583                .get(selected_idx)
7584                .and_then(|entry| entry.status_entry())
7585                .expect("selected entry should be a status entry");
7586            assert_eq!(selected_entry.repo_path, repo_path("foobar.py"));
7587        });
7588    }
7589
7590    fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7591        assert_eq!(entries.len(), expected_paths.len());
7592        for (entry, expected_path) in entries.iter().zip(expected_paths) {
7593            assert_eq!(
7594                entry.status_entry().map(|status| status
7595                    .repo_path
7596                    .as_ref()
7597                    .as_std_path()
7598                    .to_string_lossy()
7599                    .to_string()),
7600                expected_path.map(|s| s.to_string())
7601            );
7602        }
7603    }
7604
7605    #[test]
7606    fn test_compress_diff_no_truncation() {
7607        let diff = indoc! {"
7608            --- a/file.txt
7609            +++ b/file.txt
7610            @@ -1,2 +1,2 @@
7611            -old
7612            +new
7613        "};
7614        let result = GitPanel::compress_commit_diff(diff, 1000);
7615        assert_eq!(result, diff);
7616    }
7617
7618    #[test]
7619    fn test_compress_diff_truncate_long_lines() {
7620        let long_line = "🦀".repeat(300);
7621        let diff = indoc::formatdoc! {"
7622            --- a/file.txt
7623            +++ b/file.txt
7624            @@ -1,2 +1,3 @@
7625             context
7626            +{}
7627             more context
7628        ", long_line};
7629        let result = GitPanel::compress_commit_diff(&diff, 100);
7630        assert!(result.contains("...[truncated]"));
7631        assert!(result.len() < diff.len());
7632    }
7633
7634    #[test]
7635    fn test_compress_diff_truncate_hunks() {
7636        let diff = indoc! {"
7637            --- a/file.txt
7638            +++ b/file.txt
7639            @@ -1,2 +1,2 @@
7640             context
7641            -old1
7642            +new1
7643            @@ -5,2 +5,2 @@
7644             context 2
7645            -old2
7646            +new2
7647            @@ -10,2 +10,2 @@
7648             context 3
7649            -old3
7650            +new3
7651        "};
7652        let result = GitPanel::compress_commit_diff(diff, 100);
7653        let expected = indoc! {"
7654            --- a/file.txt
7655            +++ b/file.txt
7656            @@ -1,2 +1,2 @@
7657             context
7658            -old1
7659            +new1
7660            [...skipped 2 hunks...]
7661        "};
7662        assert_eq!(result, expected);
7663    }
7664
7665    #[gpui::test]
7666    async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7667        init_test(cx);
7668
7669        let fs = FakeFs::new(cx.background_executor.clone());
7670        fs.insert_tree(
7671            path!("/project"),
7672            json!({
7673                ".git": {},
7674                "tracked": "tracked\n",
7675                "untracked": "\n",
7676            }),
7677        )
7678        .await;
7679
7680        fs.set_head_and_index_for_repo(
7681            path!("/project/.git").as_ref(),
7682            &[("tracked", "old tracked\n".into())],
7683        );
7684
7685        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7686        let window_handle =
7687            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7688        let workspace = window_handle
7689            .read_with(cx, |mw, _| mw.workspace().clone())
7690            .unwrap();
7691        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7692        let panel = workspace.update_in(cx, GitPanel::new);
7693
7694        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7695            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7696        });
7697        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7698        handle.await;
7699
7700        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7701
7702        // GitPanel
7703        // - Tracked:
7704        // - [] tracked
7705        // - Untracked
7706        // - [] untracked
7707        //
7708        // The commit message should now read:
7709        // "Update tracked"
7710        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7711        assert_eq!(message, Some("Update tracked".to_string()));
7712
7713        let first_status_entry = entries[1].clone();
7714        panel.update_in(cx, |panel, window, cx| {
7715            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7716        });
7717
7718        cx.read(|cx| {
7719            project
7720                .read(cx)
7721                .worktrees(cx)
7722                .next()
7723                .unwrap()
7724                .read(cx)
7725                .as_local()
7726                .unwrap()
7727                .scan_complete()
7728        })
7729        .await;
7730
7731        cx.executor().run_until_parked();
7732
7733        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7734            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7735        });
7736        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7737        handle.await;
7738
7739        // GitPanel
7740        // - Tracked:
7741        // - [x] tracked
7742        // - Untracked
7743        // - [] untracked
7744        //
7745        // The commit message should still read:
7746        // "Update tracked"
7747        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7748        assert_eq!(message, Some("Update tracked".to_string()));
7749
7750        let second_status_entry = entries[3].clone();
7751        panel.update_in(cx, |panel, window, cx| {
7752            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7753        });
7754
7755        cx.read(|cx| {
7756            project
7757                .read(cx)
7758                .worktrees(cx)
7759                .next()
7760                .unwrap()
7761                .read(cx)
7762                .as_local()
7763                .unwrap()
7764                .scan_complete()
7765        })
7766        .await;
7767
7768        cx.executor().run_until_parked();
7769
7770        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7771            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7772        });
7773        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7774        handle.await;
7775
7776        // GitPanel
7777        // - Tracked:
7778        // - [x] tracked
7779        // - Untracked
7780        // - [x] untracked
7781        //
7782        // The commit message should now read:
7783        // "Enter commit message"
7784        // (which means we should see None returned).
7785        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7786        assert!(message.is_none());
7787
7788        panel.update_in(cx, |panel, window, cx| {
7789            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7790        });
7791
7792        cx.read(|cx| {
7793            project
7794                .read(cx)
7795                .worktrees(cx)
7796                .next()
7797                .unwrap()
7798                .read(cx)
7799                .as_local()
7800                .unwrap()
7801                .scan_complete()
7802        })
7803        .await;
7804
7805        cx.executor().run_until_parked();
7806
7807        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7808            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7809        });
7810        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7811        handle.await;
7812
7813        // GitPanel
7814        // - Tracked:
7815        // - [] tracked
7816        // - Untracked
7817        // - [x] untracked
7818        //
7819        // The commit message should now read:
7820        // "Update untracked"
7821        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7822        assert_eq!(message, Some("Create untracked".to_string()));
7823
7824        panel.update_in(cx, |panel, window, cx| {
7825            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7826        });
7827
7828        cx.read(|cx| {
7829            project
7830                .read(cx)
7831                .worktrees(cx)
7832                .next()
7833                .unwrap()
7834                .read(cx)
7835                .as_local()
7836                .unwrap()
7837                .scan_complete()
7838        })
7839        .await;
7840
7841        cx.executor().run_until_parked();
7842
7843        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7844            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7845        });
7846        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7847        handle.await;
7848
7849        // GitPanel
7850        // - Tracked:
7851        // - [] tracked
7852        // - Untracked
7853        // - [] untracked
7854        //
7855        // The commit message should now read:
7856        // "Update tracked"
7857        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7858        assert_eq!(message, Some("Update tracked".to_string()));
7859    }
7860
7861    #[gpui::test]
7862    async fn test_dispatch_context_with_focus_states(cx: &mut TestAppContext) {
7863        init_test(cx);
7864
7865        let fs = FakeFs::new(cx.background_executor.clone());
7866        fs.insert_tree(
7867            path!("/project"),
7868            json!({
7869                ".git": {},
7870                "tracked": "tracked\n",
7871            }),
7872        )
7873        .await;
7874
7875        fs.set_head_and_index_for_repo(
7876            path!("/project/.git").as_ref(),
7877            &[("tracked", "old tracked\n".into())],
7878        );
7879
7880        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7881        let window_handle =
7882            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7883        let workspace = window_handle
7884            .read_with(cx, |mw, _| mw.workspace().clone())
7885            .unwrap();
7886        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7887        let panel = workspace.update_in(cx, GitPanel::new);
7888
7889        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7890            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7891        });
7892        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7893        handle.await;
7894
7895        // Case 1: Focus the commit editor — should have "CommitEditor" but NOT "menu"/"ChangesList"
7896        panel.update_in(cx, |panel, window, cx| {
7897            panel.focus_editor(&FocusEditor, window, cx);
7898            let editor_is_focused = panel.commit_editor.read(cx).is_focused(window);
7899            assert!(
7900                editor_is_focused,
7901                "commit editor should be focused after focus_editor action"
7902            );
7903            let context = panel.dispatch_context(window, cx);
7904            assert!(
7905                context.contains("GitPanel"),
7906                "should always have GitPanel context"
7907            );
7908            assert!(
7909                context.contains("CommitEditor"),
7910                "should have CommitEditor context when commit editor is focused"
7911            );
7912            assert!(
7913                !context.contains("menu"),
7914                "should not have menu context when commit editor is focused"
7915            );
7916            assert!(
7917                !context.contains("ChangesList"),
7918                "should not have ChangesList context when commit editor is focused"
7919            );
7920        });
7921
7922        // Case 2: Focus the panel's focus handle directly — should have "menu" and "ChangesList".
7923        // We force a draw via simulate_resize to ensure the dispatch tree is populated,
7924        // since contains_focused() depends on the rendered dispatch tree.
7925        panel.update_in(cx, |panel, window, cx| {
7926            panel.focus_handle.focus(window, cx);
7927        });
7928        cx.simulate_resize(gpui::size(px(800.), px(600.)));
7929
7930        panel.update_in(cx, |panel, window, cx| {
7931            let context = panel.dispatch_context(window, cx);
7932            assert!(
7933                context.contains("GitPanel"),
7934                "should always have GitPanel context"
7935            );
7936            assert!(
7937                context.contains("menu"),
7938                "should have menu context when changes list is focused"
7939            );
7940            assert!(
7941                context.contains("ChangesList"),
7942                "should have ChangesList context when changes list is focused"
7943            );
7944            assert!(
7945                !context.contains("CommitEditor"),
7946                "should not have CommitEditor context when changes list is focused"
7947            );
7948        });
7949
7950        // Case 3: Switch back to commit editor and verify context switches correctly
7951        panel.update_in(cx, |panel, window, cx| {
7952            panel.focus_editor(&FocusEditor, window, cx);
7953        });
7954
7955        panel.update_in(cx, |panel, window, cx| {
7956            let context = panel.dispatch_context(window, cx);
7957            assert!(
7958                context.contains("CommitEditor"),
7959                "should have CommitEditor after switching focus back to editor"
7960            );
7961            assert!(
7962                !context.contains("menu"),
7963                "should not have menu after switching focus back to editor"
7964            );
7965        });
7966
7967        // Case 4: Re-focus changes list and verify it transitions back correctly
7968        panel.update_in(cx, |panel, window, cx| {
7969            panel.focus_handle.focus(window, cx);
7970        });
7971        cx.simulate_resize(gpui::size(px(800.), px(600.)));
7972
7973        panel.update_in(cx, |panel, window, cx| {
7974            assert!(
7975                panel.focus_handle.contains_focused(window, cx),
7976                "panel focus handle should report contains_focused when directly focused"
7977            );
7978            let context = panel.dispatch_context(window, cx);
7979            assert!(
7980                context.contains("menu"),
7981                "should have menu context after re-focusing changes list"
7982            );
7983            assert!(
7984                context.contains("ChangesList"),
7985                "should have ChangesList context after re-focusing changes list"
7986            );
7987        });
7988    }
7989}