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;
  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(
3868                        Icon::new(IconName::GitBranch)
3869                            .size(IconSize::Small)
3870                            .color(Color::Muted),
3871                    ),
3872                    ToastWithLog { output } => this
3873                        .icon(
3874                            Icon::new(IconName::GitBranch)
3875                                .size(IconSize::Small)
3876                                .color(Color::Muted),
3877                        )
3878                        .action("View Log", move |window, cx| {
3879                            let output = output.clone();
3880                            let output =
3881                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3882                            workspace_weak
3883                                .update(cx, move |workspace, cx| {
3884                                    open_output(operation, workspace, &output, window, cx)
3885                                })
3886                                .ok();
3887                        }),
3888                    PushPrLink { text, link } => this
3889                        .icon(
3890                            Icon::new(IconName::GitBranch)
3891                                .size(IconSize::Small)
3892                                .color(Color::Muted),
3893                        )
3894                        .action(text, move |_, cx| cx.open_url(&link)),
3895                }
3896                .dismiss_button(true)
3897            });
3898            workspace.toggle_status_toast(status_toast, cx)
3899        });
3900    }
3901
3902    pub fn can_commit(&self) -> bool {
3903        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3904    }
3905
3906    pub fn can_stage_all(&self) -> bool {
3907        self.has_unstaged_changes()
3908    }
3909
3910    pub fn can_unstage_all(&self) -> bool {
3911        self.has_staged_changes()
3912    }
3913
3914    /// Computes tree indentation depths for visible entries in the given range.
3915    /// Used by indent guides to render vertical connector lines in tree view.
3916    fn compute_visible_depths(&self, range: Range<usize>) -> SmallVec<[usize; 64]> {
3917        let GitPanelViewMode::Tree(state) = &self.view_mode else {
3918            return SmallVec::new();
3919        };
3920
3921        range
3922            .map(|ix| {
3923                state
3924                    .logical_indices
3925                    .get(ix)
3926                    .and_then(|&entry_ix| self.entries.get(entry_ix))
3927                    .map_or(0, |entry| entry.depth())
3928            })
3929            .collect()
3930    }
3931
3932    fn status_width_estimate(
3933        tree_view: bool,
3934        entry: &GitStatusEntry,
3935        path_style: PathStyle,
3936        depth: usize,
3937    ) -> usize {
3938        if tree_view {
3939            Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3940        } else {
3941            Self::item_width_estimate(
3942                entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3943                entry.display_name(path_style).len(),
3944                0,
3945            )
3946        }
3947    }
3948
3949    fn width_estimate_for_list_entry(
3950        &self,
3951        tree_view: bool,
3952        entry: &GitListEntry,
3953        path_style: PathStyle,
3954    ) -> Option<usize> {
3955        match entry {
3956            GitListEntry::Status(status) => Some(Self::status_width_estimate(
3957                tree_view, status, path_style, 0,
3958            )),
3959            GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3960                tree_view,
3961                &status.entry,
3962                path_style,
3963                status.depth,
3964            )),
3965            GitListEntry::Directory(dir) => {
3966                Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
3967            }
3968            GitListEntry::Header(_) => None,
3969        }
3970    }
3971
3972    fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
3973        path + file_name + depth * 2
3974    }
3975
3976    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3977        let focus_handle = self.focus_handle.clone();
3978        let has_tracked_changes = self.has_tracked_changes();
3979        let has_staged_changes = self.has_staged_changes();
3980        let has_unstaged_changes = self.has_unstaged_changes();
3981        let has_new_changes = self.new_count > 0;
3982        let has_stash_items = self.stash_entries.entries.len() > 0;
3983
3984        PopoverMenu::new(id.into())
3985            .trigger(
3986                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3987                    .icon_size(IconSize::Small)
3988                    .icon_color(Color::Muted),
3989            )
3990            .menu(move |window, cx| {
3991                Some(git_panel_context_menu(
3992                    focus_handle.clone(),
3993                    GitMenuState {
3994                        has_tracked_changes,
3995                        has_staged_changes,
3996                        has_unstaged_changes,
3997                        has_new_changes,
3998                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3999                        has_stash_items,
4000                        tree_view: GitPanelSettings::get_global(cx).tree_view,
4001                    },
4002                    window,
4003                    cx,
4004                ))
4005            })
4006            .anchor(Corner::TopRight)
4007    }
4008
4009    pub(crate) fn render_generate_commit_message_button(
4010        &self,
4011        cx: &Context<Self>,
4012    ) -> Option<AnyElement> {
4013        if !agent_settings::AgentSettings::get_global(cx).enabled(cx) {
4014            return None;
4015        }
4016
4017        if self.generate_commit_message_task.is_some() {
4018            return Some(
4019                h_flex()
4020                    .gap_1()
4021                    .child(
4022                        Icon::new(IconName::ArrowCircle)
4023                            .size(IconSize::XSmall)
4024                            .color(Color::Info)
4025                            .with_rotate_animation(2),
4026                    )
4027                    .child(
4028                        Label::new("Generating Commit…")
4029                            .size(LabelSize::Small)
4030                            .color(Color::Muted),
4031                    )
4032                    .into_any_element(),
4033            );
4034        }
4035
4036        let model_registry = LanguageModelRegistry::read_global(cx);
4037        let has_commit_model_configuration_error = model_registry
4038            .configuration_error(model_registry.commit_message_model(), cx)
4039            .is_some();
4040        let can_commit = self.can_commit();
4041
4042        let editor_focus_handle = self.commit_editor.focus_handle(cx);
4043
4044        Some(
4045            IconButton::new("generate-commit-message", IconName::AiEdit)
4046                .shape(ui::IconButtonShape::Square)
4047                .icon_color(if has_commit_model_configuration_error {
4048                    Color::Disabled
4049                } else {
4050                    Color::Muted
4051                })
4052                .tooltip(move |_window, cx| {
4053                    if !can_commit {
4054                        Tooltip::simple("No Changes to Commit", cx)
4055                    } else if has_commit_model_configuration_error {
4056                        Tooltip::simple("Configure an LLM provider to generate commit messages", cx)
4057                    } else {
4058                        Tooltip::for_action_in(
4059                            "Generate Commit Message",
4060                            &git::GenerateCommitMessage,
4061                            &editor_focus_handle,
4062                            cx,
4063                        )
4064                    }
4065                })
4066                .disabled(!can_commit || has_commit_model_configuration_error)
4067                .on_click(cx.listener(move |this, _event, _window, cx| {
4068                    this.generate_commit_message(cx);
4069                }))
4070                .into_any_element(),
4071        )
4072    }
4073
4074    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
4075        let potential_co_authors = self.potential_co_authors(cx);
4076
4077        let (tooltip_label, icon) = if self.add_coauthors {
4078            ("Remove co-authored-by", IconName::Person)
4079        } else {
4080            ("Add co-authored-by", IconName::UserCheck)
4081        };
4082
4083        if potential_co_authors.is_empty() {
4084            None
4085        } else {
4086            Some(
4087                IconButton::new("co-authors", icon)
4088                    .shape(ui::IconButtonShape::Square)
4089                    .icon_color(Color::Disabled)
4090                    .selected_icon_color(Color::Selected)
4091                    .toggle_state(self.add_coauthors)
4092                    .tooltip(move |_, cx| {
4093                        let title = format!(
4094                            "{}:{}{}",
4095                            tooltip_label,
4096                            if potential_co_authors.len() == 1 {
4097                                ""
4098                            } else {
4099                                "\n"
4100                            },
4101                            potential_co_authors
4102                                .iter()
4103                                .map(|(name, email)| format!(" {} <{}>", name, email))
4104                                .join("\n")
4105                        );
4106                        Tooltip::simple(title, cx)
4107                    })
4108                    .on_click(cx.listener(|this, _, _, cx| {
4109                        this.add_coauthors = !this.add_coauthors;
4110                        cx.notify();
4111                    }))
4112                    .into_any_element(),
4113            )
4114        }
4115    }
4116
4117    fn render_git_commit_menu(
4118        &self,
4119        id: impl Into<ElementId>,
4120        keybinding_target: Option<FocusHandle>,
4121        cx: &mut Context<Self>,
4122    ) -> impl IntoElement {
4123        PopoverMenu::new(id.into())
4124            .trigger(
4125                ui::ButtonLike::new_rounded_right("commit-split-button-right")
4126                    .layer(ui::ElevationIndex::ModalSurface)
4127                    .size(ButtonSize::None)
4128                    .child(
4129                        h_flex()
4130                            .px_1()
4131                            .h_full()
4132                            .justify_center()
4133                            .border_l_1()
4134                            .border_color(cx.theme().colors().border)
4135                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
4136                    ),
4137            )
4138            .menu({
4139                let git_panel = cx.entity();
4140                let has_previous_commit = self.head_commit(cx).is_some();
4141                let amend = self.amend_pending();
4142                let signoff = self.signoff_enabled;
4143
4144                move |window, cx| {
4145                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
4146                        context_menu
4147                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
4148                                el.context(keybinding_target)
4149                            })
4150                            .when(has_previous_commit, |this| {
4151                                this.toggleable_entry(
4152                                    "Amend",
4153                                    amend,
4154                                    IconPosition::Start,
4155                                    Some(Box::new(Amend)),
4156                                    {
4157                                        let git_panel = git_panel.downgrade();
4158                                        move |_, cx| {
4159                                            git_panel
4160                                                .update(cx, |git_panel, cx| {
4161                                                    git_panel.toggle_amend_pending(cx);
4162                                                })
4163                                                .ok();
4164                                        }
4165                                    },
4166                                )
4167                            })
4168                            .toggleable_entry(
4169                                "Signoff",
4170                                signoff,
4171                                IconPosition::Start,
4172                                Some(Box::new(Signoff)),
4173                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
4174                            )
4175                    }))
4176                }
4177            })
4178            .anchor(Corner::TopRight)
4179    }
4180
4181    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
4182        if self.has_unstaged_conflicts() {
4183            (false, "You must resolve conflicts before committing")
4184        } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
4185            (false, "No changes to commit")
4186        } else if self.pending_commit.is_some() {
4187            (false, "Commit in progress")
4188        } else if !self.has_commit_message(cx) {
4189            (false, "No commit message")
4190        } else if !self.has_write_access(cx) {
4191            (false, "You do not have write access to this project")
4192        } else {
4193            (true, self.commit_button_title())
4194        }
4195    }
4196
4197    pub fn commit_button_title(&self) -> &'static str {
4198        if self.amend_pending {
4199            if self.has_staged_changes() {
4200                "Amend"
4201            } else if self.has_tracked_changes() {
4202                "Amend Tracked"
4203            } else {
4204                "Amend"
4205            }
4206        } else if self.has_staged_changes() {
4207            "Commit"
4208        } else {
4209            "Commit Tracked"
4210        }
4211    }
4212
4213    fn expand_commit_editor(
4214        &mut self,
4215        _: &git::ExpandCommitEditor,
4216        window: &mut Window,
4217        cx: &mut Context<Self>,
4218    ) {
4219        let workspace = self.workspace.clone();
4220        window.defer(cx, move |window, cx| {
4221            workspace
4222                .update(cx, |workspace, cx| {
4223                    CommitModal::toggle(workspace, None, window, cx)
4224                })
4225                .ok();
4226        })
4227    }
4228
4229    fn render_panel_header(
4230        &self,
4231        window: &mut Window,
4232        cx: &mut Context<Self>,
4233    ) -> Option<impl IntoElement> {
4234        self.active_repository.as_ref()?;
4235
4236        let (text, action, stage, tooltip) =
4237            if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
4238                ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
4239            } else {
4240                ("Stage All", StageAll.boxed_clone(), true, "git add --all")
4241            };
4242
4243        let change_string = match self.changes_count {
4244            0 => "No Changes".to_string(),
4245            1 => "1 Change".to_string(),
4246            count => format!("{} Changes", count),
4247        };
4248
4249        Some(
4250            self.panel_header_container(window, cx)
4251                .px_2()
4252                .justify_between()
4253                .child(
4254                    panel_button(change_string)
4255                        .color(Color::Muted)
4256                        .tooltip(Tooltip::for_action_title_in(
4257                            "Open Diff",
4258                            &Diff,
4259                            &self.focus_handle,
4260                        ))
4261                        .on_click(|_, _, cx| {
4262                            cx.defer(|cx| {
4263                                cx.dispatch_action(&Diff);
4264                            })
4265                        }),
4266                )
4267                .child(
4268                    h_flex()
4269                        .gap_1()
4270                        .child(self.render_overflow_menu("overflow_menu"))
4271                        .child(
4272                            panel_filled_button(text)
4273                                .tooltip(Tooltip::for_action_title_in(
4274                                    tooltip,
4275                                    action.as_ref(),
4276                                    &self.focus_handle,
4277                                ))
4278                                .disabled(self.entry_count == 0)
4279                                .on_click({
4280                                    let git_panel = cx.weak_entity();
4281                                    move |_, _, cx| {
4282                                        git_panel
4283                                            .update(cx, |git_panel, cx| {
4284                                                git_panel.change_all_files_stage(stage, cx);
4285                                            })
4286                                            .ok();
4287                                    }
4288                                }),
4289                        ),
4290                ),
4291        )
4292    }
4293
4294    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4295        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
4296        if !self.can_push_and_pull(cx) {
4297            return None;
4298        }
4299        Some(
4300            h_flex()
4301                .gap_1()
4302                .flex_shrink_0()
4303                .when_some(branch, |this, branch| {
4304                    let focus_handle = Some(self.focus_handle(cx));
4305
4306                    this.children(render_remote_button(
4307                        "remote-button",
4308                        &branch,
4309                        focus_handle,
4310                        true,
4311                    ))
4312                })
4313                .into_any_element(),
4314        )
4315    }
4316
4317    pub fn render_footer(
4318        &self,
4319        window: &mut Window,
4320        cx: &mut Context<Self>,
4321    ) -> Option<impl IntoElement> {
4322        let active_repository = self.active_repository.clone()?;
4323        let panel_editor_style = panel_editor_style(true, window, cx);
4324        let enable_coauthors = self.render_co_authors(cx);
4325
4326        let editor_focus_handle = self.commit_editor.focus_handle(cx);
4327        let expand_tooltip_focus_handle = editor_focus_handle;
4328
4329        let branch = active_repository.read(cx).branch.clone();
4330        let head_commit = active_repository.read(cx).head_commit.clone();
4331
4332        let footer_size = px(32.);
4333        let gap = px(9.0);
4334        let max_height = panel_editor_style
4335            .text
4336            .line_height_in_pixels(window.rem_size())
4337            * MAX_PANEL_EDITOR_LINES
4338            + gap;
4339
4340        let git_panel = cx.entity();
4341        let display_name = SharedString::from(Arc::from(
4342            active_repository
4343                .read(cx)
4344                .display_name()
4345                .trim_end_matches("/"),
4346        ));
4347        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4348            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4349        });
4350
4351        let footer = v_flex()
4352            .child(PanelRepoFooter::new(
4353                display_name,
4354                branch,
4355                head_commit,
4356                Some(git_panel),
4357            ))
4358            .child(
4359                panel_editor_container(window, cx)
4360                    .id("commit-editor-container")
4361                    .relative()
4362                    .w_full()
4363                    .h(max_height + footer_size)
4364                    .border_t_1()
4365                    .border_color(cx.theme().colors().border)
4366                    .cursor_text()
4367                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4368                        window.focus(&this.commit_editor.focus_handle(cx), cx);
4369                    }))
4370                    .child(
4371                        h_flex()
4372                            .id("commit-footer")
4373                            .border_t_1()
4374                            .when(editor_is_long, |el| {
4375                                el.border_color(cx.theme().colors().border_variant)
4376                            })
4377                            .absolute()
4378                            .bottom_0()
4379                            .left_0()
4380                            .w_full()
4381                            .px_2()
4382                            .h(footer_size)
4383                            .flex_none()
4384                            .justify_between()
4385                            .child(
4386                                self.render_generate_commit_message_button(cx)
4387                                    .unwrap_or_else(|| div().into_any_element()),
4388                            )
4389                            .child(
4390                                h_flex()
4391                                    .gap_0p5()
4392                                    .children(enable_coauthors)
4393                                    .child(self.render_commit_button(cx)),
4394                            ),
4395                    )
4396                    .child(
4397                        div()
4398                            .pr_2p5()
4399                            .on_action(|&zed_actions::editor::MoveUp, _, cx| {
4400                                cx.stop_propagation();
4401                            })
4402                            .on_action(|&zed_actions::editor::MoveDown, _, cx| {
4403                                cx.stop_propagation();
4404                            })
4405                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4406                    )
4407                    .child(
4408                        h_flex()
4409                            .absolute()
4410                            .top_2()
4411                            .right_2()
4412                            .opacity(0.5)
4413                            .hover(|this| this.opacity(1.0))
4414                            .child(
4415                                panel_icon_button("expand-commit-editor", IconName::Maximize)
4416                                    .icon_size(IconSize::Small)
4417                                    .size(ui::ButtonSize::Default)
4418                                    .tooltip(move |_window, cx| {
4419                                        Tooltip::for_action_in(
4420                                            "Open Commit Modal",
4421                                            &git::ExpandCommitEditor,
4422                                            &expand_tooltip_focus_handle,
4423                                            cx,
4424                                        )
4425                                    })
4426                                    .on_click(cx.listener({
4427                                        move |_, _, window, cx| {
4428                                            window.dispatch_action(
4429                                                git::ExpandCommitEditor.boxed_clone(),
4430                                                cx,
4431                                            )
4432                                        }
4433                                    })),
4434                            ),
4435                    ),
4436            );
4437
4438        Some(footer)
4439    }
4440
4441    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4442        let (can_commit, tooltip) = self.configure_commit_button(cx);
4443        let title = self.commit_button_title();
4444        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4445        let amend = self.amend_pending();
4446        let signoff = self.signoff_enabled;
4447
4448        let label_color = if self.pending_commit.is_some() {
4449            Color::Disabled
4450        } else {
4451            Color::Default
4452        };
4453
4454        div()
4455            .id("commit-wrapper")
4456            .on_hover(cx.listener(move |this, hovered, _, cx| {
4457                this.show_placeholders =
4458                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4459                cx.notify()
4460            }))
4461            .child(SplitButton::new(
4462                ButtonLike::new_rounded_left(ElementId::Name(
4463                    format!("split-button-left-{}", title).into(),
4464                ))
4465                .layer(ElevationIndex::ModalSurface)
4466                .size(ButtonSize::Compact)
4467                .child(
4468                    Label::new(title)
4469                        .size(LabelSize::Small)
4470                        .color(label_color)
4471                        .mr_0p5(),
4472                )
4473                .on_click({
4474                    let git_panel = cx.weak_entity();
4475                    move |_, window, cx| {
4476                        telemetry::event!("Git Committed", source = "Git Panel");
4477                        git_panel
4478                            .update(cx, |git_panel, cx| {
4479                                git_panel.commit_changes(
4480                                    CommitOptions {
4481                                        amend,
4482                                        signoff,
4483                                        allow_empty: false,
4484                                    },
4485                                    window,
4486                                    cx,
4487                                );
4488                            })
4489                            .ok();
4490                    }
4491                })
4492                .disabled(!can_commit || self.modal_open)
4493                .tooltip({
4494                    let handle = commit_tooltip_focus_handle.clone();
4495                    move |_window, cx| {
4496                        if can_commit {
4497                            Tooltip::with_meta_in(
4498                                tooltip,
4499                                Some(if amend { &git::Amend } else { &git::Commit }),
4500                                format!(
4501                                    "git commit{}{}",
4502                                    if amend { " --amend" } else { "" },
4503                                    if signoff { " --signoff" } else { "" }
4504                                ),
4505                                &handle.clone(),
4506                                cx,
4507                            )
4508                        } else {
4509                            Tooltip::simple(tooltip, cx)
4510                        }
4511                    }
4512                }),
4513                self.render_git_commit_menu(
4514                    ElementId::Name(format!("split-button-right-{}", title).into()),
4515                    Some(commit_tooltip_focus_handle),
4516                    cx,
4517                )
4518                .into_any_element(),
4519            ))
4520    }
4521
4522    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4523        h_flex()
4524            .py_1p5()
4525            .px_2()
4526            .gap_1p5()
4527            .justify_between()
4528            .border_t_1()
4529            .border_color(cx.theme().colors().border.opacity(0.8))
4530            .child(
4531                div()
4532                    .flex_grow()
4533                    .overflow_hidden()
4534                    .max_w(relative(0.85))
4535                    .child(
4536                        Label::new("This will update your most recent commit.")
4537                            .size(LabelSize::Small)
4538                            .truncate(),
4539                    ),
4540            )
4541            .child(
4542                panel_button("Cancel")
4543                    .size(ButtonSize::Default)
4544                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4545            )
4546    }
4547
4548    fn render_previous_commit(
4549        &self,
4550        _window: &mut Window,
4551        cx: &mut Context<Self>,
4552    ) -> Option<impl IntoElement> {
4553        let active_repository = self.active_repository.as_ref()?;
4554        let branch = active_repository.read(cx).branch.as_ref()?;
4555        let commit = branch.most_recent_commit.as_ref()?.clone();
4556        let workspace = self.workspace.clone();
4557        let this = cx.entity();
4558
4559        Some(
4560            h_flex()
4561                .p_1p5()
4562                .gap_1p5()
4563                .justify_between()
4564                .border_t_1()
4565                .border_color(cx.theme().colors().border.opacity(0.8))
4566                .child(
4567                    div()
4568                        .id("commit-msg-hover")
4569                        .cursor_pointer()
4570                        .px_1()
4571                        .rounded_sm()
4572                        .line_clamp(1)
4573                        .hover(|s| s.bg(cx.theme().colors().element_hover))
4574                        .child(
4575                            Label::new(commit.subject.clone())
4576                                .size(LabelSize::Small)
4577                                .truncate(),
4578                        )
4579                        .on_click({
4580                            let commit = commit.clone();
4581                            let repo = active_repository.downgrade();
4582                            move |_, window, cx| {
4583                                CommitView::open(
4584                                    commit.sha.to_string(),
4585                                    repo.clone(),
4586                                    workspace.clone(),
4587                                    None,
4588                                    None,
4589                                    window,
4590                                    cx,
4591                                );
4592                            }
4593                        })
4594                        .hoverable_tooltip({
4595                            let repo = active_repository.clone();
4596                            move |window, cx| {
4597                                GitPanelMessageTooltip::new(
4598                                    this.clone(),
4599                                    commit.sha.clone(),
4600                                    repo.clone(),
4601                                    window,
4602                                    cx,
4603                                )
4604                                .into()
4605                            }
4606                        }),
4607                )
4608                .child(
4609                    h_flex()
4610                        .gap_0p5()
4611                        .when(commit.has_parent, |this| {
4612                            let has_unstaged = self.has_unstaged_changes();
4613                            this.child(
4614                                panel_icon_button("undo", IconName::Undo)
4615                                    .icon_size(IconSize::Small)
4616                                    .tooltip(move |_window, cx| {
4617                                        Tooltip::with_meta(
4618                                            "Uncommit",
4619                                            Some(&git::Uncommit),
4620                                            if has_unstaged {
4621                                                "git reset HEAD^ --soft"
4622                                            } else {
4623                                                "git reset HEAD^"
4624                                            },
4625                                            cx,
4626                                        )
4627                                    })
4628                                    .on_click(
4629                                        cx.listener(|this, _, window, cx| {
4630                                            this.uncommit(window, cx)
4631                                        }),
4632                                    ),
4633                            )
4634                        })
4635                        .child(
4636                            panel_icon_button("git-graph-button", IconName::GitGraph)
4637                                .icon_size(IconSize::Small)
4638                                .tooltip(|_window, cx| {
4639                                    Tooltip::for_action("Open Git Graph", &Open, cx)
4640                                })
4641                                .on_click(|_, window, cx| {
4642                                    window.dispatch_action(Open.boxed_clone(), cx)
4643                                }),
4644                        ),
4645                ),
4646        )
4647    }
4648
4649    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4650        let has_repo = self.active_repository.is_some();
4651        let has_no_repo = self.active_repository.is_none();
4652        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4653
4654        let should_show_branch_diff =
4655            has_repo && self.changes_count == 0 && !self.is_on_main_branch(cx);
4656
4657        let label = if has_repo {
4658            "No changes to commit"
4659        } else {
4660            "No Git repositories"
4661        };
4662
4663        v_flex()
4664            .gap_1p5()
4665            .flex_1()
4666            .items_center()
4667            .justify_center()
4668            .child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
4669            .when(has_no_repo && worktree_count > 0, |this| {
4670                this.child(
4671                    panel_filled_button("Initialize Repository")
4672                        .tooltip(Tooltip::for_action_title_in(
4673                            "git init",
4674                            &git::Init,
4675                            &self.focus_handle,
4676                        ))
4677                        .on_click(move |_, _, cx| {
4678                            cx.defer(move |cx| {
4679                                cx.dispatch_action(&git::Init);
4680                            })
4681                        }),
4682                )
4683            })
4684            .when(should_show_branch_diff, |this| {
4685                this.child(
4686                    panel_filled_button("View Branch Diff")
4687                        .tooltip(move |_, cx| {
4688                            Tooltip::with_meta(
4689                                "Branch Diff",
4690                                Some(&BranchDiff),
4691                                "Show diff between working directory and default branch",
4692                                cx,
4693                            )
4694                        })
4695                        .on_click(move |_, _, cx| {
4696                            cx.defer(move |cx| {
4697                                cx.dispatch_action(&BranchDiff);
4698                            })
4699                        }),
4700                )
4701            })
4702    }
4703
4704    fn is_on_main_branch(&self, cx: &Context<Self>) -> bool {
4705        let Some(repo) = self.active_repository.as_ref() else {
4706            return false;
4707        };
4708
4709        let Some(branch) = repo.read(cx).branch.as_ref() else {
4710            return false;
4711        };
4712
4713        let branch_name = branch.name();
4714        matches!(branch_name, "main" | "master")
4715    }
4716
4717    fn render_buffer_header_controls(
4718        &self,
4719        entity: &Entity<Self>,
4720        file: &Arc<dyn File>,
4721        _: &Window,
4722        cx: &App,
4723    ) -> Option<AnyElement> {
4724        let repo = self.active_repository.as_ref()?.read(cx);
4725        let project_path = (file.worktree_id(cx), file.path().clone()).into();
4726        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4727        let ix = self.entry_by_path(&repo_path)?;
4728        let entry = self.entries.get(ix)?;
4729
4730        let is_staging_or_staged = repo
4731            .pending_ops_for_path(&repo_path)
4732            .map(|ops| ops.staging() || ops.staged())
4733            .or_else(|| {
4734                repo.status_for_path(&repo_path)
4735                    .and_then(|status| status.status.staging().as_bool())
4736            })
4737            .or_else(|| {
4738                entry
4739                    .status_entry()
4740                    .and_then(|entry| entry.staging.as_bool())
4741            });
4742
4743        let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4744            .disabled(!self.has_write_access(cx))
4745            .fill()
4746            .elevation(ElevationIndex::Surface)
4747            .on_click({
4748                let entry = entry.clone();
4749                let git_panel = entity.downgrade();
4750                move |_, window, cx| {
4751                    git_panel
4752                        .update(cx, |this, cx| {
4753                            this.toggle_staged_for_entry(&entry, window, cx);
4754                            cx.stop_propagation();
4755                        })
4756                        .ok();
4757                }
4758            });
4759        Some(
4760            h_flex()
4761                .id("start-slot")
4762                .text_lg()
4763                .child(checkbox)
4764                .on_mouse_down(MouseButton::Left, |_, _, cx| {
4765                    // prevent the list item active state triggering when toggling checkbox
4766                    cx.stop_propagation();
4767                })
4768                .into_any_element(),
4769        )
4770    }
4771
4772    fn render_entries(
4773        &self,
4774        has_write_access: bool,
4775        repo: Entity<Repository>,
4776        window: &mut Window,
4777        cx: &mut Context<Self>,
4778    ) -> impl IntoElement {
4779        let (is_tree_view, entry_count) = match &self.view_mode {
4780            GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4781            GitPanelViewMode::Flat => (false, self.entries.len()),
4782        };
4783        let repo = repo.downgrade();
4784
4785        v_flex()
4786            .flex_1()
4787            .size_full()
4788            .overflow_hidden()
4789            .relative()
4790            .child(
4791                h_flex()
4792                    .flex_1()
4793                    .size_full()
4794                    .relative()
4795                    .overflow_hidden()
4796                    .child(
4797                        uniform_list(
4798                            "entries",
4799                            entry_count,
4800                            cx.processor(move |this, range: Range<usize>, window, cx| {
4801                                let Some(repo) = repo.upgrade() else {
4802                                    return Vec::new();
4803                                };
4804                                let repo = repo.read(cx);
4805
4806                                let mut items = Vec::with_capacity(range.end - range.start);
4807
4808                                for ix in range.into_iter().map(|ix| match &this.view_mode {
4809                                    GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4810                                    GitPanelViewMode::Flat => ix,
4811                                }) {
4812                                    match &this.entries.get(ix) {
4813                                        Some(GitListEntry::Status(entry)) => {
4814                                            items.push(this.render_status_entry(
4815                                                ix,
4816                                                entry,
4817                                                0,
4818                                                has_write_access,
4819                                                repo,
4820                                                window,
4821                                                cx,
4822                                            ));
4823                                        }
4824                                        Some(GitListEntry::TreeStatus(entry)) => {
4825                                            items.push(this.render_status_entry(
4826                                                ix,
4827                                                &entry.entry,
4828                                                entry.depth,
4829                                                has_write_access,
4830                                                repo,
4831                                                window,
4832                                                cx,
4833                                            ));
4834                                        }
4835                                        Some(GitListEntry::Directory(entry)) => {
4836                                            items.push(this.render_directory_entry(
4837                                                ix,
4838                                                entry,
4839                                                has_write_access,
4840                                                window,
4841                                                cx,
4842                                            ));
4843                                        }
4844                                        Some(GitListEntry::Header(header)) => {
4845                                            items.push(this.render_list_header(
4846                                                ix,
4847                                                header,
4848                                                has_write_access,
4849                                                window,
4850                                                cx,
4851                                            ));
4852                                        }
4853                                        None => {}
4854                                    }
4855                                }
4856
4857                                items
4858                            }),
4859                        )
4860                        .when(is_tree_view, |list| {
4861                            let indent_size = px(TREE_INDENT);
4862                            list.with_decoration(
4863                                ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4864                                    .with_compute_indents_fn(
4865                                        cx.entity(),
4866                                        |this, range, _window, _cx| {
4867                                            this.compute_visible_depths(range)
4868                                        },
4869                                    )
4870                                    .with_render_fn(cx.entity(), |_, params, _, _| {
4871                                        // Magic number to align the tree item is 3 here
4872                                        // because we're using 12px as the left-side padding
4873                                        // and 3 makes the alignment work with the bounding box of the icon
4874                                        let left_offset = px(TREE_INDENT + 3_f32);
4875                                        let indent_size = params.indent_size;
4876                                        let item_height = params.item_height;
4877
4878                                        params
4879                                            .indent_guides
4880                                            .into_iter()
4881                                            .map(|layout| {
4882                                                let bounds = Bounds::new(
4883                                                    point(
4884                                                        layout.offset.x * indent_size + left_offset,
4885                                                        layout.offset.y * item_height,
4886                                                    ),
4887                                                    size(px(1.), layout.length * item_height),
4888                                                );
4889                                                RenderedIndentGuide {
4890                                                    bounds,
4891                                                    layout,
4892                                                    is_active: false,
4893                                                    hitbox: None,
4894                                                }
4895                                            })
4896                                            .collect()
4897                                    }),
4898                            )
4899                        })
4900                        .size_full()
4901                        .flex_grow()
4902                        .with_width_from_item(self.max_width_item_index)
4903                        .track_scroll(&self.scroll_handle),
4904                    )
4905                    .on_mouse_down(
4906                        MouseButton::Right,
4907                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4908                            this.deploy_panel_context_menu(event.position, window, cx)
4909                        }),
4910                    )
4911                    .custom_scrollbars(
4912                        Scrollbars::for_settings::<GitPanelScrollbarAccessor>()
4913                            .tracked_scroll_handle(&self.scroll_handle)
4914                            .with_track_along(
4915                                ScrollAxes::Horizontal,
4916                                cx.theme().colors().panel_background,
4917                            ),
4918                        window,
4919                        cx,
4920                    ),
4921            )
4922    }
4923
4924    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4925        Label::new(label.into()).color(color)
4926    }
4927
4928    fn list_item_height(&self) -> Rems {
4929        rems(1.75)
4930    }
4931
4932    fn render_list_header(
4933        &self,
4934        ix: usize,
4935        header: &GitHeaderEntry,
4936        _: bool,
4937        _: &Window,
4938        _: &Context<Self>,
4939    ) -> AnyElement {
4940        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4941
4942        h_flex()
4943            .id(id)
4944            .h(self.list_item_height())
4945            .w_full()
4946            .items_end()
4947            .px_3()
4948            .pb_1()
4949            .child(
4950                Label::new(header.title())
4951                    .color(Color::Muted)
4952                    .size(LabelSize::Small)
4953                    .line_height_style(LineHeightStyle::UiLabel)
4954                    .single_line(),
4955            )
4956            .into_any_element()
4957    }
4958
4959    pub fn load_commit_details(
4960        &self,
4961        sha: String,
4962        cx: &mut Context<Self>,
4963    ) -> Task<anyhow::Result<CommitDetails>> {
4964        let Some(repo) = self.active_repository.clone() else {
4965            return Task::ready(Err(anyhow::anyhow!("no active repo")));
4966        };
4967        repo.update(cx, |repo, cx| {
4968            let show = repo.show(sha);
4969            cx.spawn(async move |_, _| show.await?)
4970        })
4971    }
4972
4973    fn deploy_entry_context_menu(
4974        &mut self,
4975        position: Point<Pixels>,
4976        ix: usize,
4977        window: &mut Window,
4978        cx: &mut Context<Self>,
4979    ) {
4980        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4981            return;
4982        };
4983        let stage_title = if entry.status.staging().is_fully_staged() {
4984            "Unstage File"
4985        } else {
4986            "Stage File"
4987        };
4988        let restore_title = if entry.status.is_created() {
4989            "Trash File"
4990        } else {
4991            "Discard Changes"
4992        };
4993        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4994            let is_created = entry.status.is_created();
4995            context_menu
4996                .context(self.focus_handle.clone())
4997                .action(stage_title, ToggleStaged.boxed_clone())
4998                .action(restore_title, git::RestoreFile::default().boxed_clone())
4999                .action_disabled_when(
5000                    !is_created,
5001                    "Add to .gitignore",
5002                    git::AddToGitignore.boxed_clone(),
5003                )
5004                .separator()
5005                .action("Open Diff", menu::Confirm.boxed_clone())
5006                .action("Open File", menu::SecondaryConfirm.boxed_clone())
5007                .separator()
5008                .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
5009        });
5010        self.selected_entry = Some(ix);
5011        self.set_context_menu(context_menu, position, window, cx);
5012    }
5013
5014    fn deploy_panel_context_menu(
5015        &mut self,
5016        position: Point<Pixels>,
5017        window: &mut Window,
5018        cx: &mut Context<Self>,
5019    ) {
5020        let context_menu = git_panel_context_menu(
5021            self.focus_handle.clone(),
5022            GitMenuState {
5023                has_tracked_changes: self.has_tracked_changes(),
5024                has_staged_changes: self.has_staged_changes(),
5025                has_unstaged_changes: self.has_unstaged_changes(),
5026                has_new_changes: self.new_count > 0,
5027                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
5028                has_stash_items: self.stash_entries.entries.len() > 0,
5029                tree_view: GitPanelSettings::get_global(cx).tree_view,
5030            },
5031            window,
5032            cx,
5033        );
5034        self.set_context_menu(context_menu, position, window, cx);
5035    }
5036
5037    fn set_context_menu(
5038        &mut self,
5039        context_menu: Entity<ContextMenu>,
5040        position: Point<Pixels>,
5041        window: &Window,
5042        cx: &mut Context<Self>,
5043    ) {
5044        let subscription = cx.subscribe_in(
5045            &context_menu,
5046            window,
5047            |this, _, _: &DismissEvent, window, cx| {
5048                if this.context_menu.as_ref().is_some_and(|context_menu| {
5049                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
5050                }) {
5051                    cx.focus_self(window);
5052                }
5053                this.context_menu.take();
5054                cx.notify();
5055            },
5056        );
5057        self.context_menu = Some((context_menu, position, subscription));
5058        cx.notify();
5059    }
5060
5061    fn render_status_entry(
5062        &self,
5063        ix: usize,
5064        entry: &GitStatusEntry,
5065        depth: usize,
5066        has_write_access: bool,
5067        repo: &Repository,
5068        window: &Window,
5069        cx: &Context<Self>,
5070    ) -> AnyElement {
5071        let settings = GitPanelSettings::get_global(cx);
5072        let tree_view = settings.tree_view;
5073        let path_style = self.project.read(cx).path_style(cx);
5074        let git_path_style = ProjectSettings::get_global(cx).git.path_style;
5075        let display_name = entry.display_name(path_style);
5076
5077        let selected = self.selected_entry == Some(ix);
5078        let marked = self.marked_entries.contains(&ix);
5079        let status_style = settings.status_style;
5080        let status = entry.status;
5081        let file_icon = if settings.file_icons {
5082            FileIcons::get_icon(entry.repo_path.as_std_path(), cx)
5083        } else {
5084            None
5085        };
5086
5087        let has_conflict = status.is_conflicted();
5088        let is_modified = status.is_modified();
5089        let is_deleted = status.is_deleted();
5090        let is_created = status.is_created();
5091
5092        let label_color = if status_style == StatusStyle::LabelColor {
5093            if has_conflict {
5094                Color::VersionControlConflict
5095            } else if is_created {
5096                Color::VersionControlAdded
5097            } else if is_modified {
5098                Color::VersionControlModified
5099            } else if is_deleted {
5100                // We don't want a bunch of red labels in the list
5101                Color::Disabled
5102            } else {
5103                Color::VersionControlAdded
5104            }
5105        } else {
5106            Color::Default
5107        };
5108
5109        let path_color = if status.is_deleted() {
5110            Color::Disabled
5111        } else {
5112            Color::Muted
5113        };
5114
5115        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
5116        let checkbox_wrapper_id: ElementId =
5117            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
5118        let checkbox_id: ElementId =
5119            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
5120
5121        let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
5122        let mut is_staged: ToggleState = match stage_status {
5123            StageStatus::Staged => ToggleState::Selected,
5124            StageStatus::Unstaged => ToggleState::Unselected,
5125            StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5126        };
5127        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
5128            is_staged = ToggleState::Selected;
5129        }
5130
5131        let handle = cx.weak_entity();
5132
5133        let selected_bg_alpha = 0.08;
5134        let marked_bg_alpha = 0.12;
5135        let state_opacity_step = 0.04;
5136
5137        let info_color = cx.theme().status().info;
5138
5139        let base_bg = match (selected, marked) {
5140            (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
5141            (true, false) => info_color.alpha(selected_bg_alpha),
5142            (false, true) => info_color.alpha(marked_bg_alpha),
5143            _ => cx.theme().colors().ghost_element_background,
5144        };
5145
5146        let (hover_bg, active_bg) = if selected {
5147            (
5148                info_color.alpha(selected_bg_alpha + state_opacity_step),
5149                info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5150            )
5151        } else {
5152            (
5153                cx.theme().colors().ghost_element_hover,
5154                cx.theme().colors().ghost_element_active,
5155            )
5156        };
5157
5158        let name_row = h_flex()
5159            .min_w_0()
5160            .flex_1()
5161            .gap_1()
5162            .when(settings.file_icons, |this| {
5163                this.child(
5164                    file_icon
5165                        .map(|file_icon| {
5166                            Icon::from_path(file_icon)
5167                                .size(IconSize::Small)
5168                                .color(Color::Muted)
5169                        })
5170                        .unwrap_or_else(|| {
5171                            Icon::new(IconName::File)
5172                                .size(IconSize::Small)
5173                                .color(Color::Muted)
5174                        }),
5175                )
5176            })
5177            .when(status_style != StatusStyle::LabelColor, |el| {
5178                el.child(git_status_icon(status))
5179            })
5180            .map(|this| {
5181                if tree_view {
5182                    this.pl(px(depth as f32 * TREE_INDENT)).child(
5183                        self.entry_label(display_name, label_color)
5184                            .when(status.is_deleted(), Label::strikethrough)
5185                            .truncate(),
5186                    )
5187                } else {
5188                    this.child(self.path_formatted(
5189                        entry.parent_dir(path_style),
5190                        path_color,
5191                        display_name,
5192                        label_color,
5193                        path_style,
5194                        git_path_style,
5195                        status.is_deleted(),
5196                    ))
5197                }
5198            });
5199
5200        let id_for_diff_stat = id.clone();
5201
5202        h_flex()
5203            .id(id)
5204            .h(self.list_item_height())
5205            .w_full()
5206            .pl_3()
5207            .pr_1()
5208            .gap_1p5()
5209            .border_1()
5210            .border_r_2()
5211            .when(selected && self.focus_handle.is_focused(window), |el| {
5212                el.border_color(cx.theme().colors().panel_focused_border)
5213            })
5214            .bg(base_bg)
5215            .hover(|s| s.bg(hover_bg))
5216            .active(|s| s.bg(active_bg))
5217            .child(name_row)
5218            .when(GitPanelSettings::get_global(cx).diff_stats, |el| {
5219                el.when_some(entry.diff_stat, move |this, stat| {
5220                    let id = format!("diff-stat-{}", id_for_diff_stat);
5221                    this.child(ui::DiffStat::new(
5222                        id,
5223                        stat.added as usize,
5224                        stat.deleted as usize,
5225                    ))
5226                })
5227            })
5228            .child(
5229                div()
5230                    .id(checkbox_wrapper_id)
5231                    .flex_none()
5232                    .occlude()
5233                    .cursor_pointer()
5234                    .child(
5235                        Checkbox::new(checkbox_id, is_staged)
5236                            .disabled(!has_write_access)
5237                            .fill()
5238                            .elevation(ElevationIndex::Surface)
5239                            .on_click_ext({
5240                                let entry = entry.clone();
5241                                let this = cx.weak_entity();
5242                                move |_, click, window, cx| {
5243                                    this.update(cx, |this, cx| {
5244                                        if !has_write_access {
5245                                            return;
5246                                        }
5247                                        if click.modifiers().shift {
5248                                            this.stage_bulk(ix, cx);
5249                                        } else {
5250                                            let list_entry =
5251                                                if GitPanelSettings::get_global(cx).tree_view {
5252                                                    GitListEntry::TreeStatus(GitTreeStatusEntry {
5253                                                        entry: entry.clone(),
5254                                                        depth,
5255                                                    })
5256                                                } else {
5257                                                    GitListEntry::Status(entry.clone())
5258                                                };
5259                                            this.toggle_staged_for_entry(&list_entry, window, cx);
5260                                        }
5261                                        cx.stop_propagation();
5262                                    })
5263                                    .ok();
5264                                }
5265                            })
5266                            .tooltip(move |_window, cx| {
5267                                let action = match stage_status {
5268                                    StageStatus::Staged => "Unstage",
5269                                    StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5270                                };
5271                                let tooltip_name = action.to_string();
5272
5273                                Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5274                            }),
5275                    ),
5276            )
5277            .on_click({
5278                cx.listener(move |this, event: &ClickEvent, window, cx| {
5279                    this.selected_entry = Some(ix);
5280                    cx.notify();
5281                    if event.click_count() > 1 || event.modifiers().secondary() {
5282                        this.open_file(&Default::default(), window, cx)
5283                    } else {
5284                        this.open_diff(&Default::default(), window, cx);
5285                        this.focus_handle.focus(window, cx);
5286                    }
5287                })
5288            })
5289            .on_mouse_down(
5290                MouseButton::Right,
5291                move |event: &MouseDownEvent, window, cx| {
5292                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5293                    if event.button != MouseButton::Right {
5294                        return;
5295                    }
5296
5297                    let Some(this) = handle.upgrade() else {
5298                        return;
5299                    };
5300                    this.update(cx, |this, cx| {
5301                        this.deploy_entry_context_menu(event.position, ix, window, cx);
5302                    });
5303                    cx.stop_propagation();
5304                },
5305            )
5306            .into_any_element()
5307    }
5308
5309    fn render_directory_entry(
5310        &self,
5311        ix: usize,
5312        entry: &GitTreeDirEntry,
5313        has_write_access: bool,
5314        window: &Window,
5315        cx: &Context<Self>,
5316    ) -> AnyElement {
5317        // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5318        let selected = self.selected_entry == Some(ix);
5319        let label_color = Color::Muted;
5320
5321        let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5322        let checkbox_id: ElementId =
5323            ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5324        let checkbox_wrapper_id: ElementId =
5325            ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5326
5327        let selected_bg_alpha = 0.08;
5328        let state_opacity_step = 0.04;
5329
5330        let info_color = cx.theme().status().info;
5331        let colors = cx.theme().colors();
5332
5333        let (base_bg, hover_bg, active_bg) = if selected {
5334            (
5335                info_color.alpha(selected_bg_alpha),
5336                info_color.alpha(selected_bg_alpha + state_opacity_step),
5337                info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5338            )
5339        } else {
5340            (
5341                colors.ghost_element_background,
5342                colors.ghost_element_hover,
5343                colors.ghost_element_active,
5344            )
5345        };
5346
5347        let settings = GitPanelSettings::get_global(cx);
5348        let folder_icon = if settings.folder_icons {
5349            FileIcons::get_folder_icon(entry.expanded, entry.key.path.as_std_path(), cx)
5350        } else {
5351            FileIcons::get_chevron_icon(entry.expanded, cx)
5352        };
5353        let fallback_folder_icon = if settings.folder_icons {
5354            if entry.expanded {
5355                IconName::FolderOpen
5356            } else {
5357                IconName::Folder
5358            }
5359        } else {
5360            if entry.expanded {
5361                IconName::ChevronDown
5362            } else {
5363                IconName::ChevronRight
5364            }
5365        };
5366
5367        let stage_status = if let Some(repo) = &self.active_repository {
5368            self.stage_status_for_directory(entry, repo.read(cx))
5369        } else {
5370            util::debug_panic!(
5371                "Won't have entries to render without an active repository in Git Panel"
5372            );
5373            StageStatus::PartiallyStaged
5374        };
5375
5376        let toggle_state: ToggleState = match stage_status {
5377            StageStatus::Staged => ToggleState::Selected,
5378            StageStatus::Unstaged => ToggleState::Unselected,
5379            StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5380        };
5381
5382        let name_row = h_flex()
5383            .min_w_0()
5384            .gap_1()
5385            .pl(px(entry.depth as f32 * TREE_INDENT))
5386            .child(
5387                folder_icon
5388                    .map(|folder_icon| {
5389                        Icon::from_path(folder_icon)
5390                            .size(IconSize::Small)
5391                            .color(Color::Muted)
5392                    })
5393                    .unwrap_or_else(|| {
5394                        Icon::new(fallback_folder_icon)
5395                            .size(IconSize::Small)
5396                            .color(Color::Muted)
5397                    }),
5398            )
5399            .child(self.entry_label(entry.name.clone(), label_color).truncate());
5400
5401        h_flex()
5402            .id(id)
5403            .h(self.list_item_height())
5404            .min_w_0()
5405            .w_full()
5406            .pl_3()
5407            .pr_1()
5408            .gap_1p5()
5409            .justify_between()
5410            .border_1()
5411            .border_r_2()
5412            .when(selected && self.focus_handle.is_focused(window), |el| {
5413                el.border_color(cx.theme().colors().panel_focused_border)
5414            })
5415            .bg(base_bg)
5416            .hover(|s| s.bg(hover_bg))
5417            .active(|s| s.bg(active_bg))
5418            .child(name_row)
5419            .child(
5420                div()
5421                    .id(checkbox_wrapper_id)
5422                    .flex_none()
5423                    .occlude()
5424                    .cursor_pointer()
5425                    .child(
5426                        Checkbox::new(checkbox_id, toggle_state)
5427                            .disabled(!has_write_access)
5428                            .fill()
5429                            .elevation(ElevationIndex::Surface)
5430                            .on_click({
5431                                let entry = entry.clone();
5432                                let this = cx.weak_entity();
5433                                move |_, window, cx| {
5434                                    this.update(cx, |this, cx| {
5435                                        if !has_write_access {
5436                                            return;
5437                                        }
5438                                        this.toggle_staged_for_entry(
5439                                            &GitListEntry::Directory(entry.clone()),
5440                                            window,
5441                                            cx,
5442                                        );
5443                                        cx.stop_propagation();
5444                                    })
5445                                    .ok();
5446                                }
5447                            })
5448                            .tooltip(move |_window, cx| {
5449                                let action = match stage_status {
5450                                    StageStatus::Staged => "Unstage",
5451                                    StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5452                                };
5453                                Tooltip::simple(format!("{action} folder"), cx)
5454                            }),
5455                    ),
5456            )
5457            .on_click({
5458                let key = entry.key.clone();
5459                cx.listener(move |this, _event: &ClickEvent, window, cx| {
5460                    this.selected_entry = Some(ix);
5461                    this.toggle_directory(&key, window, cx);
5462                })
5463            })
5464            .into_any_element()
5465    }
5466
5467    fn path_formatted(
5468        &self,
5469        directory: Option<String>,
5470        path_color: Color,
5471        file_name: String,
5472        label_color: Color,
5473        path_style: PathStyle,
5474        git_path_style: GitPathStyle,
5475        strikethrough: bool,
5476    ) -> Div {
5477        let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5478        let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5479
5480        let file_name = format!("{} ", file_name);
5481
5482        h_flex()
5483            .min_w_0()
5484            .overflow_hidden()
5485            .when(file_path_first, |this| this.flex_row_reverse())
5486            .child(
5487                div().flex_none().child(
5488                    self.entry_label(file_name, label_color)
5489                        .when(strikethrough, Label::strikethrough),
5490                ),
5491            )
5492            .when_some(directory, |this, dir| {
5493                let path_name = if file_name_first {
5494                    dir
5495                } else {
5496                    format!("{dir}{}", path_style.primary_separator())
5497                };
5498
5499                this.child(
5500                    self.entry_label(path_name, path_color)
5501                        .truncate_start()
5502                        .when(strikethrough, Label::strikethrough),
5503                )
5504            })
5505    }
5506
5507    fn has_write_access(&self, cx: &App) -> bool {
5508        !self.project.read(cx).is_read_only(cx)
5509    }
5510
5511    pub fn amend_pending(&self) -> bool {
5512        self.amend_pending
5513    }
5514
5515    /// Sets the pending amend state, ensuring that the original commit message
5516    /// is either saved, when `value` is `true` and there's no pending amend, or
5517    /// restored, when `value` is `false` and there's a pending amend.
5518    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5519        if value && !self.amend_pending {
5520            let current_message = self.commit_message_buffer(cx).read(cx).text();
5521            self.original_commit_message = if current_message.trim().is_empty() {
5522                None
5523            } else {
5524                Some(current_message)
5525            };
5526        } else if !value && self.amend_pending {
5527            let message = self.original_commit_message.take().unwrap_or_default();
5528            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5529                let start = buffer.anchor_before(0);
5530                let end = buffer.anchor_after(buffer.len());
5531                buffer.edit([(start..end, message)], None, cx);
5532            });
5533        }
5534
5535        self.amend_pending = value;
5536        self.serialize(cx);
5537        cx.notify();
5538    }
5539
5540    pub fn signoff_enabled(&self) -> bool {
5541        self.signoff_enabled
5542    }
5543
5544    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5545        self.signoff_enabled = value;
5546        self.serialize(cx);
5547        cx.notify();
5548    }
5549
5550    pub fn toggle_signoff_enabled(
5551        &mut self,
5552        _: &Signoff,
5553        _window: &mut Window,
5554        cx: &mut Context<Self>,
5555    ) {
5556        self.set_signoff_enabled(!self.signoff_enabled, cx);
5557    }
5558
5559    pub async fn load(
5560        workspace: WeakEntity<Workspace>,
5561        mut cx: AsyncWindowContext,
5562    ) -> anyhow::Result<Entity<Self>> {
5563        let serialized_panel = match workspace
5564            .read_with(&cx, |workspace, cx| {
5565                Self::serialization_key(workspace).map(|key| (key, KeyValueStore::global(cx)))
5566            })
5567            .ok()
5568            .flatten()
5569        {
5570            Some((serialization_key, kvp)) => cx
5571                .background_spawn(async move { kvp.read_kvp(&serialization_key) })
5572                .await
5573                .context("loading git panel")
5574                .log_err()
5575                .flatten()
5576                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5577                .transpose()
5578                .log_err()
5579                .flatten(),
5580            None => None,
5581        };
5582
5583        workspace.update_in(&mut cx, |workspace, window, cx| {
5584            let panel = GitPanel::new(workspace, window, cx);
5585
5586            if let Some(serialized_panel) = serialized_panel {
5587                panel.update(cx, |panel, cx| {
5588                    panel.amend_pending = serialized_panel.amend_pending;
5589                    panel.signoff_enabled = serialized_panel.signoff_enabled;
5590                    cx.notify();
5591                })
5592            }
5593
5594            panel
5595        })
5596    }
5597
5598    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5599        let Some(op) = self.bulk_staging.as_ref() else {
5600            return;
5601        };
5602        let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5603            return;
5604        };
5605        if let Some(entry) = self.entries.get(index)
5606            && let Some(entry) = entry.status_entry()
5607        {
5608            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5609        }
5610        if index < anchor_index {
5611            std::mem::swap(&mut index, &mut anchor_index);
5612        }
5613        let entries = self
5614            .entries
5615            .get(anchor_index..=index)
5616            .unwrap_or_default()
5617            .iter()
5618            .filter_map(|entry| entry.status_entry().cloned())
5619            .collect::<Vec<_>>();
5620        self.change_file_stage(true, entries, cx);
5621    }
5622
5623    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5624        let Some(repo) = self.active_repository.as_ref() else {
5625            return;
5626        };
5627        self.bulk_staging = Some(BulkStaging {
5628            repo_id: repo.read(cx).id,
5629            anchor: path,
5630        });
5631    }
5632
5633    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5634        self.set_amend_pending(!self.amend_pending, cx);
5635        if self.amend_pending {
5636            self.load_last_commit_message(cx);
5637        }
5638    }
5639}
5640
5641#[cfg(any(test, feature = "test-support"))]
5642impl GitPanel {
5643    pub fn new_test(
5644        workspace: &mut Workspace,
5645        window: &mut Window,
5646        cx: &mut Context<Workspace>,
5647    ) -> Entity<Self> {
5648        Self::new(workspace, window, cx)
5649    }
5650
5651    pub fn active_repository(&self) -> Option<&Entity<Repository>> {
5652        self.active_repository.as_ref()
5653    }
5654}
5655
5656impl Render for GitPanel {
5657    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5658        let project = self.project.read(cx);
5659        let has_entries = !self.entries.is_empty();
5660        let room = self.workspace.upgrade().and_then(|_workspace| {
5661            call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
5662        });
5663
5664        let has_write_access = self.has_write_access(cx);
5665
5666        let has_co_authors = room.is_some_and(|room| {
5667            self.load_local_committer(cx);
5668            let room = room.read(cx);
5669            room.remote_participants()
5670                .values()
5671                .any(|remote_participant| remote_participant.can_write())
5672        });
5673
5674        v_flex()
5675            .id("git_panel")
5676            .key_context(self.dispatch_context(window, cx))
5677            .track_focus(&self.focus_handle)
5678            .when(has_write_access && !project.is_read_only(cx), |this| {
5679                this.on_action(cx.listener(Self::toggle_staged_for_selected))
5680                    .on_action(cx.listener(Self::stage_range))
5681                    .on_action(cx.listener(GitPanel::on_commit))
5682                    .on_action(cx.listener(GitPanel::on_amend))
5683                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5684                    .on_action(cx.listener(Self::stage_all))
5685                    .on_action(cx.listener(Self::unstage_all))
5686                    .on_action(cx.listener(Self::stage_selected))
5687                    .on_action(cx.listener(Self::unstage_selected))
5688                    .on_action(cx.listener(Self::restore_tracked_files))
5689                    .on_action(cx.listener(Self::revert_selected))
5690                    .on_action(cx.listener(Self::add_to_gitignore))
5691                    .on_action(cx.listener(Self::clean_all))
5692                    .on_action(cx.listener(Self::generate_commit_message_action))
5693                    .on_action(cx.listener(Self::stash_all))
5694                    .on_action(cx.listener(Self::stash_pop))
5695            })
5696            .on_action(cx.listener(Self::collapse_selected_entry))
5697            .on_action(cx.listener(Self::expand_selected_entry))
5698            .on_action(cx.listener(Self::select_first))
5699            .on_action(cx.listener(Self::select_next))
5700            .on_action(cx.listener(Self::select_previous))
5701            .on_action(cx.listener(Self::select_last))
5702            .on_action(cx.listener(Self::first_entry))
5703            .on_action(cx.listener(Self::next_entry))
5704            .on_action(cx.listener(Self::previous_entry))
5705            .on_action(cx.listener(Self::last_entry))
5706            .on_action(cx.listener(Self::close_panel))
5707            .on_action(cx.listener(Self::open_diff))
5708            .on_action(cx.listener(Self::open_file))
5709            .on_action(cx.listener(Self::file_history))
5710            .on_action(cx.listener(Self::focus_changes_list))
5711            .on_action(cx.listener(Self::focus_editor))
5712            .on_action(cx.listener(Self::expand_commit_editor))
5713            .when(has_write_access && has_co_authors, |git_panel| {
5714                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5715            })
5716            .on_action(cx.listener(Self::toggle_sort_by_path))
5717            .on_action(cx.listener(Self::toggle_tree_view))
5718            .size_full()
5719            .overflow_hidden()
5720            .bg(cx.theme().colors().panel_background)
5721            .child(
5722                v_flex()
5723                    .size_full()
5724                    .children(self.render_panel_header(window, cx))
5725                    .map(|this| {
5726                        if let Some(repo) = self.active_repository.clone()
5727                            && has_entries
5728                        {
5729                            this.child(self.render_entries(has_write_access, repo, window, cx))
5730                        } else {
5731                            this.child(self.render_empty_state(cx).into_any_element())
5732                        }
5733                    })
5734                    .children(self.render_footer(window, cx))
5735                    .when(self.amend_pending, |this| {
5736                        this.child(self.render_pending_amend(cx))
5737                    })
5738                    .when(!self.amend_pending, |this| {
5739                        this.children(self.render_previous_commit(window, cx))
5740                    })
5741                    .into_any_element(),
5742            )
5743            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5744                deferred(
5745                    anchored()
5746                        .position(*position)
5747                        .anchor(Corner::TopLeft)
5748                        .child(menu.clone()),
5749                )
5750                .with_priority(1)
5751            }))
5752    }
5753}
5754
5755impl Focusable for GitPanel {
5756    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5757        if self.entries.is_empty() {
5758            self.commit_editor.focus_handle(cx)
5759        } else {
5760            self.focus_handle.clone()
5761        }
5762    }
5763}
5764
5765impl EventEmitter<Event> for GitPanel {}
5766
5767impl EventEmitter<PanelEvent> for GitPanel {}
5768
5769pub(crate) struct GitPanelAddon {
5770    pub(crate) workspace: WeakEntity<Workspace>,
5771}
5772
5773impl editor::Addon for GitPanelAddon {
5774    fn to_any(&self) -> &dyn std::any::Any {
5775        self
5776    }
5777
5778    fn render_buffer_header_controls(
5779        &self,
5780        _excerpt_info: &ExcerptBoundaryInfo,
5781        buffer: &language::BufferSnapshot,
5782        window: &Window,
5783        cx: &App,
5784    ) -> Option<AnyElement> {
5785        let file = buffer.file()?;
5786        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5787
5788        git_panel
5789            .read(cx)
5790            .render_buffer_header_controls(&git_panel, file, window, cx)
5791    }
5792}
5793
5794impl Panel for GitPanel {
5795    fn persistent_name() -> &'static str {
5796        "GitPanel"
5797    }
5798
5799    fn panel_key() -> &'static str {
5800        GIT_PANEL_KEY
5801    }
5802
5803    fn position(&self, _: &Window, cx: &App) -> DockPosition {
5804        GitPanelSettings::get_global(cx).dock
5805    }
5806
5807    fn position_is_valid(&self, position: DockPosition) -> bool {
5808        matches!(position, DockPosition::Left | DockPosition::Right)
5809    }
5810
5811    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5812        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5813            settings.git_panel.get_or_insert_default().dock = Some(position.into())
5814        });
5815    }
5816
5817    fn default_size(&self, _: &Window, cx: &App) -> Pixels {
5818        GitPanelSettings::get_global(cx).default_width
5819    }
5820
5821    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5822        Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
5823    }
5824
5825    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5826        Some("Git Panel")
5827    }
5828
5829    fn icon_label(&self, _: &Window, cx: &App) -> Option<String> {
5830        if !GitPanelSettings::get_global(cx).show_count_badge {
5831            return None;
5832        }
5833        let total = self.changes_count;
5834        (total > 0).then(|| total.to_string())
5835    }
5836
5837    fn toggle_action(&self) -> Box<dyn Action> {
5838        Box::new(ToggleFocus)
5839    }
5840
5841    fn starts_open(&self, _: &Window, cx: &App) -> bool {
5842        GitPanelSettings::get_global(cx).starts_open
5843    }
5844
5845    fn activation_priority(&self) -> u32 {
5846        3
5847    }
5848}
5849
5850impl PanelHeader for GitPanel {}
5851
5852pub fn panel_editor_container(_window: &mut Window, cx: &mut App) -> Div {
5853    v_flex()
5854        .size_full()
5855        .gap(px(8.))
5856        .p_2()
5857        .bg(cx.theme().colors().editor_background)
5858}
5859
5860pub(crate) fn panel_editor_style(monospace: bool, window: &Window, cx: &App) -> EditorStyle {
5861    let settings = ThemeSettings::get_global(cx);
5862
5863    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
5864
5865    let (font_family, font_fallbacks, font_features, font_weight, line_height) = if monospace {
5866        (
5867            settings.buffer_font.family.clone(),
5868            settings.buffer_font.fallbacks.clone(),
5869            settings.buffer_font.features.clone(),
5870            settings.buffer_font.weight,
5871            font_size * settings.buffer_line_height.value(),
5872        )
5873    } else {
5874        (
5875            settings.ui_font.family.clone(),
5876            settings.ui_font.fallbacks.clone(),
5877            settings.ui_font.features.clone(),
5878            settings.ui_font.weight,
5879            window.line_height(),
5880        )
5881    };
5882
5883    EditorStyle {
5884        background: cx.theme().colors().editor_background,
5885        local_player: cx.theme().players().local(),
5886        text: TextStyle {
5887            color: cx.theme().colors().text,
5888            font_family,
5889            font_fallbacks,
5890            font_features,
5891            font_size: TextSize::Small.rems(cx).into(),
5892            font_weight,
5893            line_height: line_height.into(),
5894            ..Default::default()
5895        },
5896        syntax: cx.theme().syntax().clone(),
5897        ..Default::default()
5898    }
5899}
5900
5901struct GitPanelMessageTooltip {
5902    commit_tooltip: Option<Entity<CommitTooltip>>,
5903}
5904
5905impl GitPanelMessageTooltip {
5906    fn new(
5907        git_panel: Entity<GitPanel>,
5908        sha: SharedString,
5909        repository: Entity<Repository>,
5910        window: &mut Window,
5911        cx: &mut App,
5912    ) -> Entity<Self> {
5913        let remote_url = repository.read(cx).default_remote_url();
5914        cx.new(|cx| {
5915            cx.spawn_in(window, async move |this, cx| {
5916                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5917                    (
5918                        git_panel.load_commit_details(sha.to_string(), cx),
5919                        git_panel.workspace.clone(),
5920                    )
5921                });
5922                let details = details.await?;
5923                let provider_registry = cx
5924                    .update(|_, app| GitHostingProviderRegistry::default_global(app))
5925                    .ok();
5926
5927                let commit_details = crate::commit_tooltip::CommitDetails {
5928                    sha: details.sha.clone(),
5929                    author_name: details.author_name.clone(),
5930                    author_email: details.author_email.clone(),
5931                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5932                    message: Some(ParsedCommitMessage::parse(
5933                        details.sha.to_string(),
5934                        details.message.to_string(),
5935                        remote_url.as_deref(),
5936                        provider_registry,
5937                    )),
5938                };
5939
5940                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5941                    this.commit_tooltip = Some(cx.new(move |cx| {
5942                        CommitTooltip::new(commit_details, repository, workspace, cx)
5943                    }));
5944                    cx.notify();
5945                })
5946            })
5947            .detach();
5948
5949            Self {
5950                commit_tooltip: None,
5951            }
5952        })
5953    }
5954}
5955
5956impl Render for GitPanelMessageTooltip {
5957    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5958        if let Some(commit_tooltip) = &self.commit_tooltip {
5959            commit_tooltip.clone().into_any_element()
5960        } else {
5961            gpui::Empty.into_any_element()
5962        }
5963    }
5964}
5965
5966#[derive(IntoElement, RegisterComponent)]
5967pub struct PanelRepoFooter {
5968    active_repository: SharedString,
5969    branch: Option<Branch>,
5970    head_commit: Option<CommitDetails>,
5971
5972    // Getting a GitPanel in previews will be difficult.
5973    //
5974    // For now just take an option here, and we won't bind handlers to buttons in previews.
5975    git_panel: Option<Entity<GitPanel>>,
5976}
5977
5978impl PanelRepoFooter {
5979    pub fn new(
5980        active_repository: SharedString,
5981        branch: Option<Branch>,
5982        head_commit: Option<CommitDetails>,
5983        git_panel: Option<Entity<GitPanel>>,
5984    ) -> Self {
5985        Self {
5986            active_repository,
5987            branch,
5988            head_commit,
5989            git_panel,
5990        }
5991    }
5992
5993    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5994        Self {
5995            active_repository,
5996            branch,
5997            head_commit: None,
5998            git_panel: None,
5999        }
6000    }
6001}
6002
6003impl RenderOnce for PanelRepoFooter {
6004    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
6005        let project = self
6006            .git_panel
6007            .as_ref()
6008            .map(|panel| panel.read(cx).project.clone());
6009
6010        let (workspace, repo) = self
6011            .git_panel
6012            .as_ref()
6013            .map(|panel| {
6014                let panel = panel.read(cx);
6015                (panel.workspace.clone(), panel.active_repository.clone())
6016            })
6017            .unzip();
6018
6019        let single_repo = project
6020            .as_ref()
6021            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
6022            .unwrap_or(true);
6023
6024        const MAX_BRANCH_LEN: usize = 16;
6025        const MAX_REPO_LEN: usize = 16;
6026        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
6027        const MAX_SHORT_SHA_LEN: usize = 8;
6028        let branch_name = self
6029            .branch
6030            .as_ref()
6031            .map(|branch| branch.name().to_owned())
6032            .or_else(|| {
6033                self.head_commit.as_ref().map(|commit| {
6034                    commit
6035                        .sha
6036                        .chars()
6037                        .take(MAX_SHORT_SHA_LEN)
6038                        .collect::<String>()
6039                })
6040            })
6041            .unwrap_or_else(|| " (no branch)".to_owned());
6042        let show_separator = self.branch.is_some() || self.head_commit.is_some();
6043
6044        let active_repo_name = self.active_repository.clone();
6045
6046        let branch_actual_len = branch_name.len();
6047        let repo_actual_len = active_repo_name.len();
6048
6049        // ideally, show the whole branch and repo names but
6050        // when we can't, use a budget to allocate space between the two
6051        let (repo_display_len, branch_display_len) =
6052            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
6053                (repo_actual_len, branch_actual_len)
6054            } else if branch_actual_len <= MAX_BRANCH_LEN {
6055                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
6056                (repo_space, branch_actual_len)
6057            } else if repo_actual_len <= MAX_REPO_LEN {
6058                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
6059                (repo_actual_len, branch_space)
6060            } else {
6061                (MAX_REPO_LEN, MAX_BRANCH_LEN)
6062            };
6063
6064        let truncated_repo_name = if repo_actual_len <= repo_display_len {
6065            active_repo_name.to_string()
6066        } else {
6067            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
6068        };
6069
6070        let truncated_branch_name = if branch_actual_len <= branch_display_len {
6071            branch_name
6072        } else {
6073            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
6074        };
6075
6076        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
6077            .size(ButtonSize::None)
6078            .label_size(LabelSize::Small);
6079
6080        let repo_selector = PopoverMenu::new("repository-switcher")
6081            .menu({
6082                let project = project;
6083                move |window, cx| {
6084                    let project = project.clone()?;
6085                    Some(cx.new(|cx| RepositorySelector::new(project, rems(20.), window, cx)))
6086                }
6087            })
6088            .trigger_with_tooltip(
6089                repo_selector_trigger
6090                    .when(single_repo, |this| this.disabled(true).color(Color::Muted))
6091                    .truncate(true),
6092                move |_, cx| {
6093                    if single_repo {
6094                        cx.new(|_| Empty).into()
6095                    } else {
6096                        Tooltip::simple("Switch Active Repository", cx)
6097                    }
6098                },
6099            )
6100            .anchor(Corner::BottomLeft)
6101            .offset(gpui::Point {
6102                x: px(0.0),
6103                y: px(-2.0),
6104            })
6105            .into_any_element();
6106
6107        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
6108            .size(ButtonSize::None)
6109            .label_size(LabelSize::Small)
6110            .truncate(true)
6111            .on_click(|_, window, cx| {
6112                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
6113            });
6114
6115        let branch_selector = PopoverMenu::new("popover-button")
6116            .menu(move |window, cx| {
6117                let workspace = workspace.clone()?;
6118                let repo = repo.clone().flatten();
6119                Some(branch_picker::popover(workspace, false, repo, window, cx))
6120            })
6121            .trigger_with_tooltip(
6122                branch_selector_button,
6123                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
6124            )
6125            .anchor(Corner::BottomLeft)
6126            .offset(gpui::Point {
6127                x: px(0.0),
6128                y: px(-2.0),
6129            });
6130
6131        h_flex()
6132            .h(px(36.))
6133            .w_full()
6134            .px_2()
6135            .justify_between()
6136            .gap_1()
6137            .child(
6138                h_flex()
6139                    .flex_1()
6140                    .overflow_hidden()
6141                    .gap_px()
6142                    .child(Icon::new(IconName::GitBranch).size(IconSize::Small).color(
6143                        if single_repo {
6144                            Color::Disabled
6145                        } else {
6146                            Color::Muted
6147                        },
6148                    ))
6149                    .child(repo_selector)
6150                    .when(show_separator, |this| {
6151                        this.child(
6152                            div()
6153                                .text_sm()
6154                                .text_color(cx.theme().colors().icon_muted.opacity(0.5))
6155                                .child("/"),
6156                        )
6157                    })
6158                    .child(branch_selector),
6159            )
6160            .children(if let Some(git_panel) = self.git_panel {
6161                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
6162            } else {
6163                None
6164            })
6165    }
6166}
6167
6168impl Component for PanelRepoFooter {
6169    fn scope() -> ComponentScope {
6170        ComponentScope::VersionControl
6171    }
6172
6173    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
6174        let unknown_upstream = None;
6175        let no_remote_upstream = Some(UpstreamTracking::Gone);
6176        let ahead_of_upstream = Some(
6177            UpstreamTrackingStatus {
6178                ahead: 2,
6179                behind: 0,
6180            }
6181            .into(),
6182        );
6183        let behind_upstream = Some(
6184            UpstreamTrackingStatus {
6185                ahead: 0,
6186                behind: 2,
6187            }
6188            .into(),
6189        );
6190        let ahead_and_behind_upstream = Some(
6191            UpstreamTrackingStatus {
6192                ahead: 3,
6193                behind: 1,
6194            }
6195            .into(),
6196        );
6197
6198        let not_ahead_or_behind_upstream = Some(
6199            UpstreamTrackingStatus {
6200                ahead: 0,
6201                behind: 0,
6202            }
6203            .into(),
6204        );
6205
6206        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
6207            Branch {
6208                is_head: true,
6209                ref_name: "some-branch".into(),
6210                upstream: upstream.map(|tracking| Upstream {
6211                    ref_name: "origin/some-branch".into(),
6212                    tracking,
6213                }),
6214                most_recent_commit: Some(CommitSummary {
6215                    sha: "abc123".into(),
6216                    subject: "Modify stuff".into(),
6217                    commit_timestamp: 1710932954,
6218                    author_name: "John Doe".into(),
6219                    has_parent: true,
6220                }),
6221            }
6222        }
6223
6224        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
6225            Branch {
6226                is_head: true,
6227                ref_name: branch_name.to_string().into(),
6228                upstream: upstream.map(|tracking| Upstream {
6229                    ref_name: format!("zed/{}", branch_name).into(),
6230                    tracking,
6231                }),
6232                most_recent_commit: Some(CommitSummary {
6233                    sha: "abc123".into(),
6234                    subject: "Modify stuff".into(),
6235                    commit_timestamp: 1710932954,
6236                    author_name: "John Doe".into(),
6237                    has_parent: true,
6238                }),
6239            }
6240        }
6241
6242        fn active_repository(id: usize) -> SharedString {
6243            format!("repo-{}", id).into()
6244        }
6245
6246        let example_width = px(340.);
6247        Some(
6248            v_flex()
6249                .gap_6()
6250                .w_full()
6251                .flex_none()
6252                .children(vec![
6253                    example_group_with_title(
6254                        "Action Button States",
6255                        vec![
6256                            single_example(
6257                                "No Branch",
6258                                div()
6259                                    .w(example_width)
6260                                    .overflow_hidden()
6261                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
6262                                    .into_any_element(),
6263                            ),
6264                            single_example(
6265                                "Remote status unknown",
6266                                div()
6267                                    .w(example_width)
6268                                    .overflow_hidden()
6269                                    .child(PanelRepoFooter::new_preview(
6270                                        active_repository(2),
6271                                        Some(branch(unknown_upstream)),
6272                                    ))
6273                                    .into_any_element(),
6274                            ),
6275                            single_example(
6276                                "No Remote Upstream",
6277                                div()
6278                                    .w(example_width)
6279                                    .overflow_hidden()
6280                                    .child(PanelRepoFooter::new_preview(
6281                                        active_repository(3),
6282                                        Some(branch(no_remote_upstream)),
6283                                    ))
6284                                    .into_any_element(),
6285                            ),
6286                            single_example(
6287                                "Not Ahead or Behind",
6288                                div()
6289                                    .w(example_width)
6290                                    .overflow_hidden()
6291                                    .child(PanelRepoFooter::new_preview(
6292                                        active_repository(4),
6293                                        Some(branch(not_ahead_or_behind_upstream)),
6294                                    ))
6295                                    .into_any_element(),
6296                            ),
6297                            single_example(
6298                                "Behind remote",
6299                                div()
6300                                    .w(example_width)
6301                                    .overflow_hidden()
6302                                    .child(PanelRepoFooter::new_preview(
6303                                        active_repository(5),
6304                                        Some(branch(behind_upstream)),
6305                                    ))
6306                                    .into_any_element(),
6307                            ),
6308                            single_example(
6309                                "Ahead of remote",
6310                                div()
6311                                    .w(example_width)
6312                                    .overflow_hidden()
6313                                    .child(PanelRepoFooter::new_preview(
6314                                        active_repository(6),
6315                                        Some(branch(ahead_of_upstream)),
6316                                    ))
6317                                    .into_any_element(),
6318                            ),
6319                            single_example(
6320                                "Ahead and behind remote",
6321                                div()
6322                                    .w(example_width)
6323                                    .overflow_hidden()
6324                                    .child(PanelRepoFooter::new_preview(
6325                                        active_repository(7),
6326                                        Some(branch(ahead_and_behind_upstream)),
6327                                    ))
6328                                    .into_any_element(),
6329                            ),
6330                        ],
6331                    )
6332                    .grow()
6333                    .vertical(),
6334                ])
6335                .children(vec![
6336                    example_group_with_title(
6337                        "Labels",
6338                        vec![
6339                            single_example(
6340                                "Short Branch & Repo",
6341                                div()
6342                                    .w(example_width)
6343                                    .overflow_hidden()
6344                                    .child(PanelRepoFooter::new_preview(
6345                                        SharedString::from("zed"),
6346                                        Some(custom("main", behind_upstream)),
6347                                    ))
6348                                    .into_any_element(),
6349                            ),
6350                            single_example(
6351                                "Long Branch",
6352                                div()
6353                                    .w(example_width)
6354                                    .overflow_hidden()
6355                                    .child(PanelRepoFooter::new_preview(
6356                                        SharedString::from("zed"),
6357                                        Some(custom(
6358                                            "redesign-and-update-git-ui-list-entry-style",
6359                                            behind_upstream,
6360                                        )),
6361                                    ))
6362                                    .into_any_element(),
6363                            ),
6364                            single_example(
6365                                "Long Repo",
6366                                div()
6367                                    .w(example_width)
6368                                    .overflow_hidden()
6369                                    .child(PanelRepoFooter::new_preview(
6370                                        SharedString::from("zed-industries-community-examples"),
6371                                        Some(custom("gpui", ahead_of_upstream)),
6372                                    ))
6373                                    .into_any_element(),
6374                            ),
6375                            single_example(
6376                                "Long Repo & Branch",
6377                                div()
6378                                    .w(example_width)
6379                                    .overflow_hidden()
6380                                    .child(PanelRepoFooter::new_preview(
6381                                        SharedString::from("zed-industries-community-examples"),
6382                                        Some(custom(
6383                                            "redesign-and-update-git-ui-list-entry-style",
6384                                            behind_upstream,
6385                                        )),
6386                                    ))
6387                                    .into_any_element(),
6388                            ),
6389                            single_example(
6390                                "Uppercase Repo",
6391                                div()
6392                                    .w(example_width)
6393                                    .overflow_hidden()
6394                                    .child(PanelRepoFooter::new_preview(
6395                                        SharedString::from("LICENSES"),
6396                                        Some(custom("main", ahead_of_upstream)),
6397                                    ))
6398                                    .into_any_element(),
6399                            ),
6400                            single_example(
6401                                "Uppercase Branch",
6402                                div()
6403                                    .w(example_width)
6404                                    .overflow_hidden()
6405                                    .child(PanelRepoFooter::new_preview(
6406                                        SharedString::from("zed"),
6407                                        Some(custom("update-README", behind_upstream)),
6408                                    ))
6409                                    .into_any_element(),
6410                            ),
6411                        ],
6412                    )
6413                    .grow()
6414                    .vertical(),
6415                ])
6416                .into_any_element(),
6417        )
6418    }
6419}
6420
6421fn open_output(
6422    operation: impl Into<SharedString>,
6423    workspace: &mut Workspace,
6424    output: &str,
6425    window: &mut Window,
6426    cx: &mut Context<Workspace>,
6427) {
6428    let operation = operation.into();
6429
6430    let mut handler = GitOutputHandler::default();
6431    let mut processor = ansi::Processor::<ansi::StdSyncHandler>::default();
6432    processor.advance(&mut handler, output.as_bytes());
6433    let plain_text = handler.output;
6434
6435    let buffer = cx.new(|cx| Buffer::local(plain_text.as_str(), cx));
6436    buffer.update(cx, |buffer, cx| {
6437        buffer.set_capability(language::Capability::ReadOnly, cx);
6438    });
6439    let editor = cx.new(|cx| {
6440        let mut editor = Editor::for_buffer(buffer, None, window, cx);
6441        editor.buffer().update(cx, |buffer, cx| {
6442            buffer.set_title(format!("Output from git {operation}"), cx);
6443        });
6444        editor.set_read_only(true);
6445        editor
6446    });
6447
6448    workspace.add_item_to_center(Box::new(editor), window, cx);
6449}
6450
6451#[derive(Default)]
6452struct GitOutputHandler {
6453    output: String,
6454    line_start: usize,
6455}
6456
6457impl ansi::Handler for GitOutputHandler {
6458    fn input(&mut self, c: char) {
6459        self.output.push(c);
6460    }
6461
6462    fn linefeed(&mut self) {
6463        self.output.push('\n');
6464        self.line_start = self.output.len();
6465    }
6466
6467    fn carriage_return(&mut self) {
6468        self.output.truncate(self.line_start);
6469    }
6470
6471    fn put_tab(&mut self, count: u16) {
6472        self.output
6473            .extend(std::iter::repeat_n('\t', count as usize));
6474    }
6475}
6476
6477pub(crate) fn show_error_toast(
6478    workspace: Entity<Workspace>,
6479    action: impl Into<SharedString>,
6480    e: anyhow::Error,
6481    cx: &mut App,
6482) {
6483    let action = action.into();
6484    let message = format_git_error_toast_message(&e);
6485    if message
6486        .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6487        .next()
6488        .is_some()
6489    { // Hide the cancelled by user message
6490    } else {
6491        workspace.update(cx, |workspace, cx| {
6492            let workspace_weak = cx.weak_entity();
6493            let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6494                this.icon(
6495                    Icon::new(IconName::XCircle)
6496                        .size(IconSize::Small)
6497                        .color(Color::Error),
6498                )
6499                .action("View Log", move |window, cx| {
6500                    let message = message.clone();
6501                    let action = action.clone();
6502                    workspace_weak
6503                        .update(cx, move |workspace, cx| {
6504                            open_output(action, workspace, &message, window, cx)
6505                        })
6506                        .ok();
6507                })
6508            });
6509            workspace.toggle_status_toast(toast, cx)
6510        });
6511    }
6512}
6513
6514fn rpc_error_raw_message_from_chain(error: &anyhow::Error) -> Option<&str> {
6515    error
6516        .chain()
6517        .find_map(|cause| cause.downcast_ref::<RpcError>().map(RpcError::raw_message))
6518}
6519
6520fn format_git_error_toast_message(error: &anyhow::Error) -> String {
6521    if let Some(message) = rpc_error_raw_message_from_chain(error) {
6522        message.trim().to_string()
6523    } else {
6524        error.to_string().trim().to_string()
6525    }
6526}
6527
6528#[cfg(test)]
6529mod tests {
6530    use git::{
6531        repository::repo_path,
6532        status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6533    };
6534    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext, px};
6535    use indoc::indoc;
6536    use project::FakeFs;
6537    use serde_json::json;
6538    use settings::SettingsStore;
6539    use theme::LoadThemes;
6540    use util::path;
6541    use util::rel_path::rel_path;
6542
6543    use workspace::MultiWorkspace;
6544
6545    use super::*;
6546
6547    fn init_test(cx: &mut gpui::TestAppContext) {
6548        zlog::init_test();
6549
6550        cx.update(|cx| {
6551            let settings_store = SettingsStore::test(cx);
6552            cx.set_global(settings_store);
6553            theme_settings::init(LoadThemes::JustBase, cx);
6554            editor::init(cx);
6555            crate::init(cx);
6556        });
6557    }
6558
6559    #[test]
6560    fn test_format_git_error_toast_message_prefers_raw_rpc_message() {
6561        let rpc_error = RpcError::from_proto(
6562            &proto::Error {
6563                message:
6564                    "Your local changes to the following files would be overwritten by merge\n"
6565                        .to_string(),
6566                code: proto::ErrorCode::Internal as i32,
6567                tags: Default::default(),
6568            },
6569            "Pull",
6570        );
6571
6572        let message = format_git_error_toast_message(&rpc_error);
6573        assert_eq!(
6574            message,
6575            "Your local changes to the following files would be overwritten by merge"
6576        );
6577    }
6578
6579    #[test]
6580    fn test_format_git_error_toast_message_prefers_raw_rpc_message_when_wrapped() {
6581        let rpc_error = RpcError::from_proto(
6582            &proto::Error {
6583                message:
6584                    "Your local changes to the following files would be overwritten by merge\n"
6585                        .to_string(),
6586                code: proto::ErrorCode::Internal as i32,
6587                tags: Default::default(),
6588            },
6589            "Pull",
6590        );
6591        let wrapped = rpc_error.context("sending pull request");
6592
6593        let message = format_git_error_toast_message(&wrapped);
6594        assert_eq!(
6595            message,
6596            "Your local changes to the following files would be overwritten by merge"
6597        );
6598    }
6599
6600    #[gpui::test]
6601    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6602        init_test(cx);
6603        let fs = FakeFs::new(cx.background_executor.clone());
6604        fs.insert_tree(
6605            "/root",
6606            json!({
6607                "zed": {
6608                    ".git": {},
6609                    "crates": {
6610                        "gpui": {
6611                            "gpui.rs": "fn main() {}"
6612                        },
6613                        "util": {
6614                            "util.rs": "fn do_it() {}"
6615                        }
6616                    }
6617                },
6618            }),
6619        )
6620        .await;
6621
6622        fs.set_status_for_repo(
6623            Path::new(path!("/root/zed/.git")),
6624            &[
6625                ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6626                ("crates/util/util.rs", StatusCode::Modified.worktree()),
6627            ],
6628        );
6629
6630        let project =
6631            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6632        let window_handle =
6633            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6634        let workspace = window_handle
6635            .read_with(cx, |mw, _| mw.workspace().clone())
6636            .unwrap();
6637        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6638
6639        cx.read(|cx| {
6640            project
6641                .read(cx)
6642                .worktrees(cx)
6643                .next()
6644                .unwrap()
6645                .read(cx)
6646                .as_local()
6647                .unwrap()
6648                .scan_complete()
6649        })
6650        .await;
6651
6652        cx.executor().run_until_parked();
6653
6654        let panel = workspace.update_in(cx, GitPanel::new);
6655
6656        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6657            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6658        });
6659        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6660        handle.await;
6661
6662        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6663        pretty_assertions::assert_eq!(
6664            entries,
6665            [
6666                GitListEntry::Header(GitHeaderEntry {
6667                    header: Section::Tracked
6668                }),
6669                GitListEntry::Status(GitStatusEntry {
6670                    repo_path: repo_path("crates/gpui/gpui.rs"),
6671                    status: StatusCode::Modified.worktree(),
6672                    staging: StageStatus::Unstaged,
6673                    diff_stat: Some(DiffStat {
6674                        added: 1,
6675                        deleted: 1,
6676                    }),
6677                }),
6678                GitListEntry::Status(GitStatusEntry {
6679                    repo_path: repo_path("crates/util/util.rs"),
6680                    status: StatusCode::Modified.worktree(),
6681                    staging: StageStatus::Unstaged,
6682                    diff_stat: Some(DiffStat {
6683                        added: 1,
6684                        deleted: 1,
6685                    }),
6686                },),
6687            ],
6688        );
6689
6690        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6691            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6692        });
6693        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6694        handle.await;
6695        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6696        pretty_assertions::assert_eq!(
6697            entries,
6698            [
6699                GitListEntry::Header(GitHeaderEntry {
6700                    header: Section::Tracked
6701                }),
6702                GitListEntry::Status(GitStatusEntry {
6703                    repo_path: repo_path("crates/gpui/gpui.rs"),
6704                    status: StatusCode::Modified.worktree(),
6705                    staging: StageStatus::Unstaged,
6706                    diff_stat: Some(DiffStat {
6707                        added: 1,
6708                        deleted: 1,
6709                    }),
6710                }),
6711                GitListEntry::Status(GitStatusEntry {
6712                    repo_path: repo_path("crates/util/util.rs"),
6713                    status: StatusCode::Modified.worktree(),
6714                    staging: StageStatus::Unstaged,
6715                    diff_stat: Some(DiffStat {
6716                        added: 1,
6717                        deleted: 1,
6718                    }),
6719                },),
6720            ],
6721        );
6722    }
6723
6724    #[gpui::test]
6725    async fn test_bulk_staging(cx: &mut TestAppContext) {
6726        use GitListEntry::*;
6727
6728        init_test(cx);
6729        let fs = FakeFs::new(cx.background_executor.clone());
6730        fs.insert_tree(
6731            "/root",
6732            json!({
6733                "project": {
6734                    ".git": {},
6735                    "src": {
6736                        "main.rs": "fn main() {}",
6737                        "lib.rs": "pub fn hello() {}",
6738                        "utils.rs": "pub fn util() {}"
6739                    },
6740                    "tests": {
6741                        "test.rs": "fn test() {}"
6742                    },
6743                    "new_file.txt": "new content",
6744                    "another_new.rs": "// new file",
6745                    "conflict.txt": "conflicted content"
6746                }
6747            }),
6748        )
6749        .await;
6750
6751        fs.set_status_for_repo(
6752            Path::new(path!("/root/project/.git")),
6753            &[
6754                ("src/main.rs", StatusCode::Modified.worktree()),
6755                ("src/lib.rs", StatusCode::Modified.worktree()),
6756                ("tests/test.rs", StatusCode::Modified.worktree()),
6757                ("new_file.txt", FileStatus::Untracked),
6758                ("another_new.rs", FileStatus::Untracked),
6759                ("src/utils.rs", FileStatus::Untracked),
6760                (
6761                    "conflict.txt",
6762                    UnmergedStatus {
6763                        first_head: UnmergedStatusCode::Updated,
6764                        second_head: UnmergedStatusCode::Updated,
6765                    }
6766                    .into(),
6767                ),
6768            ],
6769        );
6770
6771        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6772        let window_handle =
6773            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6774        let workspace = window_handle
6775            .read_with(cx, |mw, _| mw.workspace().clone())
6776            .unwrap();
6777        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6778
6779        cx.read(|cx| {
6780            project
6781                .read(cx)
6782                .worktrees(cx)
6783                .next()
6784                .unwrap()
6785                .read(cx)
6786                .as_local()
6787                .unwrap()
6788                .scan_complete()
6789        })
6790        .await;
6791
6792        cx.executor().run_until_parked();
6793
6794        let panel = workspace.update_in(cx, GitPanel::new);
6795
6796        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6797            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6798        });
6799        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6800        handle.await;
6801
6802        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6803        #[rustfmt::skip]
6804        pretty_assertions::assert_matches!(
6805            entries.as_slice(),
6806            &[
6807                Header(GitHeaderEntry { header: Section::Conflict }),
6808                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6809                Header(GitHeaderEntry { header: Section::Tracked }),
6810                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6811                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6812                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6813                Header(GitHeaderEntry { header: Section::New }),
6814                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6815                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6816                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6817            ],
6818        );
6819
6820        let second_status_entry = entries[3].clone();
6821        panel.update_in(cx, |panel, window, cx| {
6822            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6823        });
6824
6825        panel.update_in(cx, |panel, window, cx| {
6826            panel.selected_entry = Some(7);
6827            panel.stage_range(&git::StageRange, window, cx);
6828        });
6829
6830        cx.read(|cx| {
6831            project
6832                .read(cx)
6833                .worktrees(cx)
6834                .next()
6835                .unwrap()
6836                .read(cx)
6837                .as_local()
6838                .unwrap()
6839                .scan_complete()
6840        })
6841        .await;
6842
6843        cx.executor().run_until_parked();
6844
6845        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6846            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6847        });
6848        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6849        handle.await;
6850
6851        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6852        #[rustfmt::skip]
6853        pretty_assertions::assert_matches!(
6854            entries.as_slice(),
6855            &[
6856                Header(GitHeaderEntry { header: Section::Conflict }),
6857                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6858                Header(GitHeaderEntry { header: Section::Tracked }),
6859                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6860                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6861                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6862                Header(GitHeaderEntry { header: Section::New }),
6863                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6864                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6865                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6866            ],
6867        );
6868
6869        let third_status_entry = entries[4].clone();
6870        panel.update_in(cx, |panel, window, cx| {
6871            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6872        });
6873
6874        panel.update_in(cx, |panel, window, cx| {
6875            panel.selected_entry = Some(9);
6876            panel.stage_range(&git::StageRange, window, cx);
6877        });
6878
6879        cx.read(|cx| {
6880            project
6881                .read(cx)
6882                .worktrees(cx)
6883                .next()
6884                .unwrap()
6885                .read(cx)
6886                .as_local()
6887                .unwrap()
6888                .scan_complete()
6889        })
6890        .await;
6891
6892        cx.executor().run_until_parked();
6893
6894        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6895            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6896        });
6897        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6898        handle.await;
6899
6900        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6901        #[rustfmt::skip]
6902        pretty_assertions::assert_matches!(
6903            entries.as_slice(),
6904            &[
6905                Header(GitHeaderEntry { header: Section::Conflict }),
6906                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6907                Header(GitHeaderEntry { header: Section::Tracked }),
6908                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6909                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6910                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6911                Header(GitHeaderEntry { header: Section::New }),
6912                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6913                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6914                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6915            ],
6916        );
6917    }
6918
6919    #[gpui::test]
6920    async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6921        use GitListEntry::*;
6922
6923        init_test(cx);
6924        let fs = FakeFs::new(cx.background_executor.clone());
6925        fs.insert_tree(
6926            "/root",
6927            json!({
6928                "project": {
6929                    ".git": {},
6930                    "src": {
6931                        "main.rs": "fn main() {}",
6932                        "lib.rs": "pub fn hello() {}",
6933                        "utils.rs": "pub fn util() {}"
6934                    },
6935                    "tests": {
6936                        "test.rs": "fn test() {}"
6937                    },
6938                    "new_file.txt": "new content",
6939                    "another_new.rs": "// new file",
6940                    "conflict.txt": "conflicted content"
6941                }
6942            }),
6943        )
6944        .await;
6945
6946        fs.set_status_for_repo(
6947            Path::new(path!("/root/project/.git")),
6948            &[
6949                ("src/main.rs", StatusCode::Modified.worktree()),
6950                ("src/lib.rs", StatusCode::Modified.worktree()),
6951                ("tests/test.rs", StatusCode::Modified.worktree()),
6952                ("new_file.txt", FileStatus::Untracked),
6953                ("another_new.rs", FileStatus::Untracked),
6954                ("src/utils.rs", FileStatus::Untracked),
6955                (
6956                    "conflict.txt",
6957                    UnmergedStatus {
6958                        first_head: UnmergedStatusCode::Updated,
6959                        second_head: UnmergedStatusCode::Updated,
6960                    }
6961                    .into(),
6962                ),
6963            ],
6964        );
6965
6966        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6967        let window_handle =
6968            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6969        let workspace = window_handle
6970            .read_with(cx, |mw, _| mw.workspace().clone())
6971            .unwrap();
6972        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6973
6974        cx.read(|cx| {
6975            project
6976                .read(cx)
6977                .worktrees(cx)
6978                .next()
6979                .unwrap()
6980                .read(cx)
6981                .as_local()
6982                .unwrap()
6983                .scan_complete()
6984        })
6985        .await;
6986
6987        cx.executor().run_until_parked();
6988
6989        let panel = workspace.update_in(cx, GitPanel::new);
6990
6991        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6992            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6993        });
6994        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6995        handle.await;
6996
6997        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6998        #[rustfmt::skip]
6999        pretty_assertions::assert_matches!(
7000            entries.as_slice(),
7001            &[
7002                Header(GitHeaderEntry { header: Section::Conflict }),
7003                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7004                Header(GitHeaderEntry { header: Section::Tracked }),
7005                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7006                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7007                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7008                Header(GitHeaderEntry { header: Section::New }),
7009                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7010                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7011                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
7012            ],
7013        );
7014
7015        assert_entry_paths(
7016            &entries,
7017            &[
7018                None,
7019                Some("conflict.txt"),
7020                None,
7021                Some("src/lib.rs"),
7022                Some("src/main.rs"),
7023                Some("tests/test.rs"),
7024                None,
7025                Some("another_new.rs"),
7026                Some("new_file.txt"),
7027                Some("src/utils.rs"),
7028            ],
7029        );
7030
7031        let second_status_entry = entries[3].clone();
7032        panel.update_in(cx, |panel, window, cx| {
7033            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7034        });
7035
7036        cx.update(|_window, cx| {
7037            SettingsStore::update_global(cx, |store, cx| {
7038                store.update_user_settings(cx, |settings| {
7039                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7040                })
7041            });
7042        });
7043
7044        panel.update_in(cx, |panel, window, cx| {
7045            panel.selected_entry = Some(7);
7046            panel.stage_range(&git::StageRange, window, cx);
7047        });
7048
7049        cx.read(|cx| {
7050            project
7051                .read(cx)
7052                .worktrees(cx)
7053                .next()
7054                .unwrap()
7055                .read(cx)
7056                .as_local()
7057                .unwrap()
7058                .scan_complete()
7059        })
7060        .await;
7061
7062        cx.executor().run_until_parked();
7063
7064        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7065            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7066        });
7067        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7068        handle.await;
7069
7070        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7071        #[rustfmt::skip]
7072        pretty_assertions::assert_matches!(
7073            entries.as_slice(),
7074            &[
7075                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7076                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7077                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7078                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7079                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7080                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7081                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7082            ],
7083        );
7084
7085        assert_entry_paths(
7086            &entries,
7087            &[
7088                Some("another_new.rs"),
7089                Some("conflict.txt"),
7090                Some("new_file.txt"),
7091                Some("src/lib.rs"),
7092                Some("src/main.rs"),
7093                Some("src/utils.rs"),
7094                Some("tests/test.rs"),
7095            ],
7096        );
7097
7098        let third_status_entry = entries[4].clone();
7099        panel.update_in(cx, |panel, window, cx| {
7100            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
7101        });
7102
7103        panel.update_in(cx, |panel, window, cx| {
7104            panel.selected_entry = Some(9);
7105            panel.stage_range(&git::StageRange, window, cx);
7106        });
7107
7108        cx.read(|cx| {
7109            project
7110                .read(cx)
7111                .worktrees(cx)
7112                .next()
7113                .unwrap()
7114                .read(cx)
7115                .as_local()
7116                .unwrap()
7117                .scan_complete()
7118        })
7119        .await;
7120
7121        cx.executor().run_until_parked();
7122
7123        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7124            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7125        });
7126        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7127        handle.await;
7128
7129        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7130        #[rustfmt::skip]
7131        pretty_assertions::assert_matches!(
7132            entries.as_slice(),
7133            &[
7134                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7135                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7136                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7137                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7138                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7139                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7140                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7141            ],
7142        );
7143
7144        assert_entry_paths(
7145            &entries,
7146            &[
7147                Some("another_new.rs"),
7148                Some("conflict.txt"),
7149                Some("new_file.txt"),
7150                Some("src/lib.rs"),
7151                Some("src/main.rs"),
7152                Some("src/utils.rs"),
7153                Some("tests/test.rs"),
7154            ],
7155        );
7156    }
7157
7158    #[gpui::test]
7159    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
7160        init_test(cx);
7161        let fs = FakeFs::new(cx.background_executor.clone());
7162        fs.insert_tree(
7163            "/root",
7164            json!({
7165                "project": {
7166                    ".git": {},
7167                    "src": {
7168                        "main.rs": "fn main() {}"
7169                    }
7170                }
7171            }),
7172        )
7173        .await;
7174
7175        fs.set_status_for_repo(
7176            Path::new(path!("/root/project/.git")),
7177            &[("src/main.rs", StatusCode::Modified.worktree())],
7178        );
7179
7180        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7181        let window_handle =
7182            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7183        let workspace = window_handle
7184            .read_with(cx, |mw, _| mw.workspace().clone())
7185            .unwrap();
7186        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7187
7188        let panel = workspace.update_in(cx, GitPanel::new);
7189
7190        // Test: User has commit message, enables amend (saves message), then disables (restores message)
7191        panel.update(cx, |panel, cx| {
7192            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7193                let start = buffer.anchor_before(0);
7194                let end = buffer.anchor_after(buffer.len());
7195                buffer.edit([(start..end, "Initial commit message")], None, cx);
7196            });
7197
7198            panel.set_amend_pending(true, cx);
7199            assert!(panel.original_commit_message.is_some());
7200
7201            panel.set_amend_pending(false, cx);
7202            let current_message = panel.commit_message_buffer(cx).read(cx).text();
7203            assert_eq!(current_message, "Initial commit message");
7204            assert!(panel.original_commit_message.is_none());
7205        });
7206
7207        // Test: User has empty commit message, enables amend, then disables (clears message)
7208        panel.update(cx, |panel, cx| {
7209            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7210                let start = buffer.anchor_before(0);
7211                let end = buffer.anchor_after(buffer.len());
7212                buffer.edit([(start..end, "")], None, cx);
7213            });
7214
7215            panel.set_amend_pending(true, cx);
7216            assert!(panel.original_commit_message.is_none());
7217
7218            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7219                let start = buffer.anchor_before(0);
7220                let end = buffer.anchor_after(buffer.len());
7221                buffer.edit([(start..end, "Previous commit message")], None, cx);
7222            });
7223
7224            panel.set_amend_pending(false, cx);
7225            let current_message = panel.commit_message_buffer(cx).read(cx).text();
7226            assert_eq!(current_message, "");
7227        });
7228    }
7229
7230    #[gpui::test]
7231    async fn test_amend(cx: &mut TestAppContext) {
7232        init_test(cx);
7233        let fs = FakeFs::new(cx.background_executor.clone());
7234        fs.insert_tree(
7235            "/root",
7236            json!({
7237                "project": {
7238                    ".git": {},
7239                    "src": {
7240                        "main.rs": "fn main() {}"
7241                    }
7242                }
7243            }),
7244        )
7245        .await;
7246
7247        fs.set_status_for_repo(
7248            Path::new(path!("/root/project/.git")),
7249            &[("src/main.rs", StatusCode::Modified.worktree())],
7250        );
7251
7252        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7253        let window_handle =
7254            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7255        let workspace = window_handle
7256            .read_with(cx, |mw, _| mw.workspace().clone())
7257            .unwrap();
7258        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7259
7260        // Wait for the project scanning to finish so that `head_commit(cx)` is
7261        // actually set, otherwise no head commit would be available from which
7262        // to fetch the latest commit message from.
7263        cx.executor().run_until_parked();
7264
7265        let panel = workspace.update_in(cx, GitPanel::new);
7266        panel.read_with(cx, |panel, cx| {
7267            assert!(panel.active_repository.is_some());
7268            assert!(panel.head_commit(cx).is_some());
7269        });
7270
7271        panel.update_in(cx, |panel, window, cx| {
7272            // Update the commit editor's message to ensure that its contents
7273            // are later restored, after amending is finished.
7274            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7275                buffer.set_text("refactor: update main.rs", cx);
7276            });
7277
7278            // Start amending the previous commit.
7279            panel.focus_editor(&Default::default(), window, cx);
7280            panel.on_amend(&Amend, window, cx);
7281        });
7282
7283        // Since `GitPanel.amend` attempts to fetch the latest commit message in
7284        // a background task, we need to wait for it to complete before being
7285        // able to assert that the commit message editor's state has been
7286        // updated.
7287        cx.run_until_parked();
7288
7289        panel.update_in(cx, |panel, window, cx| {
7290            assert_eq!(
7291                panel.commit_message_buffer(cx).read(cx).text(),
7292                "initial commit"
7293            );
7294            assert_eq!(
7295                panel.original_commit_message,
7296                Some("refactor: update main.rs".to_string())
7297            );
7298
7299            // Finish amending the previous commit.
7300            panel.focus_editor(&Default::default(), window, cx);
7301            panel.on_amend(&Amend, window, cx);
7302        });
7303
7304        // Since the actual commit logic is run in a background task, we need to
7305        // await its completion to actually ensure that the commit message
7306        // editor's contents are set to the original message and haven't been
7307        // cleared.
7308        cx.run_until_parked();
7309
7310        panel.update_in(cx, |panel, _window, cx| {
7311            // After amending, the commit editor's message should be restored to
7312            // the original message.
7313            assert_eq!(
7314                panel.commit_message_buffer(cx).read(cx).text(),
7315                "refactor: update main.rs"
7316            );
7317            assert!(panel.original_commit_message.is_none());
7318        });
7319    }
7320
7321    #[gpui::test]
7322    async fn test_open_diff(cx: &mut TestAppContext) {
7323        init_test(cx);
7324
7325        let fs = FakeFs::new(cx.background_executor.clone());
7326        fs.insert_tree(
7327            path!("/project"),
7328            json!({
7329                ".git": {},
7330                "tracked": "tracked\n",
7331                "untracked": "\n",
7332            }),
7333        )
7334        .await;
7335
7336        fs.set_head_and_index_for_repo(
7337            path!("/project/.git").as_ref(),
7338            &[("tracked", "old tracked\n".into())],
7339        );
7340
7341        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7342        let window_handle =
7343            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7344        let workspace = window_handle
7345            .read_with(cx, |mw, _| mw.workspace().clone())
7346            .unwrap();
7347        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7348        let panel = workspace.update_in(cx, GitPanel::new);
7349
7350        // Enable the `sort_by_path` setting and wait for entries to be updated,
7351        // as there should no longer be separators between Tracked and Untracked
7352        // files.
7353        cx.update(|_window, cx| {
7354            SettingsStore::update_global(cx, |store, cx| {
7355                store.update_user_settings(cx, |settings| {
7356                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7357                })
7358            });
7359        });
7360
7361        cx.update_window_entity(&panel, |panel, _, _| {
7362            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7363        })
7364        .await;
7365
7366        // Confirm that `Open Diff` still works for the untracked file, updating
7367        // the Project Diff's active path.
7368        panel.update_in(cx, |panel, window, cx| {
7369            panel.selected_entry = Some(1);
7370            panel.open_diff(&menu::Confirm, window, cx);
7371        });
7372        cx.run_until_parked();
7373
7374        workspace.update_in(cx, |workspace, _window, cx| {
7375            let active_path = workspace
7376                .item_of_type::<ProjectDiff>(cx)
7377                .expect("ProjectDiff should exist")
7378                .read(cx)
7379                .active_path(cx)
7380                .expect("active_path should exist");
7381
7382            assert_eq!(active_path.path, rel_path("untracked").into_arc());
7383        });
7384    }
7385
7386    #[gpui::test]
7387    async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
7388        cx: &mut TestAppContext,
7389    ) {
7390        init_test(cx);
7391
7392        let fs = FakeFs::new(cx.background_executor.clone());
7393        fs.insert_tree(
7394            path!("/project"),
7395            json!({
7396                ".git": {},
7397                "src": {
7398                    "a": {
7399                        "foo.rs": "fn foo() {}",
7400                    },
7401                    "b": {
7402                        "bar.rs": "fn bar() {}",
7403                    },
7404                },
7405            }),
7406        )
7407        .await;
7408
7409        fs.set_status_for_repo(
7410            path!("/project/.git").as_ref(),
7411            &[
7412                ("src/a/foo.rs", StatusCode::Modified.worktree()),
7413                ("src/b/bar.rs", StatusCode::Modified.worktree()),
7414            ],
7415        );
7416
7417        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7418        let window_handle =
7419            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7420        let workspace = window_handle
7421            .read_with(cx, |mw, _| mw.workspace().clone())
7422            .unwrap();
7423        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7424
7425        cx.read(|cx| {
7426            project
7427                .read(cx)
7428                .worktrees(cx)
7429                .next()
7430                .unwrap()
7431                .read(cx)
7432                .as_local()
7433                .unwrap()
7434                .scan_complete()
7435        })
7436        .await;
7437
7438        cx.executor().run_until_parked();
7439
7440        cx.update(|_window, cx| {
7441            SettingsStore::update_global(cx, |store, cx| {
7442                store.update_user_settings(cx, |settings| {
7443                    settings.git_panel.get_or_insert_default().tree_view = Some(true);
7444                })
7445            });
7446        });
7447
7448        let panel = workspace.update_in(cx, GitPanel::new);
7449
7450        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7451            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7452        });
7453        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7454        handle.await;
7455
7456        let src_key = panel.read_with(cx, |panel, _| {
7457            panel
7458                .entries
7459                .iter()
7460                .find_map(|entry| match entry {
7461                    GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7462                        Some(dir.key.clone())
7463                    }
7464                    _ => None,
7465                })
7466                .expect("src directory should exist in tree view")
7467        });
7468
7469        panel.update_in(cx, |panel, window, cx| {
7470            panel.toggle_directory(&src_key, window, cx);
7471        });
7472
7473        panel.read_with(cx, |panel, _| {
7474            let state = panel
7475                .view_mode
7476                .tree_state()
7477                .expect("tree view state should exist");
7478            assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7479        });
7480
7481        let worktree_id =
7482            cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7483        let project_path = ProjectPath {
7484            worktree_id,
7485            path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7486        };
7487
7488        panel.update_in(cx, |panel, window, cx| {
7489            panel.select_entry_by_path(project_path, window, cx);
7490        });
7491
7492        panel.read_with(cx, |panel, _| {
7493            let state = panel
7494                .view_mode
7495                .tree_state()
7496                .expect("tree view state should exist");
7497            assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7498
7499            let selected_ix = panel.selected_entry.expect("selection should be set");
7500            assert!(state.logical_indices.contains(&selected_ix));
7501
7502            let selected_entry = panel
7503                .entries
7504                .get(selected_ix)
7505                .and_then(|entry| entry.status_entry())
7506                .expect("selected entry should be a status entry");
7507            assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7508        });
7509    }
7510
7511    #[gpui::test]
7512    async fn test_tree_view_select_next_at_last_visible_collapsed_directory(
7513        cx: &mut TestAppContext,
7514    ) {
7515        init_test(cx);
7516
7517        let fs = FakeFs::new(cx.background_executor.clone());
7518        fs.insert_tree(
7519            path!("/project"),
7520            json!({
7521                ".git": {},
7522                "bar": {
7523                    "bar1.py": "print('bar1')",
7524                    "bar2.py": "print('bar2')",
7525                },
7526                "foo": {
7527                    "foo1.py": "print('foo1')",
7528                    "foo2.py": "print('foo2')",
7529                },
7530                "foobar.py": "print('foobar')",
7531            }),
7532        )
7533        .await;
7534
7535        fs.set_status_for_repo(
7536            path!("/project/.git").as_ref(),
7537            &[
7538                ("bar/bar1.py", StatusCode::Modified.worktree()),
7539                ("bar/bar2.py", StatusCode::Modified.worktree()),
7540                ("foo/foo1.py", StatusCode::Modified.worktree()),
7541                ("foo/foo2.py", StatusCode::Modified.worktree()),
7542                ("foobar.py", FileStatus::Untracked),
7543            ],
7544        );
7545
7546        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7547        let window_handle =
7548            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7549        let workspace = window_handle
7550            .read_with(cx, |mw, _| mw.workspace().clone())
7551            .unwrap();
7552        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7553
7554        cx.read(|cx| {
7555            project
7556                .read(cx)
7557                .worktrees(cx)
7558                .next()
7559                .unwrap()
7560                .read(cx)
7561                .as_local()
7562                .unwrap()
7563                .scan_complete()
7564        })
7565        .await;
7566
7567        cx.executor().run_until_parked();
7568        cx.update(|_window, cx| {
7569            SettingsStore::update_global(cx, |store, cx| {
7570                store.update_user_settings(cx, |settings| {
7571                    settings.git_panel.get_or_insert_default().tree_view = Some(true);
7572                })
7573            });
7574        });
7575
7576        let panel = workspace.update_in(cx, GitPanel::new);
7577        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7578            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7579        });
7580
7581        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7582        handle.await;
7583
7584        let foo_key = panel.read_with(cx, |panel, _| {
7585            panel
7586                .entries
7587                .iter()
7588                .find_map(|entry| match entry {
7589                    GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => {
7590                        Some(dir.key.clone())
7591                    }
7592                    _ => None,
7593                })
7594                .expect("foo directory should exist in tree view")
7595        });
7596
7597        panel.update_in(cx, |panel, window, cx| {
7598            panel.toggle_directory(&foo_key, window, cx);
7599        });
7600
7601        let foo_idx = panel.read_with(cx, |panel, _| {
7602            let state = panel
7603                .view_mode
7604                .tree_state()
7605                .expect("tree view state should exist");
7606            assert_eq!(state.expanded_dirs.get(&foo_key).copied(), Some(false));
7607
7608            let foo_idx = panel
7609                .entries
7610                .iter()
7611                .enumerate()
7612                .find_map(|(index, entry)| match entry {
7613                    GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => Some(index),
7614                    _ => None,
7615                })
7616                .expect("foo directory should exist in tree view");
7617
7618            let foo_logical_idx = state
7619                .logical_indices
7620                .iter()
7621                .position(|&index| index == foo_idx)
7622                .expect("foo directory should be visible");
7623            let next_logical_idx = state.logical_indices[foo_logical_idx + 1];
7624            assert!(matches!(
7625                panel.entries.get(next_logical_idx),
7626                Some(GitListEntry::Header(GitHeaderEntry {
7627                    header: Section::New
7628                }))
7629            ));
7630
7631            foo_idx
7632        });
7633
7634        panel.update_in(cx, |panel, window, cx| {
7635            panel.selected_entry = Some(foo_idx);
7636            panel.select_next(&menu::SelectNext, window, cx);
7637        });
7638
7639        panel.read_with(cx, |panel, _| {
7640            let selected_idx = panel.selected_entry.expect("selection should be set");
7641            let selected_entry = panel
7642                .entries
7643                .get(selected_idx)
7644                .and_then(|entry| entry.status_entry())
7645                .expect("selected entry should be a status entry");
7646            assert_eq!(selected_entry.repo_path, repo_path("foobar.py"));
7647        });
7648    }
7649
7650    fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7651        assert_eq!(entries.len(), expected_paths.len());
7652        for (entry, expected_path) in entries.iter().zip(expected_paths) {
7653            assert_eq!(
7654                entry.status_entry().map(|status| status
7655                    .repo_path
7656                    .as_ref()
7657                    .as_std_path()
7658                    .to_string_lossy()
7659                    .to_string()),
7660                expected_path.map(|s| s.to_string())
7661            );
7662        }
7663    }
7664
7665    #[test]
7666    fn test_compress_diff_no_truncation() {
7667        let diff = indoc! {"
7668            --- a/file.txt
7669            +++ b/file.txt
7670            @@ -1,2 +1,2 @@
7671            -old
7672            +new
7673        "};
7674        let result = GitPanel::compress_commit_diff(diff, 1000);
7675        assert_eq!(result, diff);
7676    }
7677
7678    #[test]
7679    fn test_compress_diff_truncate_long_lines() {
7680        let long_line = "🦀".repeat(300);
7681        let diff = indoc::formatdoc! {"
7682            --- a/file.txt
7683            +++ b/file.txt
7684            @@ -1,2 +1,3 @@
7685             context
7686            +{}
7687             more context
7688        ", long_line};
7689        let result = GitPanel::compress_commit_diff(&diff, 100);
7690        assert!(result.contains("...[truncated]"));
7691        assert!(result.len() < diff.len());
7692    }
7693
7694    #[test]
7695    fn test_compress_diff_truncate_hunks() {
7696        let diff = indoc! {"
7697            --- a/file.txt
7698            +++ b/file.txt
7699            @@ -1,2 +1,2 @@
7700             context
7701            -old1
7702            +new1
7703            @@ -5,2 +5,2 @@
7704             context 2
7705            -old2
7706            +new2
7707            @@ -10,2 +10,2 @@
7708             context 3
7709            -old3
7710            +new3
7711        "};
7712        let result = GitPanel::compress_commit_diff(diff, 100);
7713        let expected = indoc! {"
7714            --- a/file.txt
7715            +++ b/file.txt
7716            @@ -1,2 +1,2 @@
7717             context
7718            -old1
7719            +new1
7720            [...skipped 2 hunks...]
7721        "};
7722        assert_eq!(result, expected);
7723    }
7724
7725    #[gpui::test]
7726    async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7727        init_test(cx);
7728
7729        let fs = FakeFs::new(cx.background_executor.clone());
7730        fs.insert_tree(
7731            path!("/project"),
7732            json!({
7733                ".git": {},
7734                "tracked": "tracked\n",
7735                "untracked": "\n",
7736            }),
7737        )
7738        .await;
7739
7740        fs.set_head_and_index_for_repo(
7741            path!("/project/.git").as_ref(),
7742            &[("tracked", "old tracked\n".into())],
7743        );
7744
7745        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7746        let window_handle =
7747            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7748        let workspace = window_handle
7749            .read_with(cx, |mw, _| mw.workspace().clone())
7750            .unwrap();
7751        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7752        let panel = workspace.update_in(cx, GitPanel::new);
7753
7754        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7755            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7756        });
7757        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7758        handle.await;
7759
7760        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7761
7762        // GitPanel
7763        // - Tracked:
7764        // - [] tracked
7765        // - Untracked
7766        // - [] untracked
7767        //
7768        // The commit message should now read:
7769        // "Update tracked"
7770        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7771        assert_eq!(message, Some("Update tracked".to_string()));
7772
7773        let first_status_entry = entries[1].clone();
7774        panel.update_in(cx, |panel, window, cx| {
7775            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7776        });
7777
7778        cx.read(|cx| {
7779            project
7780                .read(cx)
7781                .worktrees(cx)
7782                .next()
7783                .unwrap()
7784                .read(cx)
7785                .as_local()
7786                .unwrap()
7787                .scan_complete()
7788        })
7789        .await;
7790
7791        cx.executor().run_until_parked();
7792
7793        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7794            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7795        });
7796        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7797        handle.await;
7798
7799        // GitPanel
7800        // - Tracked:
7801        // - [x] tracked
7802        // - Untracked
7803        // - [] untracked
7804        //
7805        // The commit message should still read:
7806        // "Update tracked"
7807        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7808        assert_eq!(message, Some("Update tracked".to_string()));
7809
7810        let second_status_entry = entries[3].clone();
7811        panel.update_in(cx, |panel, window, cx| {
7812            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7813        });
7814
7815        cx.read(|cx| {
7816            project
7817                .read(cx)
7818                .worktrees(cx)
7819                .next()
7820                .unwrap()
7821                .read(cx)
7822                .as_local()
7823                .unwrap()
7824                .scan_complete()
7825        })
7826        .await;
7827
7828        cx.executor().run_until_parked();
7829
7830        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7831            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7832        });
7833        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7834        handle.await;
7835
7836        // GitPanel
7837        // - Tracked:
7838        // - [x] tracked
7839        // - Untracked
7840        // - [x] untracked
7841        //
7842        // The commit message should now read:
7843        // "Enter commit message"
7844        // (which means we should see None returned).
7845        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7846        assert!(message.is_none());
7847
7848        panel.update_in(cx, |panel, window, cx| {
7849            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7850        });
7851
7852        cx.read(|cx| {
7853            project
7854                .read(cx)
7855                .worktrees(cx)
7856                .next()
7857                .unwrap()
7858                .read(cx)
7859                .as_local()
7860                .unwrap()
7861                .scan_complete()
7862        })
7863        .await;
7864
7865        cx.executor().run_until_parked();
7866
7867        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7868            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7869        });
7870        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7871        handle.await;
7872
7873        // GitPanel
7874        // - Tracked:
7875        // - [] tracked
7876        // - Untracked
7877        // - [x] untracked
7878        //
7879        // The commit message should now read:
7880        // "Update untracked"
7881        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7882        assert_eq!(message, Some("Create untracked".to_string()));
7883
7884        panel.update_in(cx, |panel, window, cx| {
7885            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7886        });
7887
7888        cx.read(|cx| {
7889            project
7890                .read(cx)
7891                .worktrees(cx)
7892                .next()
7893                .unwrap()
7894                .read(cx)
7895                .as_local()
7896                .unwrap()
7897                .scan_complete()
7898        })
7899        .await;
7900
7901        cx.executor().run_until_parked();
7902
7903        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7904            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7905        });
7906        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7907        handle.await;
7908
7909        // GitPanel
7910        // - Tracked:
7911        // - [] tracked
7912        // - Untracked
7913        // - [] untracked
7914        //
7915        // The commit message should now read:
7916        // "Update tracked"
7917        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7918        assert_eq!(message, Some("Update tracked".to_string()));
7919    }
7920
7921    #[test]
7922    fn test_git_output_handler_strips_ansi_codes() {
7923        use alacritty_terminal::vte::ansi;
7924
7925        let cases = [
7926            ("no escape codes here\n", "no escape codes here\n"),
7927            ("\x1b[31mhello\x1b[0m", "hello"),
7928            ("\x1b[1;32mfoo\x1b[0m bar", "foo bar"),
7929            ("progress 10%\rprogress 100%\n", "progress 100%\n"),
7930        ];
7931
7932        for (input, expected) in cases {
7933            let mut handler = GitOutputHandler::default();
7934            let mut processor = ansi::Processor::<ansi::StdSyncHandler>::default();
7935            processor.advance(&mut handler, input.as_bytes());
7936            assert_eq!(handler.output, expected);
7937        }
7938    }
7939
7940    #[gpui::test]
7941    async fn test_dispatch_context_with_focus_states(cx: &mut TestAppContext) {
7942        init_test(cx);
7943
7944        let fs = FakeFs::new(cx.background_executor.clone());
7945        fs.insert_tree(
7946            path!("/project"),
7947            json!({
7948                ".git": {},
7949                "tracked": "tracked\n",
7950            }),
7951        )
7952        .await;
7953
7954        fs.set_head_and_index_for_repo(
7955            path!("/project/.git").as_ref(),
7956            &[("tracked", "old tracked\n".into())],
7957        );
7958
7959        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7960        let window_handle =
7961            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7962        let workspace = window_handle
7963            .read_with(cx, |mw, _| mw.workspace().clone())
7964            .unwrap();
7965        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7966        let panel = workspace.update_in(cx, GitPanel::new);
7967
7968        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7969            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7970        });
7971        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7972        handle.await;
7973
7974        // Case 1: Focus the commit editor — should have "CommitEditor" but NOT "menu"/"ChangesList"
7975        panel.update_in(cx, |panel, window, cx| {
7976            panel.focus_editor(&FocusEditor, window, cx);
7977            let editor_is_focused = panel.commit_editor.read(cx).is_focused(window);
7978            assert!(
7979                editor_is_focused,
7980                "commit editor should be focused after focus_editor action"
7981            );
7982            let context = panel.dispatch_context(window, cx);
7983            assert!(
7984                context.contains("GitPanel"),
7985                "should always have GitPanel context"
7986            );
7987            assert!(
7988                context.contains("CommitEditor"),
7989                "should have CommitEditor context when commit editor is focused"
7990            );
7991            assert!(
7992                !context.contains("menu"),
7993                "should not have menu context when commit editor is focused"
7994            );
7995            assert!(
7996                !context.contains("ChangesList"),
7997                "should not have ChangesList context when commit editor is focused"
7998            );
7999        });
8000
8001        // Case 2: Focus the panel's focus handle directly — should have "menu" and "ChangesList".
8002        // We force a draw via simulate_resize to ensure the dispatch tree is populated,
8003        // since contains_focused() depends on the rendered dispatch tree.
8004        panel.update_in(cx, |panel, window, cx| {
8005            panel.focus_handle.focus(window, cx);
8006        });
8007        cx.simulate_resize(gpui::size(px(800.), px(600.)));
8008
8009        panel.update_in(cx, |panel, window, cx| {
8010            let context = panel.dispatch_context(window, cx);
8011            assert!(
8012                context.contains("GitPanel"),
8013                "should always have GitPanel context"
8014            );
8015            assert!(
8016                context.contains("menu"),
8017                "should have menu context when changes list is focused"
8018            );
8019            assert!(
8020                context.contains("ChangesList"),
8021                "should have ChangesList context when changes list is focused"
8022            );
8023            assert!(
8024                !context.contains("CommitEditor"),
8025                "should not have CommitEditor context when changes list is focused"
8026            );
8027        });
8028
8029        // Case 3: Switch back to commit editor and verify context switches correctly
8030        panel.update_in(cx, |panel, window, cx| {
8031            panel.focus_editor(&FocusEditor, window, cx);
8032        });
8033
8034        panel.update_in(cx, |panel, window, cx| {
8035            let context = panel.dispatch_context(window, cx);
8036            assert!(
8037                context.contains("CommitEditor"),
8038                "should have CommitEditor after switching focus back to editor"
8039            );
8040            assert!(
8041                !context.contains("menu"),
8042                "should not have menu after switching focus back to editor"
8043            );
8044        });
8045
8046        // Case 4: Re-focus changes list and verify it transitions back correctly
8047        panel.update_in(cx, |panel, window, cx| {
8048            panel.focus_handle.focus(window, cx);
8049        });
8050        cx.simulate_resize(gpui::size(px(800.), px(600.)));
8051
8052        panel.update_in(cx, |panel, window, cx| {
8053            assert!(
8054                panel.focus_handle.contains_focused(window, cx),
8055                "panel focus handle should report contains_focused when directly focused"
8056            );
8057            let context = panel.dispatch_context(window, cx);
8058            assert!(
8059                context.contains("menu"),
8060                "should have menu context after re-focusing changes list"
8061            );
8062            assert!(
8063                context.contains("ChangesList"),
8064                "should have ChangesList context after re-focusing changes list"
8065            );
8066        });
8067    }
8068}