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