git_panel.rs

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