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