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 this = cx.weak_entity();
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                    this.update(cx, |this, cx| {
3181                        this.workspace.update(cx, |workspace, cx| {
3182                            workspace.toggle_modal(window, cx, |window, cx| {
3183                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
3184                            });
3185                        })
3186                    })
3187                })
3188                .ok();
3189        })
3190    }
3191
3192    fn can_push_and_pull(&self, cx: &App) -> bool {
3193        !self.project.read(cx).is_via_collab()
3194    }
3195
3196    fn get_remote(
3197        &mut self,
3198        always_select: bool,
3199        is_push: bool,
3200        window: &mut Window,
3201        cx: &mut Context<Self>,
3202    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
3203        let repo = self.active_repository.clone();
3204        let workspace = self.workspace.clone();
3205        let mut cx = window.to_async(cx);
3206
3207        async move {
3208            let repo = repo.context("No active repository")?;
3209            let current_remotes: Vec<Remote> = repo
3210                .update(&mut cx, |repo, _| {
3211                    let current_branch = if always_select {
3212                        None
3213                    } else {
3214                        let current_branch = repo.branch.as_ref().context("No active branch")?;
3215                        Some(current_branch.name().to_string())
3216                    };
3217                    anyhow::Ok(repo.get_remotes(current_branch, is_push))
3218                })?
3219                .await??;
3220
3221            let current_remotes: Vec<_> = current_remotes
3222                .into_iter()
3223                .map(|remotes| remotes.name)
3224                .collect();
3225            let selection = cx
3226                .update(|window, cx| {
3227                    picker_prompt::prompt(
3228                        "Pick which remote to push to",
3229                        current_remotes.clone(),
3230                        workspace,
3231                        window,
3232                        cx,
3233                    )
3234                })?
3235                .await;
3236
3237            Ok(selection.map(|selection| Remote {
3238                name: current_remotes[selection].clone(),
3239            }))
3240        }
3241    }
3242
3243    pub fn load_local_committer(&mut self, cx: &Context<Self>) {
3244        if self.local_committer_task.is_none() {
3245            self.local_committer_task = Some(cx.spawn(async move |this, cx| {
3246                let committer = get_git_committer(cx).await;
3247                this.update(cx, |this, cx| {
3248                    this.local_committer = Some(committer);
3249                    cx.notify()
3250                })
3251                .ok();
3252            }));
3253        }
3254    }
3255
3256    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
3257        let mut new_co_authors = Vec::new();
3258        let project = self.project.read(cx);
3259
3260        let Some(room) = self
3261            .workspace
3262            .upgrade()
3263            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
3264        else {
3265            return Vec::default();
3266        };
3267
3268        let room = room.read(cx);
3269
3270        for (peer_id, collaborator) in project.collaborators() {
3271            if collaborator.is_host {
3272                continue;
3273            }
3274
3275            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
3276                continue;
3277            };
3278            if !participant.can_write() {
3279                continue;
3280            }
3281            if let Some(email) = &collaborator.committer_email {
3282                let name = collaborator
3283                    .committer_name
3284                    .clone()
3285                    .or_else(|| participant.user.name.clone())
3286                    .unwrap_or_else(|| participant.user.github_login.clone().to_string());
3287                new_co_authors.push((name.clone(), email.clone()))
3288            }
3289        }
3290        if !project.is_local()
3291            && !project.is_read_only(cx)
3292            && let Some(local_committer) = self.local_committer(room, cx)
3293        {
3294            new_co_authors.push(local_committer);
3295        }
3296        new_co_authors
3297    }
3298
3299    fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
3300        let user = room.local_participant_user(cx)?;
3301        let committer = self.local_committer.as_ref()?;
3302        let email = committer.email.clone()?;
3303        let name = committer
3304            .name
3305            .clone()
3306            .or_else(|| user.name.clone())
3307            .unwrap_or_else(|| user.github_login.clone().to_string());
3308        Some((name, email))
3309    }
3310
3311    fn toggle_fill_co_authors(
3312        &mut self,
3313        _: &ToggleFillCoAuthors,
3314        _: &mut Window,
3315        cx: &mut Context<Self>,
3316    ) {
3317        self.add_coauthors = !self.add_coauthors;
3318        cx.notify();
3319    }
3320
3321    fn toggle_sort_by_path(
3322        &mut self,
3323        _: &ToggleSortByPath,
3324        _: &mut Window,
3325        cx: &mut Context<Self>,
3326    ) {
3327        let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
3328        if let Some(workspace) = self.workspace.upgrade() {
3329            let workspace = workspace.read(cx);
3330            let fs = workspace.app_state().fs.clone();
3331            cx.update_global::<SettingsStore, _>(|store, _cx| {
3332                store.update_settings_file(fs, move |settings, _cx| {
3333                    settings.git_panel.get_or_insert_default().sort_by_path =
3334                        Some(!current_setting);
3335                });
3336            });
3337        }
3338    }
3339
3340    fn toggle_tree_view(&mut self, _: &ToggleTreeView, _: &mut Window, cx: &mut Context<Self>) {
3341        let current_setting = GitPanelSettings::get_global(cx).tree_view;
3342        if let Some(workspace) = self.workspace.upgrade() {
3343            let workspace = workspace.read(cx);
3344            let fs = workspace.app_state().fs.clone();
3345            cx.update_global::<SettingsStore, _>(|store, _cx| {
3346                store.update_settings_file(fs, move |settings, _cx| {
3347                    settings.git_panel.get_or_insert_default().tree_view = Some(!current_setting);
3348                });
3349            })
3350        }
3351    }
3352
3353    fn toggle_directory(&mut self, key: &TreeKey, window: &mut Window, cx: &mut Context<Self>) {
3354        if let Some(state) = self.view_mode.tree_state_mut() {
3355            let expanded = state.expanded_dirs.entry(key.clone()).or_insert(true);
3356            *expanded = !*expanded;
3357            self.update_visible_entries(window, cx);
3358        } else {
3359            util::debug_panic!("Attempted to toggle directory in flat Git Panel state");
3360        }
3361    }
3362
3363    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
3364        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
3365
3366        let existing_text = message.to_ascii_lowercase();
3367        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
3368        let mut ends_with_co_authors = false;
3369        let existing_co_authors = existing_text
3370            .lines()
3371            .filter_map(|line| {
3372                let line = line.trim();
3373                if line.starts_with(&lowercase_co_author_prefix) {
3374                    ends_with_co_authors = true;
3375                    Some(line)
3376                } else {
3377                    ends_with_co_authors = false;
3378                    None
3379                }
3380            })
3381            .collect::<HashSet<_>>();
3382
3383        let new_co_authors = self
3384            .potential_co_authors(cx)
3385            .into_iter()
3386            .filter(|(_, email)| {
3387                !existing_co_authors
3388                    .iter()
3389                    .any(|existing| existing.contains(email.as_str()))
3390            })
3391            .collect::<Vec<_>>();
3392
3393        if new_co_authors.is_empty() {
3394            return;
3395        }
3396
3397        if !ends_with_co_authors {
3398            message.push('\n');
3399        }
3400        for (name, email) in new_co_authors {
3401            message.push('\n');
3402            message.push_str(CO_AUTHOR_PREFIX);
3403            message.push_str(&name);
3404            message.push_str(" <");
3405            message.push_str(&email);
3406            message.push('>');
3407        }
3408        message.push('\n');
3409    }
3410
3411    fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3412        let handle = cx.entity().downgrade();
3413        self.reopen_commit_buffer(window, cx);
3414        self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
3415            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
3416            if let Some(git_panel) = handle.upgrade() {
3417                git_panel
3418                    .update_in(cx, |git_panel, window, cx| {
3419                        git_panel.update_visible_entries(window, cx);
3420                    })
3421                    .ok();
3422            }
3423        });
3424    }
3425
3426    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3427        let Some(active_repo) = self.active_repository.as_ref() else {
3428            return;
3429        };
3430        let load_buffer = active_repo.update(cx, |active_repo, cx| {
3431            let project = self.project.read(cx);
3432            active_repo.open_commit_buffer(
3433                Some(project.languages().clone()),
3434                project.buffer_store().clone(),
3435                cx,
3436            )
3437        });
3438
3439        cx.spawn_in(window, async move |git_panel, cx| {
3440            let buffer = load_buffer.await?;
3441            git_panel.update_in(cx, |git_panel, window, cx| {
3442                if git_panel
3443                    .commit_editor
3444                    .read(cx)
3445                    .buffer()
3446                    .read(cx)
3447                    .as_singleton()
3448                    .as_ref()
3449                    != Some(&buffer)
3450                {
3451                    git_panel.commit_editor = cx.new(|cx| {
3452                        commit_message_editor(
3453                            buffer,
3454                            git_panel.suggest_commit_message(cx).map(SharedString::from),
3455                            git_panel.project.clone(),
3456                            true,
3457                            window,
3458                            cx,
3459                        )
3460                    });
3461                }
3462            })
3463        })
3464        .detach_and_log_err(cx);
3465    }
3466
3467    fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3468        let path_style = self.project.read(cx).path_style(cx);
3469        let bulk_staging = self.bulk_staging.take();
3470        let last_staged_path_prev_index = bulk_staging
3471            .as_ref()
3472            .and_then(|op| self.entry_by_path(&op.anchor));
3473
3474        self.active_repository = self.project.read(cx).active_repository(cx);
3475        self.entries.clear();
3476        self.entries_indices.clear();
3477        self.single_staged_entry.take();
3478        self.single_tracked_entry.take();
3479        self.conflicted_count = 0;
3480        self.conflicted_staged_count = 0;
3481        self.changes_count = 0;
3482        self.new_count = 0;
3483        self.tracked_count = 0;
3484        self.new_staged_count = 0;
3485        self.tracked_staged_count = 0;
3486        self.entry_count = 0;
3487        self.max_width_item_index = None;
3488
3489        let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
3490        let is_tree_view = matches!(self.view_mode, GitPanelViewMode::Tree(_));
3491        let group_by_status = is_tree_view || !sort_by_path;
3492
3493        let mut changed_entries = Vec::new();
3494        let mut new_entries = Vec::new();
3495        let mut conflict_entries = Vec::new();
3496        let mut single_staged_entry = None;
3497        let mut staged_count = 0;
3498        let mut seen_directories = HashSet::default();
3499        let mut max_width_estimate = 0usize;
3500        let mut max_width_item_index = None;
3501
3502        let Some(repo) = self.active_repository.as_ref() else {
3503            // Just clear entries if no repository is active.
3504            cx.notify();
3505            return;
3506        };
3507
3508        let repo = repo.read(cx);
3509
3510        self.stash_entries = repo.cached_stash();
3511
3512        for entry in repo.cached_status() {
3513            self.changes_count += 1;
3514            let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
3515            let is_new = entry.status.is_created();
3516            let staging = entry.status.staging();
3517
3518            if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
3519                && pending
3520                    .ops
3521                    .iter()
3522                    .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
3523            {
3524                continue;
3525            }
3526
3527            let entry = GitStatusEntry {
3528                repo_path: entry.repo_path.clone(),
3529                status: entry.status,
3530                staging,
3531            };
3532
3533            if staging.has_staged() {
3534                staged_count += 1;
3535                single_staged_entry = Some(entry.clone());
3536            }
3537
3538            if group_by_status && is_conflict {
3539                conflict_entries.push(entry);
3540            } else if group_by_status && is_new {
3541                new_entries.push(entry);
3542            } else {
3543                changed_entries.push(entry);
3544            }
3545        }
3546
3547        if conflict_entries.is_empty() {
3548            if staged_count == 1
3549                && let Some(entry) = single_staged_entry.as_ref()
3550            {
3551                if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
3552                    if ops.staged() {
3553                        self.single_staged_entry = single_staged_entry;
3554                    }
3555                } else {
3556                    self.single_staged_entry = single_staged_entry;
3557                }
3558            } else if repo.pending_ops_summary().item_summary.staging_count == 1
3559                && let Some(ops) = repo.pending_ops().find(|ops| ops.staging())
3560            {
3561                self.single_staged_entry =
3562                    repo.status_for_path(&ops.repo_path)
3563                        .map(|status| GitStatusEntry {
3564                            repo_path: ops.repo_path.clone(),
3565                            status: status.status,
3566                            staging: StageStatus::Staged,
3567                        });
3568            }
3569        }
3570
3571        if conflict_entries.is_empty() && changed_entries.len() == 1 {
3572            self.single_tracked_entry = changed_entries.first().cloned();
3573        }
3574
3575        let mut push_entry =
3576            |this: &mut Self,
3577             entry: GitListEntry,
3578             is_visible: bool,
3579             logical_indices: Option<&mut Vec<usize>>| {
3580                if let Some(estimate) =
3581                    this.width_estimate_for_list_entry(is_tree_view, &entry, path_style)
3582                {
3583                    if estimate > max_width_estimate {
3584                        max_width_estimate = estimate;
3585                        max_width_item_index = Some(this.entries.len());
3586                    }
3587                }
3588
3589                if let Some(repo_path) = entry.status_entry().map(|status| status.repo_path.clone())
3590                {
3591                    this.entries_indices.insert(repo_path, this.entries.len());
3592                }
3593
3594                if let (Some(indices), true) = (logical_indices, is_visible) {
3595                    indices.push(this.entries.len());
3596                }
3597
3598                this.entries.push(entry);
3599            };
3600
3601        macro_rules! take_section_entries {
3602            () => {
3603                [
3604                    (Section::Conflict, std::mem::take(&mut conflict_entries)),
3605                    (Section::Tracked, std::mem::take(&mut changed_entries)),
3606                    (Section::New, std::mem::take(&mut new_entries)),
3607                ]
3608            };
3609        }
3610
3611        match &mut self.view_mode {
3612            GitPanelViewMode::Tree(tree_state) => {
3613                tree_state.logical_indices.clear();
3614                tree_state.directory_descendants.clear();
3615
3616                // This is just to get around the borrow checker
3617                // because push_entry mutably borrows self
3618                let mut tree_state = std::mem::take(tree_state);
3619
3620                for (section, entries) in take_section_entries!() {
3621                    if entries.is_empty() {
3622                        continue;
3623                    }
3624
3625                    push_entry(
3626                        self,
3627                        GitListEntry::Header(GitHeaderEntry { header: section }),
3628                        true,
3629                        Some(&mut tree_state.logical_indices),
3630                    );
3631
3632                    for (entry, is_visible) in
3633                        tree_state.build_tree_entries(section, entries, &mut seen_directories)
3634                    {
3635                        push_entry(
3636                            self,
3637                            entry,
3638                            is_visible,
3639                            Some(&mut tree_state.logical_indices),
3640                        );
3641                    }
3642                }
3643
3644                tree_state
3645                    .expanded_dirs
3646                    .retain(|key, _| seen_directories.contains(key));
3647                self.view_mode = GitPanelViewMode::Tree(tree_state);
3648            }
3649            GitPanelViewMode::Flat => {
3650                for (section, entries) in take_section_entries!() {
3651                    if entries.is_empty() {
3652                        continue;
3653                    }
3654
3655                    if section != Section::Tracked || !sort_by_path {
3656                        push_entry(
3657                            self,
3658                            GitListEntry::Header(GitHeaderEntry { header: section }),
3659                            true,
3660                            None,
3661                        );
3662                    }
3663
3664                    for entry in entries {
3665                        push_entry(self, GitListEntry::Status(entry), true, None);
3666                    }
3667                }
3668            }
3669        }
3670
3671        self.max_width_item_index = max_width_item_index;
3672
3673        self.update_counts(repo);
3674
3675        let bulk_staging_anchor_new_index = bulk_staging
3676            .as_ref()
3677            .filter(|op| op.repo_id == repo.id)
3678            .and_then(|op| self.entry_by_path(&op.anchor));
3679        if bulk_staging_anchor_new_index == last_staged_path_prev_index
3680            && let Some(index) = bulk_staging_anchor_new_index
3681            && let Some(entry) = self.entries.get(index)
3682            && let Some(entry) = entry.status_entry()
3683            && GitPanel::stage_status_for_entry(entry, &repo)
3684                .as_bool()
3685                .unwrap_or(false)
3686        {
3687            self.bulk_staging = bulk_staging;
3688        }
3689
3690        self.select_first_entry_if_none(window, cx);
3691
3692        let suggested_commit_message = self.suggest_commit_message(cx);
3693        let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
3694
3695        self.commit_editor.update(cx, |editor, cx| {
3696            editor.set_placeholder_text(&placeholder_text, window, cx)
3697        });
3698
3699        cx.notify();
3700    }
3701
3702    fn header_state(&self, header_type: Section) -> ToggleState {
3703        let (staged_count, count) = match header_type {
3704            Section::New => (self.new_staged_count, self.new_count),
3705            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
3706            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
3707        };
3708        if staged_count == 0 {
3709            ToggleState::Unselected
3710        } else if count == staged_count {
3711            ToggleState::Selected
3712        } else {
3713            ToggleState::Indeterminate
3714        }
3715    }
3716
3717    fn update_counts(&mut self, repo: &Repository) {
3718        self.show_placeholders = false;
3719        self.conflicted_count = 0;
3720        self.conflicted_staged_count = 0;
3721        self.new_count = 0;
3722        self.tracked_count = 0;
3723        self.new_staged_count = 0;
3724        self.tracked_staged_count = 0;
3725        self.entry_count = 0;
3726
3727        for status_entry in self.entries.iter().filter_map(|entry| entry.status_entry()) {
3728            self.entry_count += 1;
3729            let is_staging_or_staged = GitPanel::stage_status_for_entry(status_entry, repo)
3730                .as_bool()
3731                .unwrap_or(true);
3732
3733            if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
3734                self.conflicted_count += 1;
3735                if is_staging_or_staged {
3736                    self.conflicted_staged_count += 1;
3737                }
3738            } else if status_entry.status.is_created() {
3739                self.new_count += 1;
3740                if is_staging_or_staged {
3741                    self.new_staged_count += 1;
3742                }
3743            } else {
3744                self.tracked_count += 1;
3745                if is_staging_or_staged {
3746                    self.tracked_staged_count += 1;
3747                }
3748            }
3749        }
3750    }
3751
3752    pub(crate) fn has_staged_changes(&self) -> bool {
3753        self.tracked_staged_count > 0
3754            || self.new_staged_count > 0
3755            || self.conflicted_staged_count > 0
3756    }
3757
3758    pub(crate) fn has_unstaged_changes(&self) -> bool {
3759        self.tracked_count > self.tracked_staged_count
3760            || self.new_count > self.new_staged_count
3761            || self.conflicted_count > self.conflicted_staged_count
3762    }
3763
3764    fn has_tracked_changes(&self) -> bool {
3765        self.tracked_count > 0
3766    }
3767
3768    pub fn has_unstaged_conflicts(&self) -> bool {
3769        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
3770    }
3771
3772    fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
3773        let Some(workspace) = self.workspace.upgrade() else {
3774            return;
3775        };
3776        show_error_toast(workspace, action, e, cx)
3777    }
3778
3779    fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3780    where
3781        E: std::fmt::Debug + std::fmt::Display,
3782    {
3783        if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3784            let _ = workspace.update(cx, |workspace, cx| {
3785                struct CommitMessageError;
3786                let notification_id = NotificationId::unique::<CommitMessageError>();
3787                workspace.show_notification(notification_id, cx, |cx| {
3788                    cx.new(|cx| {
3789                        ErrorMessagePrompt::new(
3790                            format!("Failed to generate commit message: {err}"),
3791                            cx,
3792                        )
3793                    })
3794                });
3795            });
3796        }
3797    }
3798
3799    fn show_remote_output(
3800        &mut self,
3801        action: RemoteAction,
3802        info: RemoteCommandOutput,
3803        cx: &mut Context<Self>,
3804    ) {
3805        let Some(workspace) = self.workspace.upgrade() else {
3806            return;
3807        };
3808
3809        workspace.update(cx, |workspace, cx| {
3810            let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3811            let workspace_weak = cx.weak_entity();
3812            let operation = action.name();
3813
3814            let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3815                use remote_output::SuccessStyle::*;
3816                match style {
3817                    Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3818                    ToastWithLog { output } => this
3819                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3820                        .action("View Log", move |window, cx| {
3821                            let output = output.clone();
3822                            let output =
3823                                format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3824                            workspace_weak
3825                                .update(cx, move |workspace, cx| {
3826                                    open_output(operation, workspace, &output, window, cx)
3827                                })
3828                                .ok();
3829                        }),
3830                    PushPrLink { text, link } => this
3831                        .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3832                        .action(text, move |_, cx| cx.open_url(&link)),
3833                }
3834                .dismiss_button(true)
3835            });
3836            workspace.toggle_status_toast(status_toast, cx)
3837        });
3838    }
3839
3840    pub fn can_commit(&self) -> bool {
3841        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3842    }
3843
3844    pub fn can_stage_all(&self) -> bool {
3845        self.has_unstaged_changes()
3846    }
3847
3848    pub fn can_unstage_all(&self) -> bool {
3849        self.has_staged_changes()
3850    }
3851
3852    /// Computes tree indentation depths for visible entries in the given range.
3853    /// Used by indent guides to render vertical connector lines in tree view.
3854    fn compute_visible_depths(&self, range: Range<usize>) -> SmallVec<[usize; 64]> {
3855        let GitPanelViewMode::Tree(state) = &self.view_mode else {
3856            return SmallVec::new();
3857        };
3858
3859        range
3860            .map(|ix| {
3861                state
3862                    .logical_indices
3863                    .get(ix)
3864                    .and_then(|&entry_ix| self.entries.get(entry_ix))
3865                    .map_or(0, |entry| entry.depth())
3866            })
3867            .collect()
3868    }
3869
3870    fn status_width_estimate(
3871        tree_view: bool,
3872        entry: &GitStatusEntry,
3873        path_style: PathStyle,
3874        depth: usize,
3875    ) -> usize {
3876        if tree_view {
3877            Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3878        } else {
3879            Self::item_width_estimate(
3880                entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3881                entry.display_name(path_style).len(),
3882                0,
3883            )
3884        }
3885    }
3886
3887    fn width_estimate_for_list_entry(
3888        &self,
3889        tree_view: bool,
3890        entry: &GitListEntry,
3891        path_style: PathStyle,
3892    ) -> Option<usize> {
3893        match entry {
3894            GitListEntry::Status(status) => Some(Self::status_width_estimate(
3895                tree_view, status, path_style, 0,
3896            )),
3897            GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3898                tree_view,
3899                &status.entry,
3900                path_style,
3901                status.depth,
3902            )),
3903            GitListEntry::Directory(dir) => {
3904                Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
3905            }
3906            GitListEntry::Header(_) => None,
3907        }
3908    }
3909
3910    fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
3911        path + file_name + depth * 2
3912    }
3913
3914    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3915        let focus_handle = self.focus_handle.clone();
3916        let has_tracked_changes = self.has_tracked_changes();
3917        let has_staged_changes = self.has_staged_changes();
3918        let has_unstaged_changes = self.has_unstaged_changes();
3919        let has_new_changes = self.new_count > 0;
3920        let has_stash_items = self.stash_entries.entries.len() > 0;
3921
3922        PopoverMenu::new(id.into())
3923            .trigger(
3924                IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3925                    .icon_size(IconSize::Small)
3926                    .icon_color(Color::Muted),
3927            )
3928            .menu(move |window, cx| {
3929                Some(git_panel_context_menu(
3930                    focus_handle.clone(),
3931                    GitMenuState {
3932                        has_tracked_changes,
3933                        has_staged_changes,
3934                        has_unstaged_changes,
3935                        has_new_changes,
3936                        sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3937                        has_stash_items,
3938                        tree_view: GitPanelSettings::get_global(cx).tree_view,
3939                    },
3940                    window,
3941                    cx,
3942                ))
3943            })
3944            .anchor(Corner::TopRight)
3945    }
3946
3947    pub(crate) fn render_generate_commit_message_button(
3948        &self,
3949        cx: &Context<Self>,
3950    ) -> Option<AnyElement> {
3951        if !agent_settings::AgentSettings::get_global(cx).enabled(cx) {
3952            return None;
3953        }
3954
3955        if self.generate_commit_message_task.is_some() {
3956            return Some(
3957                h_flex()
3958                    .gap_1()
3959                    .child(
3960                        Icon::new(IconName::ArrowCircle)
3961                            .size(IconSize::XSmall)
3962                            .color(Color::Info)
3963                            .with_rotate_animation(2),
3964                    )
3965                    .child(
3966                        Label::new("Generating Commit…")
3967                            .size(LabelSize::Small)
3968                            .color(Color::Muted),
3969                    )
3970                    .into_any_element(),
3971            );
3972        }
3973
3974        let model_registry = LanguageModelRegistry::read_global(cx);
3975        let has_commit_model_configuration_error = model_registry
3976            .configuration_error(model_registry.commit_message_model(), cx)
3977            .is_some();
3978        let can_commit = self.can_commit();
3979
3980        let editor_focus_handle = self.commit_editor.focus_handle(cx);
3981
3982        Some(
3983            IconButton::new("generate-commit-message", IconName::AiEdit)
3984                .shape(ui::IconButtonShape::Square)
3985                .icon_color(if has_commit_model_configuration_error {
3986                    Color::Disabled
3987                } else {
3988                    Color::Muted
3989                })
3990                .tooltip(move |_window, cx| {
3991                    if !can_commit {
3992                        Tooltip::simple("No Changes to Commit", cx)
3993                    } else if has_commit_model_configuration_error {
3994                        Tooltip::simple("Configure an LLM provider to generate commit messages", cx)
3995                    } else {
3996                        Tooltip::for_action_in(
3997                            "Generate Commit Message",
3998                            &git::GenerateCommitMessage,
3999                            &editor_focus_handle,
4000                            cx,
4001                        )
4002                    }
4003                })
4004                .disabled(!can_commit || has_commit_model_configuration_error)
4005                .on_click(cx.listener(move |this, _event, _window, cx| {
4006                    this.generate_commit_message(cx);
4007                }))
4008                .into_any_element(),
4009        )
4010    }
4011
4012    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
4013        let potential_co_authors = self.potential_co_authors(cx);
4014
4015        let (tooltip_label, icon) = if self.add_coauthors {
4016            ("Remove co-authored-by", IconName::Person)
4017        } else {
4018            ("Add co-authored-by", IconName::UserCheck)
4019        };
4020
4021        if potential_co_authors.is_empty() {
4022            None
4023        } else {
4024            Some(
4025                IconButton::new("co-authors", icon)
4026                    .shape(ui::IconButtonShape::Square)
4027                    .icon_color(Color::Disabled)
4028                    .selected_icon_color(Color::Selected)
4029                    .toggle_state(self.add_coauthors)
4030                    .tooltip(move |_, cx| {
4031                        let title = format!(
4032                            "{}:{}{}",
4033                            tooltip_label,
4034                            if potential_co_authors.len() == 1 {
4035                                ""
4036                            } else {
4037                                "\n"
4038                            },
4039                            potential_co_authors
4040                                .iter()
4041                                .map(|(name, email)| format!(" {} <{}>", name, email))
4042                                .join("\n")
4043                        );
4044                        Tooltip::simple(title, cx)
4045                    })
4046                    .on_click(cx.listener(|this, _, _, cx| {
4047                        this.add_coauthors = !this.add_coauthors;
4048                        cx.notify();
4049                    }))
4050                    .into_any_element(),
4051            )
4052        }
4053    }
4054
4055    fn render_git_commit_menu(
4056        &self,
4057        id: impl Into<ElementId>,
4058        keybinding_target: Option<FocusHandle>,
4059        cx: &mut Context<Self>,
4060    ) -> impl IntoElement {
4061        PopoverMenu::new(id.into())
4062            .trigger(
4063                ui::ButtonLike::new_rounded_right("commit-split-button-right")
4064                    .layer(ui::ElevationIndex::ModalSurface)
4065                    .size(ButtonSize::None)
4066                    .child(
4067                        h_flex()
4068                            .px_1()
4069                            .h_full()
4070                            .justify_center()
4071                            .border_l_1()
4072                            .border_color(cx.theme().colors().border)
4073                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
4074                    ),
4075            )
4076            .menu({
4077                let git_panel = cx.entity();
4078                let has_previous_commit = self.head_commit(cx).is_some();
4079                let amend = self.amend_pending();
4080                let signoff = self.signoff_enabled;
4081
4082                move |window, cx| {
4083                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
4084                        context_menu
4085                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
4086                                el.context(keybinding_target)
4087                            })
4088                            .when(has_previous_commit, |this| {
4089                                this.toggleable_entry(
4090                                    "Amend",
4091                                    amend,
4092                                    IconPosition::Start,
4093                                    Some(Box::new(Amend)),
4094                                    {
4095                                        let git_panel = git_panel.downgrade();
4096                                        move |_, cx| {
4097                                            git_panel
4098                                                .update(cx, |git_panel, cx| {
4099                                                    git_panel.toggle_amend_pending(cx);
4100                                                })
4101                                                .ok();
4102                                        }
4103                                    },
4104                                )
4105                            })
4106                            .toggleable_entry(
4107                                "Signoff",
4108                                signoff,
4109                                IconPosition::Start,
4110                                Some(Box::new(Signoff)),
4111                                move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
4112                            )
4113                    }))
4114                }
4115            })
4116            .anchor(Corner::TopRight)
4117    }
4118
4119    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
4120        if self.has_unstaged_conflicts() {
4121            (false, "You must resolve conflicts before committing")
4122        } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
4123            (false, "No changes to commit")
4124        } else if self.pending_commit.is_some() {
4125            (false, "Commit in progress")
4126        } else if !self.has_commit_message(cx) {
4127            (false, "No commit message")
4128        } else if !self.has_write_access(cx) {
4129            (false, "You do not have write access to this project")
4130        } else {
4131            (true, self.commit_button_title())
4132        }
4133    }
4134
4135    pub fn commit_button_title(&self) -> &'static str {
4136        if self.amend_pending {
4137            if self.has_staged_changes() {
4138                "Amend"
4139            } else if self.has_tracked_changes() {
4140                "Amend Tracked"
4141            } else {
4142                "Amend"
4143            }
4144        } else if self.has_staged_changes() {
4145            "Commit"
4146        } else {
4147            "Commit Tracked"
4148        }
4149    }
4150
4151    fn expand_commit_editor(
4152        &mut self,
4153        _: &git::ExpandCommitEditor,
4154        window: &mut Window,
4155        cx: &mut Context<Self>,
4156    ) {
4157        let workspace = self.workspace.clone();
4158        window.defer(cx, move |window, cx| {
4159            workspace
4160                .update(cx, |workspace, cx| {
4161                    CommitModal::toggle(workspace, None, window, cx)
4162                })
4163                .ok();
4164        })
4165    }
4166
4167    fn render_panel_header(
4168        &self,
4169        window: &mut Window,
4170        cx: &mut Context<Self>,
4171    ) -> Option<impl IntoElement> {
4172        self.active_repository.as_ref()?;
4173
4174        let (text, action, stage, tooltip) =
4175            if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
4176                ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
4177            } else {
4178                ("Stage All", StageAll.boxed_clone(), true, "git add --all")
4179            };
4180
4181        let change_string = match self.changes_count {
4182            0 => "No Changes".to_string(),
4183            1 => "1 Change".to_string(),
4184            count => format!("{} Changes", count),
4185        };
4186
4187        Some(
4188            self.panel_header_container(window, cx)
4189                .px_2()
4190                .justify_between()
4191                .child(
4192                    panel_button(change_string)
4193                        .color(Color::Muted)
4194                        .tooltip(Tooltip::for_action_title_in(
4195                            "Open Diff",
4196                            &Diff,
4197                            &self.focus_handle,
4198                        ))
4199                        .on_click(|_, _, cx| {
4200                            cx.defer(|cx| {
4201                                cx.dispatch_action(&Diff);
4202                            })
4203                        }),
4204                )
4205                .child(
4206                    h_flex()
4207                        .gap_1()
4208                        .child(self.render_overflow_menu("overflow_menu"))
4209                        .child(
4210                            panel_filled_button(text)
4211                                .tooltip(Tooltip::for_action_title_in(
4212                                    tooltip,
4213                                    action.as_ref(),
4214                                    &self.focus_handle,
4215                                ))
4216                                .disabled(self.entry_count == 0)
4217                                .on_click({
4218                                    let git_panel = cx.weak_entity();
4219                                    move |_, _, cx| {
4220                                        git_panel
4221                                            .update(cx, |git_panel, cx| {
4222                                                git_panel.change_all_files_stage(stage, cx);
4223                                            })
4224                                            .ok();
4225                                    }
4226                                }),
4227                        ),
4228                ),
4229        )
4230    }
4231
4232    pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4233        let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
4234        if !self.can_push_and_pull(cx) {
4235            return None;
4236        }
4237        Some(
4238            h_flex()
4239                .gap_1()
4240                .flex_shrink_0()
4241                .when_some(branch, |this, branch| {
4242                    let focus_handle = Some(self.focus_handle(cx));
4243
4244                    this.children(render_remote_button(
4245                        "remote-button",
4246                        &branch,
4247                        focus_handle,
4248                        true,
4249                    ))
4250                })
4251                .into_any_element(),
4252        )
4253    }
4254
4255    pub fn render_footer(
4256        &self,
4257        window: &mut Window,
4258        cx: &mut Context<Self>,
4259    ) -> Option<impl IntoElement> {
4260        let active_repository = self.active_repository.clone()?;
4261        let panel_editor_style = panel_editor_style(true, window, cx);
4262        let enable_coauthors = self.render_co_authors(cx);
4263
4264        let editor_focus_handle = self.commit_editor.focus_handle(cx);
4265        let expand_tooltip_focus_handle = editor_focus_handle;
4266
4267        let branch = active_repository.read(cx).branch.clone();
4268        let head_commit = active_repository.read(cx).head_commit.clone();
4269
4270        let footer_size = px(32.);
4271        let gap = px(9.0);
4272        let max_height = panel_editor_style
4273            .text
4274            .line_height_in_pixels(window.rem_size())
4275            * MAX_PANEL_EDITOR_LINES
4276            + gap;
4277
4278        let git_panel = cx.entity();
4279        let display_name = SharedString::from(Arc::from(
4280            active_repository
4281                .read(cx)
4282                .display_name()
4283                .trim_end_matches("/"),
4284        ));
4285        let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4286            editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4287        });
4288
4289        let footer = v_flex()
4290            .child(PanelRepoFooter::new(
4291                display_name,
4292                branch,
4293                head_commit,
4294                Some(git_panel),
4295            ))
4296            .child(
4297                panel_editor_container(window, cx)
4298                    .id("commit-editor-container")
4299                    .relative()
4300                    .w_full()
4301                    .h(max_height + footer_size)
4302                    .border_t_1()
4303                    .border_color(cx.theme().colors().border)
4304                    .cursor_text()
4305                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4306                        window.focus(&this.commit_editor.focus_handle(cx), cx);
4307                    }))
4308                    .child(
4309                        h_flex()
4310                            .id("commit-footer")
4311                            .border_t_1()
4312                            .when(editor_is_long, |el| {
4313                                el.border_color(cx.theme().colors().border_variant)
4314                            })
4315                            .absolute()
4316                            .bottom_0()
4317                            .left_0()
4318                            .w_full()
4319                            .px_2()
4320                            .h(footer_size)
4321                            .flex_none()
4322                            .justify_between()
4323                            .child(
4324                                self.render_generate_commit_message_button(cx)
4325                                    .unwrap_or_else(|| div().into_any_element()),
4326                            )
4327                            .child(
4328                                h_flex()
4329                                    .gap_0p5()
4330                                    .children(enable_coauthors)
4331                                    .child(self.render_commit_button(cx)),
4332                            ),
4333                    )
4334                    .child(
4335                        div()
4336                            .pr_2p5()
4337                            .on_action(|&zed_actions::editor::MoveUp, _, cx| {
4338                                cx.stop_propagation();
4339                            })
4340                            .on_action(|&zed_actions::editor::MoveDown, _, cx| {
4341                                cx.stop_propagation();
4342                            })
4343                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4344                    )
4345                    .child(
4346                        h_flex()
4347                            .absolute()
4348                            .top_2()
4349                            .right_2()
4350                            .opacity(0.5)
4351                            .hover(|this| this.opacity(1.0))
4352                            .child(
4353                                panel_icon_button("expand-commit-editor", IconName::Maximize)
4354                                    .icon_size(IconSize::Small)
4355                                    .size(ui::ButtonSize::Default)
4356                                    .tooltip(move |_window, cx| {
4357                                        Tooltip::for_action_in(
4358                                            "Open Commit Modal",
4359                                            &git::ExpandCommitEditor,
4360                                            &expand_tooltip_focus_handle,
4361                                            cx,
4362                                        )
4363                                    })
4364                                    .on_click(cx.listener({
4365                                        move |_, _, window, cx| {
4366                                            window.dispatch_action(
4367                                                git::ExpandCommitEditor.boxed_clone(),
4368                                                cx,
4369                                            )
4370                                        }
4371                                    })),
4372                            ),
4373                    ),
4374            );
4375
4376        Some(footer)
4377    }
4378
4379    fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4380        let (can_commit, tooltip) = self.configure_commit_button(cx);
4381        let title = self.commit_button_title();
4382        let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4383        let amend = self.amend_pending();
4384        let signoff = self.signoff_enabled;
4385
4386        let label_color = if self.pending_commit.is_some() {
4387            Color::Disabled
4388        } else {
4389            Color::Default
4390        };
4391
4392        div()
4393            .id("commit-wrapper")
4394            .on_hover(cx.listener(move |this, hovered, _, cx| {
4395                this.show_placeholders =
4396                    *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4397                cx.notify()
4398            }))
4399            .child(SplitButton::new(
4400                ButtonLike::new_rounded_left(ElementId::Name(
4401                    format!("split-button-left-{}", title).into(),
4402                ))
4403                .layer(ElevationIndex::ModalSurface)
4404                .size(ButtonSize::Compact)
4405                .child(
4406                    Label::new(title)
4407                        .size(LabelSize::Small)
4408                        .color(label_color)
4409                        .mr_0p5(),
4410                )
4411                .on_click({
4412                    let git_panel = cx.weak_entity();
4413                    move |_, window, cx| {
4414                        telemetry::event!("Git Committed", source = "Git Panel");
4415                        git_panel
4416                            .update(cx, |git_panel, cx| {
4417                                git_panel.commit_changes(
4418                                    CommitOptions { amend, signoff },
4419                                    window,
4420                                    cx,
4421                                );
4422                            })
4423                            .ok();
4424                    }
4425                })
4426                .disabled(!can_commit || self.modal_open)
4427                .tooltip({
4428                    let handle = commit_tooltip_focus_handle.clone();
4429                    move |_window, cx| {
4430                        if can_commit {
4431                            Tooltip::with_meta_in(
4432                                tooltip,
4433                                Some(if amend { &git::Amend } else { &git::Commit }),
4434                                format!(
4435                                    "git commit{}{}",
4436                                    if amend { " --amend" } else { "" },
4437                                    if signoff { " --signoff" } else { "" }
4438                                ),
4439                                &handle.clone(),
4440                                cx,
4441                            )
4442                        } else {
4443                            Tooltip::simple(tooltip, cx)
4444                        }
4445                    }
4446                }),
4447                self.render_git_commit_menu(
4448                    ElementId::Name(format!("split-button-right-{}", title).into()),
4449                    Some(commit_tooltip_focus_handle),
4450                    cx,
4451                )
4452                .into_any_element(),
4453            ))
4454    }
4455
4456    fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4457        h_flex()
4458            .py_1p5()
4459            .px_2()
4460            .gap_1p5()
4461            .justify_between()
4462            .border_t_1()
4463            .border_color(cx.theme().colors().border.opacity(0.8))
4464            .child(
4465                div()
4466                    .flex_grow()
4467                    .overflow_hidden()
4468                    .max_w(relative(0.85))
4469                    .child(
4470                        Label::new("This will update your most recent commit.")
4471                            .size(LabelSize::Small)
4472                            .truncate(),
4473                    ),
4474            )
4475            .child(
4476                panel_button("Cancel")
4477                    .size(ButtonSize::Default)
4478                    .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4479            )
4480    }
4481
4482    fn render_previous_commit(
4483        &self,
4484        window: &mut Window,
4485        cx: &mut Context<Self>,
4486    ) -> Option<impl IntoElement> {
4487        let active_repository = self.active_repository.as_ref()?;
4488        let branch = active_repository.read(cx).branch.as_ref()?;
4489        let commit = branch.most_recent_commit.as_ref()?.clone();
4490        let workspace = self.workspace.clone();
4491        let this = cx.entity();
4492
4493        Some(
4494            h_flex()
4495                .p_1p5()
4496                .gap_1p5()
4497                .justify_between()
4498                .border_t_1()
4499                .border_color(cx.theme().colors().border.opacity(0.8))
4500                .child(
4501                    div()
4502                        .id("commit-msg-hover")
4503                        .cursor_pointer()
4504                        .px_1()
4505                        .rounded_sm()
4506                        .line_clamp(1)
4507                        .hover(|s| s.bg(cx.theme().colors().element_hover))
4508                        .child(
4509                            Label::new(commit.subject.clone())
4510                                .size(LabelSize::Small)
4511                                .truncate(),
4512                        )
4513                        .on_click({
4514                            let commit = commit.clone();
4515                            let repo = active_repository.downgrade();
4516                            move |_, window, cx| {
4517                                CommitView::open(
4518                                    commit.sha.to_string(),
4519                                    repo.clone(),
4520                                    workspace.clone(),
4521                                    None,
4522                                    None,
4523                                    window,
4524                                    cx,
4525                                );
4526                            }
4527                        })
4528                        .hoverable_tooltip({
4529                            let repo = active_repository.clone();
4530                            move |window, cx| {
4531                                GitPanelMessageTooltip::new(
4532                                    this.clone(),
4533                                    commit.sha.clone(),
4534                                    repo.clone(),
4535                                    window,
4536                                    cx,
4537                                )
4538                                .into()
4539                            }
4540                        }),
4541                )
4542                .child(
4543                    h_flex()
4544                        .gap_0p5()
4545                        .when(commit.has_parent, |this| {
4546                            let has_unstaged = self.has_unstaged_changes();
4547                            this.child(
4548                                panel_icon_button("undo", IconName::Undo)
4549                                    .icon_size(IconSize::Small)
4550                                    .tooltip(move |_window, cx| {
4551                                        Tooltip::with_meta(
4552                                            "Uncommit",
4553                                            Some(&git::Uncommit),
4554                                            if has_unstaged {
4555                                                "git reset HEAD^ --soft"
4556                                            } else {
4557                                                "git reset HEAD^"
4558                                            },
4559                                            cx,
4560                                        )
4561                                    })
4562                                    .on_click(
4563                                        cx.listener(|this, _, window, cx| {
4564                                            this.uncommit(window, cx)
4565                                        }),
4566                                    ),
4567                            )
4568                        })
4569                        .when(window.is_action_available(&Open, cx), |this| {
4570                            this.child(
4571                                panel_icon_button("git-graph-button", IconName::GitGraph)
4572                                    .icon_size(IconSize::Small)
4573                                    .tooltip(|_window, cx| {
4574                                        Tooltip::for_action("Open Git Graph", &Open, cx)
4575                                    })
4576                                    .on_click(|_, window, cx| {
4577                                        window.dispatch_action(Open.boxed_clone(), cx)
4578                                    }),
4579                            )
4580                        }),
4581                ),
4582        )
4583    }
4584
4585    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4586        let has_repo = self.active_repository.is_some();
4587        let has_no_repo = self.active_repository.is_none();
4588        let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4589
4590        let should_show_branch_diff =
4591            has_repo && self.changes_count == 0 && !self.is_on_main_branch(cx);
4592
4593        let label = if has_repo {
4594            "No changes to commit"
4595        } else {
4596            "No Git repositories"
4597        };
4598
4599        v_flex()
4600            .gap_1p5()
4601            .flex_1()
4602            .items_center()
4603            .justify_center()
4604            .child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
4605            .when(has_no_repo && worktree_count > 0, |this| {
4606                this.child(
4607                    panel_filled_button("Initialize Repository")
4608                        .tooltip(Tooltip::for_action_title_in(
4609                            "git init",
4610                            &git::Init,
4611                            &self.focus_handle,
4612                        ))
4613                        .on_click(move |_, _, cx| {
4614                            cx.defer(move |cx| {
4615                                cx.dispatch_action(&git::Init);
4616                            })
4617                        }),
4618                )
4619            })
4620            .when(should_show_branch_diff, |this| {
4621                this.child(
4622                    panel_filled_button("View Branch Diff")
4623                        .tooltip(move |_, cx| {
4624                            Tooltip::with_meta(
4625                                "Branch Diff",
4626                                Some(&BranchDiff),
4627                                "Show diff between working directory and default branch",
4628                                cx,
4629                            )
4630                        })
4631                        .on_click(move |_, _, cx| {
4632                            cx.defer(move |cx| {
4633                                cx.dispatch_action(&BranchDiff);
4634                            })
4635                        }),
4636                )
4637            })
4638    }
4639
4640    fn is_on_main_branch(&self, cx: &Context<Self>) -> bool {
4641        let Some(repo) = self.active_repository.as_ref() else {
4642            return false;
4643        };
4644
4645        let Some(branch) = repo.read(cx).branch.as_ref() else {
4646            return false;
4647        };
4648
4649        let branch_name = branch.name();
4650        matches!(branch_name, "main" | "master")
4651    }
4652
4653    fn render_buffer_header_controls(
4654        &self,
4655        entity: &Entity<Self>,
4656        file: &Arc<dyn File>,
4657        _: &Window,
4658        cx: &App,
4659    ) -> Option<AnyElement> {
4660        let repo = self.active_repository.as_ref()?.read(cx);
4661        let project_path = (file.worktree_id(cx), file.path().clone()).into();
4662        let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4663        let ix = self.entry_by_path(&repo_path)?;
4664        let entry = self.entries.get(ix)?;
4665
4666        let is_staging_or_staged = repo
4667            .pending_ops_for_path(&repo_path)
4668            .map(|ops| ops.staging() || ops.staged())
4669            .or_else(|| {
4670                repo.status_for_path(&repo_path)
4671                    .and_then(|status| status.status.staging().as_bool())
4672            })
4673            .or_else(|| {
4674                entry
4675                    .status_entry()
4676                    .and_then(|entry| entry.staging.as_bool())
4677            });
4678
4679        let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4680            .disabled(!self.has_write_access(cx))
4681            .fill()
4682            .elevation(ElevationIndex::Surface)
4683            .on_click({
4684                let entry = entry.clone();
4685                let git_panel = entity.downgrade();
4686                move |_, window, cx| {
4687                    git_panel
4688                        .update(cx, |this, cx| {
4689                            this.toggle_staged_for_entry(&entry, window, cx);
4690                            cx.stop_propagation();
4691                        })
4692                        .ok();
4693                }
4694            });
4695        Some(
4696            h_flex()
4697                .id("start-slot")
4698                .text_lg()
4699                .child(checkbox)
4700                .on_mouse_down(MouseButton::Left, |_, _, cx| {
4701                    // prevent the list item active state triggering when toggling checkbox
4702                    cx.stop_propagation();
4703                })
4704                .into_any_element(),
4705        )
4706    }
4707
4708    fn render_entries(
4709        &self,
4710        has_write_access: bool,
4711        repo: Entity<Repository>,
4712        window: &mut Window,
4713        cx: &mut Context<Self>,
4714    ) -> impl IntoElement {
4715        let (is_tree_view, entry_count) = match &self.view_mode {
4716            GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4717            GitPanelViewMode::Flat => (false, self.entries.len()),
4718        };
4719        let repo = repo.downgrade();
4720
4721        v_flex()
4722            .flex_1()
4723            .size_full()
4724            .overflow_hidden()
4725            .relative()
4726            .child(
4727                h_flex()
4728                    .flex_1()
4729                    .size_full()
4730                    .relative()
4731                    .overflow_hidden()
4732                    .child(
4733                        uniform_list(
4734                            "entries",
4735                            entry_count,
4736                            cx.processor(move |this, range: Range<usize>, window, cx| {
4737                                let Some(repo) = repo.upgrade() else {
4738                                    return Vec::new();
4739                                };
4740                                let repo = repo.read(cx);
4741
4742                                let mut items = Vec::with_capacity(range.end - range.start);
4743
4744                                for ix in range.into_iter().map(|ix| match &this.view_mode {
4745                                    GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4746                                    GitPanelViewMode::Flat => ix,
4747                                }) {
4748                                    match &this.entries.get(ix) {
4749                                        Some(GitListEntry::Status(entry)) => {
4750                                            items.push(this.render_status_entry(
4751                                                ix,
4752                                                entry,
4753                                                0,
4754                                                has_write_access,
4755                                                repo,
4756                                                window,
4757                                                cx,
4758                                            ));
4759                                        }
4760                                        Some(GitListEntry::TreeStatus(entry)) => {
4761                                            items.push(this.render_status_entry(
4762                                                ix,
4763                                                &entry.entry,
4764                                                entry.depth,
4765                                                has_write_access,
4766                                                repo,
4767                                                window,
4768                                                cx,
4769                                            ));
4770                                        }
4771                                        Some(GitListEntry::Directory(entry)) => {
4772                                            items.push(this.render_directory_entry(
4773                                                ix,
4774                                                entry,
4775                                                has_write_access,
4776                                                window,
4777                                                cx,
4778                                            ));
4779                                        }
4780                                        Some(GitListEntry::Header(header)) => {
4781                                            items.push(this.render_list_header(
4782                                                ix,
4783                                                header,
4784                                                has_write_access,
4785                                                window,
4786                                                cx,
4787                                            ));
4788                                        }
4789                                        None => {}
4790                                    }
4791                                }
4792
4793                                items
4794                            }),
4795                        )
4796                        .when(is_tree_view, |list| {
4797                            let indent_size = px(TREE_INDENT);
4798                            list.with_decoration(
4799                                ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4800                                    .with_compute_indents_fn(
4801                                        cx.entity(),
4802                                        |this, range, _window, _cx| {
4803                                            this.compute_visible_depths(range)
4804                                        },
4805                                    )
4806                                    .with_render_fn(cx.entity(), |_, params, _, _| {
4807                                        // Magic number to align the tree item is 3 here
4808                                        // because we're using 12px as the left-side padding
4809                                        // and 3 makes the alignment work with the bounding box of the icon
4810                                        let left_offset = px(TREE_INDENT + 3_f32);
4811                                        let indent_size = params.indent_size;
4812                                        let item_height = params.item_height;
4813
4814                                        params
4815                                            .indent_guides
4816                                            .into_iter()
4817                                            .map(|layout| {
4818                                                let bounds = Bounds::new(
4819                                                    point(
4820                                                        layout.offset.x * indent_size + left_offset,
4821                                                        layout.offset.y * item_height,
4822                                                    ),
4823                                                    size(px(1.), layout.length * item_height),
4824                                                );
4825                                                RenderedIndentGuide {
4826                                                    bounds,
4827                                                    layout,
4828                                                    is_active: false,
4829                                                    hitbox: None,
4830                                                }
4831                                            })
4832                                            .collect()
4833                                    }),
4834                            )
4835                        })
4836                        .size_full()
4837                        .flex_grow()
4838                        .with_width_from_item(self.max_width_item_index)
4839                        .track_scroll(&self.scroll_handle),
4840                    )
4841                    .on_mouse_down(
4842                        MouseButton::Right,
4843                        cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4844                            this.deploy_panel_context_menu(event.position, window, cx)
4845                        }),
4846                    )
4847                    .custom_scrollbars(
4848                        Scrollbars::for_settings::<GitPanelSettings>()
4849                            .tracked_scroll_handle(&self.scroll_handle)
4850                            .with_track_along(
4851                                ScrollAxes::Horizontal,
4852                                cx.theme().colors().panel_background,
4853                            ),
4854                        window,
4855                        cx,
4856                    ),
4857            )
4858    }
4859
4860    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4861        Label::new(label.into()).color(color)
4862    }
4863
4864    fn list_item_height(&self) -> Rems {
4865        rems(1.75)
4866    }
4867
4868    fn render_list_header(
4869        &self,
4870        ix: usize,
4871        header: &GitHeaderEntry,
4872        _: bool,
4873        _: &Window,
4874        _: &Context<Self>,
4875    ) -> AnyElement {
4876        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4877
4878        h_flex()
4879            .id(id)
4880            .h(self.list_item_height())
4881            .w_full()
4882            .items_end()
4883            .px_3()
4884            .pb_1()
4885            .child(
4886                Label::new(header.title())
4887                    .color(Color::Muted)
4888                    .size(LabelSize::Small)
4889                    .line_height_style(LineHeightStyle::UiLabel)
4890                    .single_line(),
4891            )
4892            .into_any_element()
4893    }
4894
4895    pub fn load_commit_details(
4896        &self,
4897        sha: String,
4898        cx: &mut Context<Self>,
4899    ) -> Task<anyhow::Result<CommitDetails>> {
4900        let Some(repo) = self.active_repository.clone() else {
4901            return Task::ready(Err(anyhow::anyhow!("no active repo")));
4902        };
4903        repo.update(cx, |repo, cx| {
4904            let show = repo.show(sha);
4905            cx.spawn(async move |_, _| show.await?)
4906        })
4907    }
4908
4909    fn deploy_entry_context_menu(
4910        &mut self,
4911        position: Point<Pixels>,
4912        ix: usize,
4913        window: &mut Window,
4914        cx: &mut Context<Self>,
4915    ) {
4916        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4917            return;
4918        };
4919        let stage_title = if entry.status.staging().is_fully_staged() {
4920            "Unstage File"
4921        } else {
4922            "Stage File"
4923        };
4924        let restore_title = if entry.status.is_created() {
4925            "Trash File"
4926        } else {
4927            "Discard Changes"
4928        };
4929        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4930            let is_created = entry.status.is_created();
4931            context_menu
4932                .context(self.focus_handle.clone())
4933                .action(stage_title, ToggleStaged.boxed_clone())
4934                .action(restore_title, git::RestoreFile::default().boxed_clone())
4935                .action_disabled_when(
4936                    !is_created,
4937                    "Add to .gitignore",
4938                    git::AddToGitignore.boxed_clone(),
4939                )
4940                .separator()
4941                .action("Open Diff", menu::Confirm.boxed_clone())
4942                .action("Open File", menu::SecondaryConfirm.boxed_clone())
4943                .separator()
4944                .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
4945        });
4946        self.selected_entry = Some(ix);
4947        self.set_context_menu(context_menu, position, window, cx);
4948    }
4949
4950    fn deploy_panel_context_menu(
4951        &mut self,
4952        position: Point<Pixels>,
4953        window: &mut Window,
4954        cx: &mut Context<Self>,
4955    ) {
4956        let context_menu = git_panel_context_menu(
4957            self.focus_handle.clone(),
4958            GitMenuState {
4959                has_tracked_changes: self.has_tracked_changes(),
4960                has_staged_changes: self.has_staged_changes(),
4961                has_unstaged_changes: self.has_unstaged_changes(),
4962                has_new_changes: self.new_count > 0,
4963                sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4964                has_stash_items: self.stash_entries.entries.len() > 0,
4965                tree_view: GitPanelSettings::get_global(cx).tree_view,
4966            },
4967            window,
4968            cx,
4969        );
4970        self.set_context_menu(context_menu, position, window, cx);
4971    }
4972
4973    fn set_context_menu(
4974        &mut self,
4975        context_menu: Entity<ContextMenu>,
4976        position: Point<Pixels>,
4977        window: &Window,
4978        cx: &mut Context<Self>,
4979    ) {
4980        let subscription = cx.subscribe_in(
4981            &context_menu,
4982            window,
4983            |this, _, _: &DismissEvent, window, cx| {
4984                if this.context_menu.as_ref().is_some_and(|context_menu| {
4985                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
4986                }) {
4987                    cx.focus_self(window);
4988                }
4989                this.context_menu.take();
4990                cx.notify();
4991            },
4992        );
4993        self.context_menu = Some((context_menu, position, subscription));
4994        cx.notify();
4995    }
4996
4997    fn render_status_entry(
4998        &self,
4999        ix: usize,
5000        entry: &GitStatusEntry,
5001        depth: usize,
5002        has_write_access: bool,
5003        repo: &Repository,
5004        window: &Window,
5005        cx: &Context<Self>,
5006    ) -> AnyElement {
5007        let tree_view = GitPanelSettings::get_global(cx).tree_view;
5008        let path_style = self.project.read(cx).path_style(cx);
5009        let git_path_style = ProjectSettings::get_global(cx).git.path_style;
5010        let display_name = entry.display_name(path_style);
5011
5012        let selected = self.selected_entry == Some(ix);
5013        let marked = self.marked_entries.contains(&ix);
5014        let status_style = GitPanelSettings::get_global(cx).status_style;
5015        let status = entry.status;
5016
5017        let has_conflict = status.is_conflicted();
5018        let is_modified = status.is_modified();
5019        let is_deleted = status.is_deleted();
5020        let is_created = status.is_created();
5021
5022        let label_color = if status_style == StatusStyle::LabelColor {
5023            if has_conflict {
5024                Color::VersionControlConflict
5025            } else if is_created {
5026                Color::VersionControlAdded
5027            } else if is_modified {
5028                Color::VersionControlModified
5029            } else if is_deleted {
5030                // We don't want a bunch of red labels in the list
5031                Color::Disabled
5032            } else {
5033                Color::VersionControlAdded
5034            }
5035        } else {
5036            Color::Default
5037        };
5038
5039        let path_color = if status.is_deleted() {
5040            Color::Disabled
5041        } else {
5042            Color::Muted
5043        };
5044
5045        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
5046        let checkbox_wrapper_id: ElementId =
5047            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
5048        let checkbox_id: ElementId =
5049            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
5050
5051        let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
5052        let mut is_staged: ToggleState = match stage_status {
5053            StageStatus::Staged => ToggleState::Selected,
5054            StageStatus::Unstaged => ToggleState::Unselected,
5055            StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5056        };
5057        if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
5058            is_staged = ToggleState::Selected;
5059        }
5060
5061        let handle = cx.weak_entity();
5062
5063        let selected_bg_alpha = 0.08;
5064        let marked_bg_alpha = 0.12;
5065        let state_opacity_step = 0.04;
5066
5067        let info_color = cx.theme().status().info;
5068
5069        let base_bg = match (selected, marked) {
5070            (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
5071            (true, false) => info_color.alpha(selected_bg_alpha),
5072            (false, true) => info_color.alpha(marked_bg_alpha),
5073            _ => cx.theme().colors().ghost_element_background,
5074        };
5075
5076        let (hover_bg, active_bg) = if selected {
5077            (
5078                info_color.alpha(selected_bg_alpha + state_opacity_step),
5079                info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5080            )
5081        } else {
5082            (
5083                cx.theme().colors().ghost_element_hover,
5084                cx.theme().colors().ghost_element_active,
5085            )
5086        };
5087
5088        let name_row = h_flex()
5089            .min_w_0()
5090            .flex_1()
5091            .gap_1()
5092            .child(git_status_icon(status))
5093            .map(|this| {
5094                if tree_view {
5095                    this.pl(px(depth as f32 * TREE_INDENT)).child(
5096                        self.entry_label(display_name, label_color)
5097                            .when(status.is_deleted(), Label::strikethrough)
5098                            .truncate(),
5099                    )
5100                } else {
5101                    this.child(self.path_formatted(
5102                        entry.parent_dir(path_style),
5103                        path_color,
5104                        display_name,
5105                        label_color,
5106                        path_style,
5107                        git_path_style,
5108                        status.is_deleted(),
5109                    ))
5110                }
5111            });
5112
5113        h_flex()
5114            .id(id)
5115            .h(self.list_item_height())
5116            .w_full()
5117            .pl_3()
5118            .pr_1()
5119            .gap_1p5()
5120            .border_1()
5121            .border_r_2()
5122            .when(selected && self.focus_handle.is_focused(window), |el| {
5123                el.border_color(cx.theme().colors().panel_focused_border)
5124            })
5125            .bg(base_bg)
5126            .hover(|s| s.bg(hover_bg))
5127            .active(|s| s.bg(active_bg))
5128            .child(name_row)
5129            .child(
5130                div()
5131                    .id(checkbox_wrapper_id)
5132                    .flex_none()
5133                    .occlude()
5134                    .cursor_pointer()
5135                    .child(
5136                        Checkbox::new(checkbox_id, is_staged)
5137                            .disabled(!has_write_access)
5138                            .fill()
5139                            .elevation(ElevationIndex::Surface)
5140                            .on_click_ext({
5141                                let entry = entry.clone();
5142                                let this = cx.weak_entity();
5143                                move |_, click, window, cx| {
5144                                    this.update(cx, |this, cx| {
5145                                        if !has_write_access {
5146                                            return;
5147                                        }
5148                                        if click.modifiers().shift {
5149                                            this.stage_bulk(ix, cx);
5150                                        } else {
5151                                            let list_entry =
5152                                                if GitPanelSettings::get_global(cx).tree_view {
5153                                                    GitListEntry::TreeStatus(GitTreeStatusEntry {
5154                                                        entry: entry.clone(),
5155                                                        depth,
5156                                                    })
5157                                                } else {
5158                                                    GitListEntry::Status(entry.clone())
5159                                                };
5160                                            this.toggle_staged_for_entry(&list_entry, window, cx);
5161                                        }
5162                                        cx.stop_propagation();
5163                                    })
5164                                    .ok();
5165                                }
5166                            })
5167                            .tooltip(move |_window, cx| {
5168                                let action = match stage_status {
5169                                    StageStatus::Staged => "Unstage",
5170                                    StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5171                                };
5172                                let tooltip_name = action.to_string();
5173
5174                                Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5175                            }),
5176                    ),
5177            )
5178            .on_click({
5179                cx.listener(move |this, event: &ClickEvent, window, cx| {
5180                    this.selected_entry = Some(ix);
5181                    cx.notify();
5182                    if event.click_count() > 1 || event.modifiers().secondary() {
5183                        this.open_file(&Default::default(), window, cx)
5184                    } else {
5185                        this.open_diff(&Default::default(), window, cx);
5186                        this.focus_handle.focus(window, cx);
5187                    }
5188                })
5189            })
5190            .on_mouse_down(
5191                MouseButton::Right,
5192                move |event: &MouseDownEvent, window, cx| {
5193                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5194                    if event.button != MouseButton::Right {
5195                        return;
5196                    }
5197
5198                    let Some(this) = handle.upgrade() else {
5199                        return;
5200                    };
5201                    this.update(cx, |this, cx| {
5202                        this.deploy_entry_context_menu(event.position, ix, window, cx);
5203                    });
5204                    cx.stop_propagation();
5205                },
5206            )
5207            .into_any_element()
5208    }
5209
5210    fn render_directory_entry(
5211        &self,
5212        ix: usize,
5213        entry: &GitTreeDirEntry,
5214        has_write_access: bool,
5215        window: &Window,
5216        cx: &Context<Self>,
5217    ) -> AnyElement {
5218        // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5219        let selected = self.selected_entry == Some(ix);
5220        let label_color = Color::Muted;
5221
5222        let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5223        let checkbox_id: ElementId =
5224            ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5225        let checkbox_wrapper_id: ElementId =
5226            ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5227
5228        let selected_bg_alpha = 0.08;
5229        let state_opacity_step = 0.04;
5230
5231        let info_color = cx.theme().status().info;
5232        let colors = cx.theme().colors();
5233
5234        let (base_bg, hover_bg, active_bg) = if selected {
5235            (
5236                info_color.alpha(selected_bg_alpha),
5237                info_color.alpha(selected_bg_alpha + state_opacity_step),
5238                info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5239            )
5240        } else {
5241            (
5242                colors.ghost_element_background,
5243                colors.ghost_element_hover,
5244                colors.ghost_element_active,
5245            )
5246        };
5247
5248        let folder_icon = if entry.expanded {
5249            IconName::FolderOpen
5250        } else {
5251            IconName::Folder
5252        };
5253
5254        let stage_status = if let Some(repo) = &self.active_repository {
5255            self.stage_status_for_directory(entry, repo.read(cx))
5256        } else {
5257            util::debug_panic!(
5258                "Won't have entries to render without an active repository in Git Panel"
5259            );
5260            StageStatus::PartiallyStaged
5261        };
5262
5263        let toggle_state: ToggleState = match stage_status {
5264            StageStatus::Staged => ToggleState::Selected,
5265            StageStatus::Unstaged => ToggleState::Unselected,
5266            StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5267        };
5268
5269        let name_row = h_flex()
5270            .min_w_0()
5271            .gap_1()
5272            .pl(px(entry.depth as f32 * TREE_INDENT))
5273            .child(
5274                Icon::new(folder_icon)
5275                    .size(IconSize::Small)
5276                    .color(Color::Muted),
5277            )
5278            .child(self.entry_label(entry.name.clone(), label_color).truncate());
5279
5280        h_flex()
5281            .id(id)
5282            .h(self.list_item_height())
5283            .min_w_0()
5284            .w_full()
5285            .pl_3()
5286            .pr_1()
5287            .gap_1p5()
5288            .justify_between()
5289            .border_1()
5290            .border_r_2()
5291            .when(selected && self.focus_handle.is_focused(window), |el| {
5292                el.border_color(cx.theme().colors().panel_focused_border)
5293            })
5294            .bg(base_bg)
5295            .hover(|s| s.bg(hover_bg))
5296            .active(|s| s.bg(active_bg))
5297            .child(name_row)
5298            .child(
5299                div()
5300                    .id(checkbox_wrapper_id)
5301                    .flex_none()
5302                    .occlude()
5303                    .cursor_pointer()
5304                    .child(
5305                        Checkbox::new(checkbox_id, toggle_state)
5306                            .disabled(!has_write_access)
5307                            .fill()
5308                            .elevation(ElevationIndex::Surface)
5309                            .on_click({
5310                                let entry = entry.clone();
5311                                let this = cx.weak_entity();
5312                                move |_, window, cx| {
5313                                    this.update(cx, |this, cx| {
5314                                        if !has_write_access {
5315                                            return;
5316                                        }
5317                                        this.toggle_staged_for_entry(
5318                                            &GitListEntry::Directory(entry.clone()),
5319                                            window,
5320                                            cx,
5321                                        );
5322                                        cx.stop_propagation();
5323                                    })
5324                                    .ok();
5325                                }
5326                            })
5327                            .tooltip(move |_window, cx| {
5328                                let action = match stage_status {
5329                                    StageStatus::Staged => "Unstage",
5330                                    StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5331                                };
5332                                Tooltip::simple(format!("{action} folder"), cx)
5333                            }),
5334                    ),
5335            )
5336            .on_click({
5337                let key = entry.key.clone();
5338                cx.listener(move |this, _event: &ClickEvent, window, cx| {
5339                    this.selected_entry = Some(ix);
5340                    this.toggle_directory(&key, window, cx);
5341                })
5342            })
5343            .into_any_element()
5344    }
5345
5346    fn path_formatted(
5347        &self,
5348        directory: Option<String>,
5349        path_color: Color,
5350        file_name: String,
5351        label_color: Color,
5352        path_style: PathStyle,
5353        git_path_style: GitPathStyle,
5354        strikethrough: bool,
5355    ) -> Div {
5356        let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5357        let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5358
5359        let file_name = format!("{} ", file_name);
5360
5361        h_flex()
5362            .min_w_0()
5363            .overflow_hidden()
5364            .when(file_path_first, |this| this.flex_row_reverse())
5365            .child(
5366                div().flex_none().child(
5367                    self.entry_label(file_name, label_color)
5368                        .when(strikethrough, Label::strikethrough),
5369                ),
5370            )
5371            .when_some(directory, |this, dir| {
5372                let path_name = if file_name_first {
5373                    dir
5374                } else {
5375                    format!("{dir}{}", path_style.primary_separator())
5376                };
5377
5378                this.child(
5379                    self.entry_label(path_name, path_color)
5380                        .truncate_start()
5381                        .when(strikethrough, Label::strikethrough),
5382                )
5383            })
5384    }
5385
5386    fn has_write_access(&self, cx: &App) -> bool {
5387        !self.project.read(cx).is_read_only(cx)
5388    }
5389
5390    pub fn amend_pending(&self) -> bool {
5391        self.amend_pending
5392    }
5393
5394    /// Sets the pending amend state, ensuring that the original commit message
5395    /// is either saved, when `value` is `true` and there's no pending amend, or
5396    /// restored, when `value` is `false` and there's a pending amend.
5397    pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5398        if value && !self.amend_pending {
5399            let current_message = self.commit_message_buffer(cx).read(cx).text();
5400            self.original_commit_message = if current_message.trim().is_empty() {
5401                None
5402            } else {
5403                Some(current_message)
5404            };
5405        } else if !value && self.amend_pending {
5406            let message = self.original_commit_message.take().unwrap_or_default();
5407            self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5408                let start = buffer.anchor_before(0);
5409                let end = buffer.anchor_after(buffer.len());
5410                buffer.edit([(start..end, message)], None, cx);
5411            });
5412        }
5413
5414        self.amend_pending = value;
5415        self.serialize(cx);
5416        cx.notify();
5417    }
5418
5419    pub fn signoff_enabled(&self) -> bool {
5420        self.signoff_enabled
5421    }
5422
5423    pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5424        self.signoff_enabled = value;
5425        self.serialize(cx);
5426        cx.notify();
5427    }
5428
5429    pub fn toggle_signoff_enabled(
5430        &mut self,
5431        _: &Signoff,
5432        _window: &mut Window,
5433        cx: &mut Context<Self>,
5434    ) {
5435        self.set_signoff_enabled(!self.signoff_enabled, cx);
5436    }
5437
5438    pub async fn load(
5439        workspace: WeakEntity<Workspace>,
5440        mut cx: AsyncWindowContext,
5441    ) -> anyhow::Result<Entity<Self>> {
5442        let serialized_panel = match workspace
5443            .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
5444            .ok()
5445            .flatten()
5446        {
5447            Some(serialization_key) => cx
5448                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
5449                .await
5450                .context("loading git panel")
5451                .log_err()
5452                .flatten()
5453                .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5454                .transpose()
5455                .log_err()
5456                .flatten(),
5457            None => None,
5458        };
5459
5460        workspace.update_in(&mut cx, |workspace, window, cx| {
5461            let panel = GitPanel::new(workspace, window, cx);
5462
5463            if let Some(serialized_panel) = serialized_panel {
5464                panel.update(cx, |panel, cx| {
5465                    panel.width = serialized_panel.width;
5466                    panel.amend_pending = serialized_panel.amend_pending;
5467                    panel.signoff_enabled = serialized_panel.signoff_enabled;
5468                    cx.notify();
5469                })
5470            }
5471
5472            panel
5473        })
5474    }
5475
5476    fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5477        let Some(op) = self.bulk_staging.as_ref() else {
5478            return;
5479        };
5480        let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5481            return;
5482        };
5483        if let Some(entry) = self.entries.get(index)
5484            && let Some(entry) = entry.status_entry()
5485        {
5486            self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5487        }
5488        if index < anchor_index {
5489            std::mem::swap(&mut index, &mut anchor_index);
5490        }
5491        let entries = self
5492            .entries
5493            .get(anchor_index..=index)
5494            .unwrap_or_default()
5495            .iter()
5496            .filter_map(|entry| entry.status_entry().cloned())
5497            .collect::<Vec<_>>();
5498        self.change_file_stage(true, entries, cx);
5499    }
5500
5501    fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5502        let Some(repo) = self.active_repository.as_ref() else {
5503            return;
5504        };
5505        self.bulk_staging = Some(BulkStaging {
5506            repo_id: repo.read(cx).id,
5507            anchor: path,
5508        });
5509    }
5510
5511    pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5512        self.set_amend_pending(!self.amend_pending, cx);
5513        if self.amend_pending {
5514            self.load_last_commit_message(cx);
5515        }
5516    }
5517}
5518
5519impl Render for GitPanel {
5520    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5521        let project = self.project.read(cx);
5522        let has_entries = !self.entries.is_empty();
5523        let room = self
5524            .workspace
5525            .upgrade()
5526            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
5527
5528        let has_write_access = self.has_write_access(cx);
5529
5530        let has_co_authors = room.is_some_and(|room| {
5531            self.load_local_committer(cx);
5532            let room = room.read(cx);
5533            room.remote_participants()
5534                .values()
5535                .any(|remote_participant| remote_participant.can_write())
5536        });
5537
5538        v_flex()
5539            .id("git_panel")
5540            .key_context(self.dispatch_context(window, cx))
5541            .track_focus(&self.focus_handle)
5542            .when(has_write_access && !project.is_read_only(cx), |this| {
5543                this.on_action(cx.listener(Self::toggle_staged_for_selected))
5544                    .on_action(cx.listener(Self::stage_range))
5545                    .on_action(cx.listener(GitPanel::on_commit))
5546                    .on_action(cx.listener(GitPanel::on_amend))
5547                    .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5548                    .on_action(cx.listener(Self::stage_all))
5549                    .on_action(cx.listener(Self::unstage_all))
5550                    .on_action(cx.listener(Self::stage_selected))
5551                    .on_action(cx.listener(Self::unstage_selected))
5552                    .on_action(cx.listener(Self::restore_tracked_files))
5553                    .on_action(cx.listener(Self::revert_selected))
5554                    .on_action(cx.listener(Self::add_to_gitignore))
5555                    .on_action(cx.listener(Self::clean_all))
5556                    .on_action(cx.listener(Self::generate_commit_message_action))
5557                    .on_action(cx.listener(Self::stash_all))
5558                    .on_action(cx.listener(Self::stash_pop))
5559            })
5560            .on_action(cx.listener(Self::collapse_selected_entry))
5561            .on_action(cx.listener(Self::expand_selected_entry))
5562            .on_action(cx.listener(Self::select_first))
5563            .on_action(cx.listener(Self::select_next))
5564            .on_action(cx.listener(Self::select_previous))
5565            .on_action(cx.listener(Self::select_last))
5566            .on_action(cx.listener(Self::first_entry))
5567            .on_action(cx.listener(Self::next_entry))
5568            .on_action(cx.listener(Self::previous_entry))
5569            .on_action(cx.listener(Self::last_entry))
5570            .on_action(cx.listener(Self::close_panel))
5571            .on_action(cx.listener(Self::open_diff))
5572            .on_action(cx.listener(Self::open_file))
5573            .on_action(cx.listener(Self::file_history))
5574            .on_action(cx.listener(Self::focus_changes_list))
5575            .on_action(cx.listener(Self::focus_editor))
5576            .on_action(cx.listener(Self::expand_commit_editor))
5577            .when(has_write_access && has_co_authors, |git_panel| {
5578                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5579            })
5580            .on_action(cx.listener(Self::toggle_sort_by_path))
5581            .on_action(cx.listener(Self::toggle_tree_view))
5582            .size_full()
5583            .overflow_hidden()
5584            .bg(cx.theme().colors().panel_background)
5585            .child(
5586                v_flex()
5587                    .size_full()
5588                    .children(self.render_panel_header(window, cx))
5589                    .map(|this| {
5590                        if let Some(repo) = self.active_repository.clone()
5591                            && has_entries
5592                        {
5593                            this.child(self.render_entries(has_write_access, repo, window, cx))
5594                        } else {
5595                            this.child(self.render_empty_state(cx).into_any_element())
5596                        }
5597                    })
5598                    .children(self.render_footer(window, cx))
5599                    .when(self.amend_pending, |this| {
5600                        this.child(self.render_pending_amend(cx))
5601                    })
5602                    .when(!self.amend_pending, |this| {
5603                        this.children(self.render_previous_commit(window, cx))
5604                    })
5605                    .into_any_element(),
5606            )
5607            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5608                deferred(
5609                    anchored()
5610                        .position(*position)
5611                        .anchor(Corner::TopLeft)
5612                        .child(menu.clone()),
5613                )
5614                .with_priority(1)
5615            }))
5616    }
5617}
5618
5619impl Focusable for GitPanel {
5620    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5621        if self.entries.is_empty() {
5622            self.commit_editor.focus_handle(cx)
5623        } else {
5624            self.focus_handle.clone()
5625        }
5626    }
5627}
5628
5629impl EventEmitter<Event> for GitPanel {}
5630
5631impl EventEmitter<PanelEvent> for GitPanel {}
5632
5633pub(crate) struct GitPanelAddon {
5634    pub(crate) workspace: WeakEntity<Workspace>,
5635}
5636
5637impl editor::Addon for GitPanelAddon {
5638    fn to_any(&self) -> &dyn std::any::Any {
5639        self
5640    }
5641
5642    fn render_buffer_header_controls(
5643        &self,
5644        excerpt_info: &ExcerptInfo,
5645        window: &Window,
5646        cx: &App,
5647    ) -> Option<AnyElement> {
5648        let file = excerpt_info.buffer.file()?;
5649        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5650
5651        git_panel
5652            .read(cx)
5653            .render_buffer_header_controls(&git_panel, file, window, cx)
5654    }
5655}
5656
5657impl Panel for GitPanel {
5658    fn persistent_name() -> &'static str {
5659        "GitPanel"
5660    }
5661
5662    fn panel_key() -> &'static str {
5663        GIT_PANEL_KEY
5664    }
5665
5666    fn position(&self, _: &Window, cx: &App) -> DockPosition {
5667        GitPanelSettings::get_global(cx).dock
5668    }
5669
5670    fn position_is_valid(&self, position: DockPosition) -> bool {
5671        matches!(position, DockPosition::Left | DockPosition::Right)
5672    }
5673
5674    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5675        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5676            settings.git_panel.get_or_insert_default().dock = Some(position.into())
5677        });
5678    }
5679
5680    fn size(&self, _: &Window, cx: &App) -> Pixels {
5681        self.width
5682            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
5683    }
5684
5685    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
5686        self.width = size;
5687        self.serialize(cx);
5688        cx.notify();
5689    }
5690
5691    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5692        Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5693    }
5694
5695    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5696        Some("Git Panel")
5697    }
5698
5699    fn toggle_action(&self) -> Box<dyn Action> {
5700        Box::new(ToggleFocus)
5701    }
5702
5703    fn activation_priority(&self) -> u32 {
5704        2
5705    }
5706}
5707
5708impl PanelHeader for GitPanel {}
5709
5710pub fn panel_editor_container(_window: &mut Window, cx: &mut App) -> Div {
5711    v_flex()
5712        .size_full()
5713        .gap(px(8.))
5714        .p_2()
5715        .bg(cx.theme().colors().editor_background)
5716}
5717
5718pub(crate) fn panel_editor_style(monospace: bool, window: &Window, cx: &App) -> EditorStyle {
5719    let settings = ThemeSettings::get_global(cx);
5720
5721    let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
5722
5723    let (font_family, font_fallbacks, font_features, font_weight, line_height) = if monospace {
5724        (
5725            settings.buffer_font.family.clone(),
5726            settings.buffer_font.fallbacks.clone(),
5727            settings.buffer_font.features.clone(),
5728            settings.buffer_font.weight,
5729            font_size * settings.buffer_line_height.value(),
5730        )
5731    } else {
5732        (
5733            settings.ui_font.family.clone(),
5734            settings.ui_font.fallbacks.clone(),
5735            settings.ui_font.features.clone(),
5736            settings.ui_font.weight,
5737            window.line_height(),
5738        )
5739    };
5740
5741    EditorStyle {
5742        background: cx.theme().colors().editor_background,
5743        local_player: cx.theme().players().local(),
5744        text: TextStyle {
5745            color: cx.theme().colors().text,
5746            font_family,
5747            font_fallbacks,
5748            font_features,
5749            font_size: TextSize::Small.rems(cx).into(),
5750            font_weight,
5751            line_height: line_height.into(),
5752            ..Default::default()
5753        },
5754        syntax: cx.theme().syntax().clone(),
5755        ..Default::default()
5756    }
5757}
5758
5759struct GitPanelMessageTooltip {
5760    commit_tooltip: Option<Entity<CommitTooltip>>,
5761}
5762
5763impl GitPanelMessageTooltip {
5764    fn new(
5765        git_panel: Entity<GitPanel>,
5766        sha: SharedString,
5767        repository: Entity<Repository>,
5768        window: &mut Window,
5769        cx: &mut App,
5770    ) -> Entity<Self> {
5771        let remote_url = repository.read(cx).default_remote_url();
5772        cx.new(|cx| {
5773            cx.spawn_in(window, async move |this, cx| {
5774                let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5775                    (
5776                        git_panel.load_commit_details(sha.to_string(), cx),
5777                        git_panel.workspace.clone(),
5778                    )
5779                });
5780                let details = details.await?;
5781                let provider_registry = cx
5782                    .update(|_, app| GitHostingProviderRegistry::default_global(app))
5783                    .ok();
5784
5785                let commit_details = crate::commit_tooltip::CommitDetails {
5786                    sha: details.sha.clone(),
5787                    author_name: details.author_name.clone(),
5788                    author_email: details.author_email.clone(),
5789                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5790                    message: Some(ParsedCommitMessage::parse(
5791                        details.sha.to_string(),
5792                        details.message.to_string(),
5793                        remote_url.as_deref(),
5794                        provider_registry,
5795                    )),
5796                };
5797
5798                this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5799                    this.commit_tooltip = Some(cx.new(move |cx| {
5800                        CommitTooltip::new(commit_details, repository, workspace, cx)
5801                    }));
5802                    cx.notify();
5803                })
5804            })
5805            .detach();
5806
5807            Self {
5808                commit_tooltip: None,
5809            }
5810        })
5811    }
5812}
5813
5814impl Render for GitPanelMessageTooltip {
5815    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5816        if let Some(commit_tooltip) = &self.commit_tooltip {
5817            commit_tooltip.clone().into_any_element()
5818        } else {
5819            gpui::Empty.into_any_element()
5820        }
5821    }
5822}
5823
5824#[derive(IntoElement, RegisterComponent)]
5825pub struct PanelRepoFooter {
5826    active_repository: SharedString,
5827    branch: Option<Branch>,
5828    head_commit: Option<CommitDetails>,
5829
5830    // Getting a GitPanel in previews will be difficult.
5831    //
5832    // For now just take an option here, and we won't bind handlers to buttons in previews.
5833    git_panel: Option<Entity<GitPanel>>,
5834}
5835
5836impl PanelRepoFooter {
5837    pub fn new(
5838        active_repository: SharedString,
5839        branch: Option<Branch>,
5840        head_commit: Option<CommitDetails>,
5841        git_panel: Option<Entity<GitPanel>>,
5842    ) -> Self {
5843        Self {
5844            active_repository,
5845            branch,
5846            head_commit,
5847            git_panel,
5848        }
5849    }
5850
5851    pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5852        Self {
5853            active_repository,
5854            branch,
5855            head_commit: None,
5856            git_panel: None,
5857        }
5858    }
5859}
5860
5861impl RenderOnce for PanelRepoFooter {
5862    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5863        let project = self
5864            .git_panel
5865            .as_ref()
5866            .map(|panel| panel.read(cx).project.clone());
5867
5868        let (workspace, repo) = self
5869            .git_panel
5870            .as_ref()
5871            .map(|panel| {
5872                let panel = panel.read(cx);
5873                (panel.workspace.clone(), panel.active_repository.clone())
5874            })
5875            .unzip();
5876
5877        let single_repo = project
5878            .as_ref()
5879            .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5880            .unwrap_or(true);
5881
5882        const MAX_BRANCH_LEN: usize = 16;
5883        const MAX_REPO_LEN: usize = 16;
5884        const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
5885        const MAX_SHORT_SHA_LEN: usize = 8;
5886        let branch_name = self
5887            .branch
5888            .as_ref()
5889            .map(|branch| branch.name().to_owned())
5890            .or_else(|| {
5891                self.head_commit.as_ref().map(|commit| {
5892                    commit
5893                        .sha
5894                        .chars()
5895                        .take(MAX_SHORT_SHA_LEN)
5896                        .collect::<String>()
5897                })
5898            })
5899            .unwrap_or_else(|| " (no branch)".to_owned());
5900        let show_separator = self.branch.is_some() || self.head_commit.is_some();
5901
5902        let active_repo_name = self.active_repository.clone();
5903
5904        let branch_actual_len = branch_name.len();
5905        let repo_actual_len = active_repo_name.len();
5906
5907        // ideally, show the whole branch and repo names but
5908        // when we can't, use a budget to allocate space between the two
5909        let (repo_display_len, branch_display_len) =
5910            if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
5911                (repo_actual_len, branch_actual_len)
5912            } else if branch_actual_len <= MAX_BRANCH_LEN {
5913                let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
5914                (repo_space, branch_actual_len)
5915            } else if repo_actual_len <= MAX_REPO_LEN {
5916                let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
5917                (repo_actual_len, branch_space)
5918            } else {
5919                (MAX_REPO_LEN, MAX_BRANCH_LEN)
5920            };
5921
5922        let truncated_repo_name = if repo_actual_len <= repo_display_len {
5923            active_repo_name.to_string()
5924        } else {
5925            util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
5926        };
5927
5928        let truncated_branch_name = if branch_actual_len <= branch_display_len {
5929            branch_name
5930        } else {
5931            util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
5932        };
5933
5934        let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
5935            .size(ButtonSize::None)
5936            .label_size(LabelSize::Small);
5937
5938        let repo_selector = PopoverMenu::new("repository-switcher")
5939            .menu({
5940                let project = project;
5941                move |window, cx| {
5942                    let project = project.clone()?;
5943                    Some(cx.new(|cx| RepositorySelector::new(project, rems(20.), window, cx)))
5944                }
5945            })
5946            .trigger_with_tooltip(
5947                repo_selector_trigger
5948                    .when(single_repo, |this| this.disabled(true).color(Color::Muted))
5949                    .truncate(true),
5950                move |_, cx| {
5951                    if single_repo {
5952                        cx.new(|_| Empty).into()
5953                    } else {
5954                        Tooltip::simple("Switch Active Repository", cx)
5955                    }
5956                },
5957            )
5958            .anchor(Corner::BottomLeft)
5959            .offset(gpui::Point {
5960                x: px(0.0),
5961                y: px(-2.0),
5962            })
5963            .into_any_element();
5964
5965        let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
5966            .size(ButtonSize::None)
5967            .label_size(LabelSize::Small)
5968            .truncate(true)
5969            .on_click(|_, window, cx| {
5970                window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
5971            });
5972
5973        let branch_selector = PopoverMenu::new("popover-button")
5974            .menu(move |window, cx| {
5975                let workspace = workspace.clone()?;
5976                let repo = repo.clone().flatten();
5977                Some(branch_picker::popover(workspace, false, repo, window, cx))
5978            })
5979            .trigger_with_tooltip(
5980                branch_selector_button,
5981                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
5982            )
5983            .anchor(Corner::BottomLeft)
5984            .offset(gpui::Point {
5985                x: px(0.0),
5986                y: px(-2.0),
5987            });
5988
5989        h_flex()
5990            .h(px(36.))
5991            .w_full()
5992            .px_2()
5993            .justify_between()
5994            .gap_1()
5995            .child(
5996                h_flex()
5997                    .flex_1()
5998                    .overflow_hidden()
5999                    .gap_px()
6000                    .child(
6001                        Icon::new(IconName::GitBranchAlt)
6002                            .size(IconSize::Small)
6003                            .color(if single_repo {
6004                                Color::Disabled
6005                            } else {
6006                                Color::Muted
6007                            }),
6008                    )
6009                    .child(repo_selector)
6010                    .when(show_separator, |this| {
6011                        this.child(
6012                            div()
6013                                .text_sm()
6014                                .text_color(cx.theme().colors().icon_muted.opacity(0.5))
6015                                .child("/"),
6016                        )
6017                    })
6018                    .child(branch_selector),
6019            )
6020            .children(if let Some(git_panel) = self.git_panel {
6021                git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
6022            } else {
6023                None
6024            })
6025    }
6026}
6027
6028impl Component for PanelRepoFooter {
6029    fn scope() -> ComponentScope {
6030        ComponentScope::VersionControl
6031    }
6032
6033    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
6034        let unknown_upstream = None;
6035        let no_remote_upstream = Some(UpstreamTracking::Gone);
6036        let ahead_of_upstream = Some(
6037            UpstreamTrackingStatus {
6038                ahead: 2,
6039                behind: 0,
6040            }
6041            .into(),
6042        );
6043        let behind_upstream = Some(
6044            UpstreamTrackingStatus {
6045                ahead: 0,
6046                behind: 2,
6047            }
6048            .into(),
6049        );
6050        let ahead_and_behind_upstream = Some(
6051            UpstreamTrackingStatus {
6052                ahead: 3,
6053                behind: 1,
6054            }
6055            .into(),
6056        );
6057
6058        let not_ahead_or_behind_upstream = Some(
6059            UpstreamTrackingStatus {
6060                ahead: 0,
6061                behind: 0,
6062            }
6063            .into(),
6064        );
6065
6066        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
6067            Branch {
6068                is_head: true,
6069                ref_name: "some-branch".into(),
6070                upstream: upstream.map(|tracking| Upstream {
6071                    ref_name: "origin/some-branch".into(),
6072                    tracking,
6073                }),
6074                most_recent_commit: Some(CommitSummary {
6075                    sha: "abc123".into(),
6076                    subject: "Modify stuff".into(),
6077                    commit_timestamp: 1710932954,
6078                    author_name: "John Doe".into(),
6079                    has_parent: true,
6080                }),
6081            }
6082        }
6083
6084        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
6085            Branch {
6086                is_head: true,
6087                ref_name: branch_name.to_string().into(),
6088                upstream: upstream.map(|tracking| Upstream {
6089                    ref_name: format!("zed/{}", branch_name).into(),
6090                    tracking,
6091                }),
6092                most_recent_commit: Some(CommitSummary {
6093                    sha: "abc123".into(),
6094                    subject: "Modify stuff".into(),
6095                    commit_timestamp: 1710932954,
6096                    author_name: "John Doe".into(),
6097                    has_parent: true,
6098                }),
6099            }
6100        }
6101
6102        fn active_repository(id: usize) -> SharedString {
6103            format!("repo-{}", id).into()
6104        }
6105
6106        let example_width = px(340.);
6107        Some(
6108            v_flex()
6109                .gap_6()
6110                .w_full()
6111                .flex_none()
6112                .children(vec![
6113                    example_group_with_title(
6114                        "Action Button States",
6115                        vec![
6116                            single_example(
6117                                "No Branch",
6118                                div()
6119                                    .w(example_width)
6120                                    .overflow_hidden()
6121                                    .child(PanelRepoFooter::new_preview(active_repository(1), None))
6122                                    .into_any_element(),
6123                            ),
6124                            single_example(
6125                                "Remote status unknown",
6126                                div()
6127                                    .w(example_width)
6128                                    .overflow_hidden()
6129                                    .child(PanelRepoFooter::new_preview(
6130                                        active_repository(2),
6131                                        Some(branch(unknown_upstream)),
6132                                    ))
6133                                    .into_any_element(),
6134                            ),
6135                            single_example(
6136                                "No Remote Upstream",
6137                                div()
6138                                    .w(example_width)
6139                                    .overflow_hidden()
6140                                    .child(PanelRepoFooter::new_preview(
6141                                        active_repository(3),
6142                                        Some(branch(no_remote_upstream)),
6143                                    ))
6144                                    .into_any_element(),
6145                            ),
6146                            single_example(
6147                                "Not Ahead or Behind",
6148                                div()
6149                                    .w(example_width)
6150                                    .overflow_hidden()
6151                                    .child(PanelRepoFooter::new_preview(
6152                                        active_repository(4),
6153                                        Some(branch(not_ahead_or_behind_upstream)),
6154                                    ))
6155                                    .into_any_element(),
6156                            ),
6157                            single_example(
6158                                "Behind remote",
6159                                div()
6160                                    .w(example_width)
6161                                    .overflow_hidden()
6162                                    .child(PanelRepoFooter::new_preview(
6163                                        active_repository(5),
6164                                        Some(branch(behind_upstream)),
6165                                    ))
6166                                    .into_any_element(),
6167                            ),
6168                            single_example(
6169                                "Ahead of remote",
6170                                div()
6171                                    .w(example_width)
6172                                    .overflow_hidden()
6173                                    .child(PanelRepoFooter::new_preview(
6174                                        active_repository(6),
6175                                        Some(branch(ahead_of_upstream)),
6176                                    ))
6177                                    .into_any_element(),
6178                            ),
6179                            single_example(
6180                                "Ahead and behind remote",
6181                                div()
6182                                    .w(example_width)
6183                                    .overflow_hidden()
6184                                    .child(PanelRepoFooter::new_preview(
6185                                        active_repository(7),
6186                                        Some(branch(ahead_and_behind_upstream)),
6187                                    ))
6188                                    .into_any_element(),
6189                            ),
6190                        ],
6191                    )
6192                    .grow()
6193                    .vertical(),
6194                ])
6195                .children(vec![
6196                    example_group_with_title(
6197                        "Labels",
6198                        vec![
6199                            single_example(
6200                                "Short Branch & Repo",
6201                                div()
6202                                    .w(example_width)
6203                                    .overflow_hidden()
6204                                    .child(PanelRepoFooter::new_preview(
6205                                        SharedString::from("zed"),
6206                                        Some(custom("main", behind_upstream)),
6207                                    ))
6208                                    .into_any_element(),
6209                            ),
6210                            single_example(
6211                                "Long Branch",
6212                                div()
6213                                    .w(example_width)
6214                                    .overflow_hidden()
6215                                    .child(PanelRepoFooter::new_preview(
6216                                        SharedString::from("zed"),
6217                                        Some(custom(
6218                                            "redesign-and-update-git-ui-list-entry-style",
6219                                            behind_upstream,
6220                                        )),
6221                                    ))
6222                                    .into_any_element(),
6223                            ),
6224                            single_example(
6225                                "Long Repo",
6226                                div()
6227                                    .w(example_width)
6228                                    .overflow_hidden()
6229                                    .child(PanelRepoFooter::new_preview(
6230                                        SharedString::from("zed-industries-community-examples"),
6231                                        Some(custom("gpui", ahead_of_upstream)),
6232                                    ))
6233                                    .into_any_element(),
6234                            ),
6235                            single_example(
6236                                "Long Repo & Branch",
6237                                div()
6238                                    .w(example_width)
6239                                    .overflow_hidden()
6240                                    .child(PanelRepoFooter::new_preview(
6241                                        SharedString::from("zed-industries-community-examples"),
6242                                        Some(custom(
6243                                            "redesign-and-update-git-ui-list-entry-style",
6244                                            behind_upstream,
6245                                        )),
6246                                    ))
6247                                    .into_any_element(),
6248                            ),
6249                            single_example(
6250                                "Uppercase Repo",
6251                                div()
6252                                    .w(example_width)
6253                                    .overflow_hidden()
6254                                    .child(PanelRepoFooter::new_preview(
6255                                        SharedString::from("LICENSES"),
6256                                        Some(custom("main", ahead_of_upstream)),
6257                                    ))
6258                                    .into_any_element(),
6259                            ),
6260                            single_example(
6261                                "Uppercase Branch",
6262                                div()
6263                                    .w(example_width)
6264                                    .overflow_hidden()
6265                                    .child(PanelRepoFooter::new_preview(
6266                                        SharedString::from("zed"),
6267                                        Some(custom("update-README", behind_upstream)),
6268                                    ))
6269                                    .into_any_element(),
6270                            ),
6271                        ],
6272                    )
6273                    .grow()
6274                    .vertical(),
6275                ])
6276                .into_any_element(),
6277        )
6278    }
6279}
6280
6281fn open_output(
6282    operation: impl Into<SharedString>,
6283    workspace: &mut Workspace,
6284    output: &str,
6285    window: &mut Window,
6286    cx: &mut Context<Workspace>,
6287) {
6288    let operation = operation.into();
6289    let buffer = cx.new(|cx| Buffer::local(output, cx));
6290    buffer.update(cx, |buffer, cx| {
6291        buffer.set_capability(language::Capability::ReadOnly, cx);
6292    });
6293    let editor = cx.new(|cx| {
6294        let mut editor = Editor::for_buffer(buffer, None, window, cx);
6295        editor.buffer().update(cx, |buffer, cx| {
6296            buffer.set_title(format!("Output from git {operation}"), cx);
6297        });
6298        editor.set_read_only(true);
6299        editor
6300    });
6301
6302    workspace.add_item_to_center(Box::new(editor), window, cx);
6303}
6304
6305pub(crate) fn show_error_toast(
6306    workspace: Entity<Workspace>,
6307    action: impl Into<SharedString>,
6308    e: anyhow::Error,
6309    cx: &mut App,
6310) {
6311    let action = action.into();
6312    let message = e.to_string().trim().to_string();
6313    if message
6314        .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6315        .next()
6316        .is_some()
6317    { // Hide the cancelled by user message
6318    } else {
6319        workspace.update(cx, |workspace, cx| {
6320            let workspace_weak = cx.weak_entity();
6321            let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6322                this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
6323                    .action("View Log", move |window, cx| {
6324                        let message = message.clone();
6325                        let action = action.clone();
6326                        workspace_weak
6327                            .update(cx, move |workspace, cx| {
6328                                open_output(action, workspace, &message, window, cx)
6329                            })
6330                            .ok();
6331                    })
6332            });
6333            workspace.toggle_status_toast(toast, cx)
6334        });
6335    }
6336}
6337
6338#[cfg(test)]
6339mod tests {
6340    use git::{
6341        repository::repo_path,
6342        status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6343    };
6344    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
6345    use indoc::indoc;
6346    use project::FakeFs;
6347    use serde_json::json;
6348    use settings::SettingsStore;
6349    use theme::LoadThemes;
6350    use util::path;
6351    use util::rel_path::rel_path;
6352
6353    use workspace::MultiWorkspace;
6354
6355    use super::*;
6356
6357    fn init_test(cx: &mut gpui::TestAppContext) {
6358        zlog::init_test();
6359
6360        cx.update(|cx| {
6361            let settings_store = SettingsStore::test(cx);
6362            cx.set_global(settings_store);
6363            theme::init(LoadThemes::JustBase, cx);
6364            editor::init(cx);
6365            crate::init(cx);
6366        });
6367    }
6368
6369    #[gpui::test]
6370    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6371        init_test(cx);
6372        let fs = FakeFs::new(cx.background_executor.clone());
6373        fs.insert_tree(
6374            "/root",
6375            json!({
6376                "zed": {
6377                    ".git": {},
6378                    "crates": {
6379                        "gpui": {
6380                            "gpui.rs": "fn main() {}"
6381                        },
6382                        "util": {
6383                            "util.rs": "fn do_it() {}"
6384                        }
6385                    }
6386                },
6387            }),
6388        )
6389        .await;
6390
6391        fs.set_status_for_repo(
6392            Path::new(path!("/root/zed/.git")),
6393            &[
6394                ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6395                ("crates/util/util.rs", StatusCode::Modified.worktree()),
6396            ],
6397        );
6398
6399        let project =
6400            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6401        let window_handle =
6402            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6403        let workspace = window_handle
6404            .read_with(cx, |mw, _| mw.workspace().clone())
6405            .unwrap();
6406        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6407
6408        cx.read(|cx| {
6409            project
6410                .read(cx)
6411                .worktrees(cx)
6412                .next()
6413                .unwrap()
6414                .read(cx)
6415                .as_local()
6416                .unwrap()
6417                .scan_complete()
6418        })
6419        .await;
6420
6421        cx.executor().run_until_parked();
6422
6423        let panel = workspace.update_in(cx, GitPanel::new);
6424
6425        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6426            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6427        });
6428        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6429        handle.await;
6430
6431        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6432        pretty_assertions::assert_eq!(
6433            entries,
6434            [
6435                GitListEntry::Header(GitHeaderEntry {
6436                    header: Section::Tracked
6437                }),
6438                GitListEntry::Status(GitStatusEntry {
6439                    repo_path: repo_path("crates/gpui/gpui.rs"),
6440                    status: StatusCode::Modified.worktree(),
6441                    staging: StageStatus::Unstaged,
6442                }),
6443                GitListEntry::Status(GitStatusEntry {
6444                    repo_path: repo_path("crates/util/util.rs"),
6445                    status: StatusCode::Modified.worktree(),
6446                    staging: StageStatus::Unstaged,
6447                },),
6448            ],
6449        );
6450
6451        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6452            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6453        });
6454        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6455        handle.await;
6456        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6457        pretty_assertions::assert_eq!(
6458            entries,
6459            [
6460                GitListEntry::Header(GitHeaderEntry {
6461                    header: Section::Tracked
6462                }),
6463                GitListEntry::Status(GitStatusEntry {
6464                    repo_path: repo_path("crates/gpui/gpui.rs"),
6465                    status: StatusCode::Modified.worktree(),
6466                    staging: StageStatus::Unstaged,
6467                }),
6468                GitListEntry::Status(GitStatusEntry {
6469                    repo_path: repo_path("crates/util/util.rs"),
6470                    status: StatusCode::Modified.worktree(),
6471                    staging: StageStatus::Unstaged,
6472                },),
6473            ],
6474        );
6475    }
6476
6477    #[gpui::test]
6478    async fn test_bulk_staging(cx: &mut TestAppContext) {
6479        use GitListEntry::*;
6480
6481        init_test(cx);
6482        let fs = FakeFs::new(cx.background_executor.clone());
6483        fs.insert_tree(
6484            "/root",
6485            json!({
6486                "project": {
6487                    ".git": {},
6488                    "src": {
6489                        "main.rs": "fn main() {}",
6490                        "lib.rs": "pub fn hello() {}",
6491                        "utils.rs": "pub fn util() {}"
6492                    },
6493                    "tests": {
6494                        "test.rs": "fn test() {}"
6495                    },
6496                    "new_file.txt": "new content",
6497                    "another_new.rs": "// new file",
6498                    "conflict.txt": "conflicted content"
6499                }
6500            }),
6501        )
6502        .await;
6503
6504        fs.set_status_for_repo(
6505            Path::new(path!("/root/project/.git")),
6506            &[
6507                ("src/main.rs", StatusCode::Modified.worktree()),
6508                ("src/lib.rs", StatusCode::Modified.worktree()),
6509                ("tests/test.rs", StatusCode::Modified.worktree()),
6510                ("new_file.txt", FileStatus::Untracked),
6511                ("another_new.rs", FileStatus::Untracked),
6512                ("src/utils.rs", FileStatus::Untracked),
6513                (
6514                    "conflict.txt",
6515                    UnmergedStatus {
6516                        first_head: UnmergedStatusCode::Updated,
6517                        second_head: UnmergedStatusCode::Updated,
6518                    }
6519                    .into(),
6520                ),
6521            ],
6522        );
6523
6524        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6525        let window_handle =
6526            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6527        let workspace = window_handle
6528            .read_with(cx, |mw, _| mw.workspace().clone())
6529            .unwrap();
6530        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6531
6532        cx.read(|cx| {
6533            project
6534                .read(cx)
6535                .worktrees(cx)
6536                .next()
6537                .unwrap()
6538                .read(cx)
6539                .as_local()
6540                .unwrap()
6541                .scan_complete()
6542        })
6543        .await;
6544
6545        cx.executor().run_until_parked();
6546
6547        let panel = workspace.update_in(cx, GitPanel::new);
6548
6549        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6550            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6551        });
6552        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6553        handle.await;
6554
6555        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6556        #[rustfmt::skip]
6557        pretty_assertions::assert_matches!(
6558            entries.as_slice(),
6559            &[
6560                Header(GitHeaderEntry { header: Section::Conflict }),
6561                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6562                Header(GitHeaderEntry { header: Section::Tracked }),
6563                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6564                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6565                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6566                Header(GitHeaderEntry { header: Section::New }),
6567                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6568                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6569                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6570            ],
6571        );
6572
6573        let second_status_entry = entries[3].clone();
6574        panel.update_in(cx, |panel, window, cx| {
6575            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6576        });
6577
6578        panel.update_in(cx, |panel, window, cx| {
6579            panel.selected_entry = Some(7);
6580            panel.stage_range(&git::StageRange, window, cx);
6581        });
6582
6583        cx.read(|cx| {
6584            project
6585                .read(cx)
6586                .worktrees(cx)
6587                .next()
6588                .unwrap()
6589                .read(cx)
6590                .as_local()
6591                .unwrap()
6592                .scan_complete()
6593        })
6594        .await;
6595
6596        cx.executor().run_until_parked();
6597
6598        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6599            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6600        });
6601        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6602        handle.await;
6603
6604        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6605        #[rustfmt::skip]
6606        pretty_assertions::assert_matches!(
6607            entries.as_slice(),
6608            &[
6609                Header(GitHeaderEntry { header: Section::Conflict }),
6610                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6611                Header(GitHeaderEntry { header: Section::Tracked }),
6612                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6613                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6614                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6615                Header(GitHeaderEntry { header: Section::New }),
6616                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6617                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6618                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6619            ],
6620        );
6621
6622        let third_status_entry = entries[4].clone();
6623        panel.update_in(cx, |panel, window, cx| {
6624            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6625        });
6626
6627        panel.update_in(cx, |panel, window, cx| {
6628            panel.selected_entry = Some(9);
6629            panel.stage_range(&git::StageRange, window, cx);
6630        });
6631
6632        cx.read(|cx| {
6633            project
6634                .read(cx)
6635                .worktrees(cx)
6636                .next()
6637                .unwrap()
6638                .read(cx)
6639                .as_local()
6640                .unwrap()
6641                .scan_complete()
6642        })
6643        .await;
6644
6645        cx.executor().run_until_parked();
6646
6647        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6648            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6649        });
6650        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6651        handle.await;
6652
6653        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6654        #[rustfmt::skip]
6655        pretty_assertions::assert_matches!(
6656            entries.as_slice(),
6657            &[
6658                Header(GitHeaderEntry { header: Section::Conflict }),
6659                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6660                Header(GitHeaderEntry { header: Section::Tracked }),
6661                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6662                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6663                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6664                Header(GitHeaderEntry { header: Section::New }),
6665                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6666                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6667                Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6668            ],
6669        );
6670    }
6671
6672    #[gpui::test]
6673    async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6674        use GitListEntry::*;
6675
6676        init_test(cx);
6677        let fs = FakeFs::new(cx.background_executor.clone());
6678        fs.insert_tree(
6679            "/root",
6680            json!({
6681                "project": {
6682                    ".git": {},
6683                    "src": {
6684                        "main.rs": "fn main() {}",
6685                        "lib.rs": "pub fn hello() {}",
6686                        "utils.rs": "pub fn util() {}"
6687                    },
6688                    "tests": {
6689                        "test.rs": "fn test() {}"
6690                    },
6691                    "new_file.txt": "new content",
6692                    "another_new.rs": "// new file",
6693                    "conflict.txt": "conflicted content"
6694                }
6695            }),
6696        )
6697        .await;
6698
6699        fs.set_status_for_repo(
6700            Path::new(path!("/root/project/.git")),
6701            &[
6702                ("src/main.rs", StatusCode::Modified.worktree()),
6703                ("src/lib.rs", StatusCode::Modified.worktree()),
6704                ("tests/test.rs", StatusCode::Modified.worktree()),
6705                ("new_file.txt", FileStatus::Untracked),
6706                ("another_new.rs", FileStatus::Untracked),
6707                ("src/utils.rs", FileStatus::Untracked),
6708                (
6709                    "conflict.txt",
6710                    UnmergedStatus {
6711                        first_head: UnmergedStatusCode::Updated,
6712                        second_head: UnmergedStatusCode::Updated,
6713                    }
6714                    .into(),
6715                ),
6716            ],
6717        );
6718
6719        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6720        let window_handle =
6721            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6722        let workspace = window_handle
6723            .read_with(cx, |mw, _| mw.workspace().clone())
6724            .unwrap();
6725        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6726
6727        cx.read(|cx| {
6728            project
6729                .read(cx)
6730                .worktrees(cx)
6731                .next()
6732                .unwrap()
6733                .read(cx)
6734                .as_local()
6735                .unwrap()
6736                .scan_complete()
6737        })
6738        .await;
6739
6740        cx.executor().run_until_parked();
6741
6742        let panel = workspace.update_in(cx, GitPanel::new);
6743
6744        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6745            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6746        });
6747        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6748        handle.await;
6749
6750        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6751        #[rustfmt::skip]
6752        pretty_assertions::assert_matches!(
6753            entries.as_slice(),
6754            &[
6755                Header(GitHeaderEntry { header: Section::Conflict }),
6756                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6757                Header(GitHeaderEntry { header: Section::Tracked }),
6758                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6759                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6760                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6761                Header(GitHeaderEntry { header: Section::New }),
6762                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6763                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6764                Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6765            ],
6766        );
6767
6768        assert_entry_paths(
6769            &entries,
6770            &[
6771                None,
6772                Some("conflict.txt"),
6773                None,
6774                Some("src/lib.rs"),
6775                Some("src/main.rs"),
6776                Some("tests/test.rs"),
6777                None,
6778                Some("another_new.rs"),
6779                Some("new_file.txt"),
6780                Some("src/utils.rs"),
6781            ],
6782        );
6783
6784        let second_status_entry = entries[3].clone();
6785        panel.update_in(cx, |panel, window, cx| {
6786            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6787        });
6788
6789        cx.update(|_window, cx| {
6790            SettingsStore::update_global(cx, |store, cx| {
6791                store.update_user_settings(cx, |settings| {
6792                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6793                })
6794            });
6795        });
6796
6797        panel.update_in(cx, |panel, window, cx| {
6798            panel.selected_entry = Some(7);
6799            panel.stage_range(&git::StageRange, window, cx);
6800        });
6801
6802        cx.read(|cx| {
6803            project
6804                .read(cx)
6805                .worktrees(cx)
6806                .next()
6807                .unwrap()
6808                .read(cx)
6809                .as_local()
6810                .unwrap()
6811                .scan_complete()
6812        })
6813        .await;
6814
6815        cx.executor().run_until_parked();
6816
6817        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6818            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6819        });
6820        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6821        handle.await;
6822
6823        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6824        #[rustfmt::skip]
6825        pretty_assertions::assert_matches!(
6826            entries.as_slice(),
6827            &[
6828                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6829                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6830                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6831                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6832                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6833                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6834                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6835            ],
6836        );
6837
6838        assert_entry_paths(
6839            &entries,
6840            &[
6841                Some("another_new.rs"),
6842                Some("conflict.txt"),
6843                Some("new_file.txt"),
6844                Some("src/lib.rs"),
6845                Some("src/main.rs"),
6846                Some("src/utils.rs"),
6847                Some("tests/test.rs"),
6848            ],
6849        );
6850
6851        let third_status_entry = entries[4].clone();
6852        panel.update_in(cx, |panel, window, cx| {
6853            panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6854        });
6855
6856        panel.update_in(cx, |panel, window, cx| {
6857            panel.selected_entry = Some(9);
6858            panel.stage_range(&git::StageRange, window, cx);
6859        });
6860
6861        cx.read(|cx| {
6862            project
6863                .read(cx)
6864                .worktrees(cx)
6865                .next()
6866                .unwrap()
6867                .read(cx)
6868                .as_local()
6869                .unwrap()
6870                .scan_complete()
6871        })
6872        .await;
6873
6874        cx.executor().run_until_parked();
6875
6876        let handle = cx.update_window_entity(&panel, |panel, _, _| {
6877            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6878        });
6879        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6880        handle.await;
6881
6882        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6883        #[rustfmt::skip]
6884        pretty_assertions::assert_matches!(
6885            entries.as_slice(),
6886            &[
6887                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6888                Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6889                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6890                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6891                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6892                Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6893                Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6894            ],
6895        );
6896
6897        assert_entry_paths(
6898            &entries,
6899            &[
6900                Some("another_new.rs"),
6901                Some("conflict.txt"),
6902                Some("new_file.txt"),
6903                Some("src/lib.rs"),
6904                Some("src/main.rs"),
6905                Some("src/utils.rs"),
6906                Some("tests/test.rs"),
6907            ],
6908        );
6909    }
6910
6911    #[gpui::test]
6912    async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
6913        init_test(cx);
6914        let fs = FakeFs::new(cx.background_executor.clone());
6915        fs.insert_tree(
6916            "/root",
6917            json!({
6918                "project": {
6919                    ".git": {},
6920                    "src": {
6921                        "main.rs": "fn main() {}"
6922                    }
6923                }
6924            }),
6925        )
6926        .await;
6927
6928        fs.set_status_for_repo(
6929            Path::new(path!("/root/project/.git")),
6930            &[("src/main.rs", StatusCode::Modified.worktree())],
6931        );
6932
6933        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6934        let window_handle =
6935            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6936        let workspace = window_handle
6937            .read_with(cx, |mw, _| mw.workspace().clone())
6938            .unwrap();
6939        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6940
6941        let panel = workspace.update_in(cx, GitPanel::new);
6942
6943        // Test: User has commit message, enables amend (saves message), then disables (restores message)
6944        panel.update(cx, |panel, cx| {
6945            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6946                let start = buffer.anchor_before(0);
6947                let end = buffer.anchor_after(buffer.len());
6948                buffer.edit([(start..end, "Initial commit message")], None, cx);
6949            });
6950
6951            panel.set_amend_pending(true, cx);
6952            assert!(panel.original_commit_message.is_some());
6953
6954            panel.set_amend_pending(false, cx);
6955            let current_message = panel.commit_message_buffer(cx).read(cx).text();
6956            assert_eq!(current_message, "Initial commit message");
6957            assert!(panel.original_commit_message.is_none());
6958        });
6959
6960        // Test: User has empty commit message, enables amend, then disables (clears message)
6961        panel.update(cx, |panel, cx| {
6962            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6963                let start = buffer.anchor_before(0);
6964                let end = buffer.anchor_after(buffer.len());
6965                buffer.edit([(start..end, "")], None, cx);
6966            });
6967
6968            panel.set_amend_pending(true, cx);
6969            assert!(panel.original_commit_message.is_none());
6970
6971            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6972                let start = buffer.anchor_before(0);
6973                let end = buffer.anchor_after(buffer.len());
6974                buffer.edit([(start..end, "Previous commit message")], None, cx);
6975            });
6976
6977            panel.set_amend_pending(false, cx);
6978            let current_message = panel.commit_message_buffer(cx).read(cx).text();
6979            assert_eq!(current_message, "");
6980        });
6981    }
6982
6983    #[gpui::test]
6984    async fn test_amend(cx: &mut TestAppContext) {
6985        init_test(cx);
6986        let fs = FakeFs::new(cx.background_executor.clone());
6987        fs.insert_tree(
6988            "/root",
6989            json!({
6990                "project": {
6991                    ".git": {},
6992                    "src": {
6993                        "main.rs": "fn main() {}"
6994                    }
6995                }
6996            }),
6997        )
6998        .await;
6999
7000        fs.set_status_for_repo(
7001            Path::new(path!("/root/project/.git")),
7002            &[("src/main.rs", StatusCode::Modified.worktree())],
7003        );
7004
7005        let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7006        let window_handle =
7007            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7008        let workspace = window_handle
7009            .read_with(cx, |mw, _| mw.workspace().clone())
7010            .unwrap();
7011        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7012
7013        // Wait for the project scanning to finish so that `head_commit(cx)` is
7014        // actually set, otherwise no head commit would be available from which
7015        // to fetch the latest commit message from.
7016        cx.executor().run_until_parked();
7017
7018        let panel = workspace.update_in(cx, GitPanel::new);
7019        panel.read_with(cx, |panel, cx| {
7020            assert!(panel.active_repository.is_some());
7021            assert!(panel.head_commit(cx).is_some());
7022        });
7023
7024        panel.update_in(cx, |panel, window, cx| {
7025            // Update the commit editor's message to ensure that its contents
7026            // are later restored, after amending is finished.
7027            panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7028                buffer.set_text("refactor: update main.rs", cx);
7029            });
7030
7031            // Start amending the previous commit.
7032            panel.focus_editor(&Default::default(), window, cx);
7033            panel.on_amend(&Amend, window, cx);
7034        });
7035
7036        // Since `GitPanel.amend` attempts to fetch the latest commit message in
7037        // a background task, we need to wait for it to complete before being
7038        // able to assert that the commit message editor's state has been
7039        // updated.
7040        cx.run_until_parked();
7041
7042        panel.update_in(cx, |panel, window, cx| {
7043            assert_eq!(
7044                panel.commit_message_buffer(cx).read(cx).text(),
7045                "initial commit"
7046            );
7047            assert_eq!(
7048                panel.original_commit_message,
7049                Some("refactor: update main.rs".to_string())
7050            );
7051
7052            // Finish amending the previous commit.
7053            panel.focus_editor(&Default::default(), window, cx);
7054            panel.on_amend(&Amend, window, cx);
7055        });
7056
7057        // Since the actual commit logic is run in a background task, we need to
7058        // await its completion to actually ensure that the commit message
7059        // editor's contents are set to the original message and haven't been
7060        // cleared.
7061        cx.run_until_parked();
7062
7063        panel.update_in(cx, |panel, _window, cx| {
7064            // After amending, the commit editor's message should be restored to
7065            // the original message.
7066            assert_eq!(
7067                panel.commit_message_buffer(cx).read(cx).text(),
7068                "refactor: update main.rs"
7069            );
7070            assert!(panel.original_commit_message.is_none());
7071        });
7072    }
7073
7074    #[gpui::test]
7075    async fn test_open_diff(cx: &mut TestAppContext) {
7076        init_test(cx);
7077
7078        let fs = FakeFs::new(cx.background_executor.clone());
7079        fs.insert_tree(
7080            path!("/project"),
7081            json!({
7082                ".git": {},
7083                "tracked": "tracked\n",
7084                "untracked": "\n",
7085            }),
7086        )
7087        .await;
7088
7089        fs.set_head_and_index_for_repo(
7090            path!("/project/.git").as_ref(),
7091            &[("tracked", "old tracked\n".into())],
7092        );
7093
7094        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7095        let window_handle =
7096            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7097        let workspace = window_handle
7098            .read_with(cx, |mw, _| mw.workspace().clone())
7099            .unwrap();
7100        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7101        let panel = workspace.update_in(cx, GitPanel::new);
7102
7103        // Enable the `sort_by_path` setting and wait for entries to be updated,
7104        // as there should no longer be separators between Tracked and Untracked
7105        // files.
7106        cx.update(|_window, cx| {
7107            SettingsStore::update_global(cx, |store, cx| {
7108                store.update_user_settings(cx, |settings| {
7109                    settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7110                })
7111            });
7112        });
7113
7114        cx.update_window_entity(&panel, |panel, _, _| {
7115            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7116        })
7117        .await;
7118
7119        // Confirm that `Open Diff` still works for the untracked file, updating
7120        // the Project Diff's active path.
7121        panel.update_in(cx, |panel, window, cx| {
7122            panel.selected_entry = Some(1);
7123            panel.open_diff(&menu::Confirm, window, cx);
7124        });
7125        cx.run_until_parked();
7126
7127        workspace.update_in(cx, |workspace, _window, cx| {
7128            let active_path = workspace
7129                .item_of_type::<ProjectDiff>(cx)
7130                .expect("ProjectDiff should exist")
7131                .read(cx)
7132                .active_path(cx)
7133                .expect("active_path should exist");
7134
7135            assert_eq!(active_path.path, rel_path("untracked").into_arc());
7136        });
7137    }
7138
7139    #[gpui::test]
7140    async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
7141        cx: &mut TestAppContext,
7142    ) {
7143        init_test(cx);
7144
7145        let fs = FakeFs::new(cx.background_executor.clone());
7146        fs.insert_tree(
7147            path!("/project"),
7148            json!({
7149                ".git": {},
7150                "src": {
7151                    "a": {
7152                        "foo.rs": "fn foo() {}",
7153                    },
7154                    "b": {
7155                        "bar.rs": "fn bar() {}",
7156                    },
7157                },
7158            }),
7159        )
7160        .await;
7161
7162        fs.set_status_for_repo(
7163            path!("/project/.git").as_ref(),
7164            &[
7165                ("src/a/foo.rs", StatusCode::Modified.worktree()),
7166                ("src/b/bar.rs", StatusCode::Modified.worktree()),
7167            ],
7168        );
7169
7170        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7171        let window_handle =
7172            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7173        let workspace = window_handle
7174            .read_with(cx, |mw, _| mw.workspace().clone())
7175            .unwrap();
7176        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7177
7178        cx.read(|cx| {
7179            project
7180                .read(cx)
7181                .worktrees(cx)
7182                .next()
7183                .unwrap()
7184                .read(cx)
7185                .as_local()
7186                .unwrap()
7187                .scan_complete()
7188        })
7189        .await;
7190
7191        cx.executor().run_until_parked();
7192
7193        cx.update(|_window, cx| {
7194            SettingsStore::update_global(cx, |store, cx| {
7195                store.update_user_settings(cx, |settings| {
7196                    settings.git_panel.get_or_insert_default().tree_view = Some(true);
7197                })
7198            });
7199        });
7200
7201        let panel = workspace.update_in(cx, GitPanel::new);
7202
7203        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7204            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7205        });
7206        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7207        handle.await;
7208
7209        let src_key = panel.read_with(cx, |panel, _| {
7210            panel
7211                .entries
7212                .iter()
7213                .find_map(|entry| match entry {
7214                    GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7215                        Some(dir.key.clone())
7216                    }
7217                    _ => None,
7218                })
7219                .expect("src directory should exist in tree view")
7220        });
7221
7222        panel.update_in(cx, |panel, window, cx| {
7223            panel.toggle_directory(&src_key, window, cx);
7224        });
7225
7226        panel.read_with(cx, |panel, _| {
7227            let state = panel
7228                .view_mode
7229                .tree_state()
7230                .expect("tree view state should exist");
7231            assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7232        });
7233
7234        let worktree_id =
7235            cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7236        let project_path = ProjectPath {
7237            worktree_id,
7238            path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7239        };
7240
7241        panel.update_in(cx, |panel, window, cx| {
7242            panel.select_entry_by_path(project_path, window, cx);
7243        });
7244
7245        panel.read_with(cx, |panel, _| {
7246            let state = panel
7247                .view_mode
7248                .tree_state()
7249                .expect("tree view state should exist");
7250            assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7251
7252            let selected_ix = panel.selected_entry.expect("selection should be set");
7253            assert!(state.logical_indices.contains(&selected_ix));
7254
7255            let selected_entry = panel
7256                .entries
7257                .get(selected_ix)
7258                .and_then(|entry| entry.status_entry())
7259                .expect("selected entry should be a status entry");
7260            assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7261        });
7262    }
7263
7264    #[gpui::test]
7265    async fn test_tree_view_select_next_at_last_visible_collapsed_directory(
7266        cx: &mut TestAppContext,
7267    ) {
7268        init_test(cx);
7269
7270        let fs = FakeFs::new(cx.background_executor.clone());
7271        fs.insert_tree(
7272            path!("/project"),
7273            json!({
7274                ".git": {},
7275                "bar": {
7276                    "bar1.py": "print('bar1')",
7277                    "bar2.py": "print('bar2')",
7278                },
7279                "foo": {
7280                    "foo1.py": "print('foo1')",
7281                    "foo2.py": "print('foo2')",
7282                },
7283                "foobar.py": "print('foobar')",
7284            }),
7285        )
7286        .await;
7287
7288        fs.set_status_for_repo(
7289            path!("/project/.git").as_ref(),
7290            &[
7291                ("bar/bar1.py", StatusCode::Modified.worktree()),
7292                ("bar/bar2.py", StatusCode::Modified.worktree()),
7293                ("foo/foo1.py", StatusCode::Modified.worktree()),
7294                ("foo/foo2.py", StatusCode::Modified.worktree()),
7295                ("foobar.py", FileStatus::Untracked),
7296            ],
7297        );
7298
7299        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7300        let window_handle =
7301            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7302        let workspace = window_handle
7303            .read_with(cx, |mw, _| mw.workspace().clone())
7304            .unwrap();
7305        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7306
7307        cx.read(|cx| {
7308            project
7309                .read(cx)
7310                .worktrees(cx)
7311                .next()
7312                .unwrap()
7313                .read(cx)
7314                .as_local()
7315                .unwrap()
7316                .scan_complete()
7317        })
7318        .await;
7319
7320        cx.executor().run_until_parked();
7321        cx.update(|_window, cx| {
7322            SettingsStore::update_global(cx, |store, cx| {
7323                store.update_user_settings(cx, |settings| {
7324                    settings.git_panel.get_or_insert_default().tree_view = Some(true);
7325                })
7326            });
7327        });
7328
7329        let panel = workspace.update_in(cx, GitPanel::new);
7330        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7331            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7332        });
7333
7334        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7335        handle.await;
7336
7337        let foo_key = panel.read_with(cx, |panel, _| {
7338            panel
7339                .entries
7340                .iter()
7341                .find_map(|entry| match entry {
7342                    GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => {
7343                        Some(dir.key.clone())
7344                    }
7345                    _ => None,
7346                })
7347                .expect("foo directory should exist in tree view")
7348        });
7349
7350        panel.update_in(cx, |panel, window, cx| {
7351            panel.toggle_directory(&foo_key, window, cx);
7352        });
7353
7354        let foo_idx = panel.read_with(cx, |panel, _| {
7355            let state = panel
7356                .view_mode
7357                .tree_state()
7358                .expect("tree view state should exist");
7359            assert_eq!(state.expanded_dirs.get(&foo_key).copied(), Some(false));
7360
7361            let foo_idx = panel
7362                .entries
7363                .iter()
7364                .enumerate()
7365                .find_map(|(index, entry)| match entry {
7366                    GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => Some(index),
7367                    _ => None,
7368                })
7369                .expect("foo directory should exist in tree view");
7370
7371            let foo_logical_idx = state
7372                .logical_indices
7373                .iter()
7374                .position(|&index| index == foo_idx)
7375                .expect("foo directory should be visible");
7376            let next_logical_idx = state.logical_indices[foo_logical_idx + 1];
7377            assert!(matches!(
7378                panel.entries.get(next_logical_idx),
7379                Some(GitListEntry::Header(GitHeaderEntry {
7380                    header: Section::New
7381                }))
7382            ));
7383
7384            foo_idx
7385        });
7386
7387        panel.update_in(cx, |panel, window, cx| {
7388            panel.selected_entry = Some(foo_idx);
7389            panel.select_next(&menu::SelectNext, window, cx);
7390        });
7391
7392        panel.read_with(cx, |panel, _| {
7393            let selected_idx = panel.selected_entry.expect("selection should be set");
7394            let selected_entry = panel
7395                .entries
7396                .get(selected_idx)
7397                .and_then(|entry| entry.status_entry())
7398                .expect("selected entry should be a status entry");
7399            assert_eq!(selected_entry.repo_path, repo_path("foobar.py"));
7400        });
7401    }
7402
7403    fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7404        assert_eq!(entries.len(), expected_paths.len());
7405        for (entry, expected_path) in entries.iter().zip(expected_paths) {
7406            assert_eq!(
7407                entry.status_entry().map(|status| status
7408                    .repo_path
7409                    .as_ref()
7410                    .as_std_path()
7411                    .to_string_lossy()
7412                    .to_string()),
7413                expected_path.map(|s| s.to_string())
7414            );
7415        }
7416    }
7417
7418    #[test]
7419    fn test_compress_diff_no_truncation() {
7420        let diff = indoc! {"
7421            --- a/file.txt
7422            +++ b/file.txt
7423            @@ -1,2 +1,2 @@
7424            -old
7425            +new
7426        "};
7427        let result = GitPanel::compress_commit_diff(diff, 1000);
7428        assert_eq!(result, diff);
7429    }
7430
7431    #[test]
7432    fn test_compress_diff_truncate_long_lines() {
7433        let long_line = "🦀".repeat(300);
7434        let diff = indoc::formatdoc! {"
7435            --- a/file.txt
7436            +++ b/file.txt
7437            @@ -1,2 +1,3 @@
7438             context
7439            +{}
7440             more context
7441        ", long_line};
7442        let result = GitPanel::compress_commit_diff(&diff, 100);
7443        assert!(result.contains("...[truncated]"));
7444        assert!(result.len() < diff.len());
7445    }
7446
7447    #[test]
7448    fn test_compress_diff_truncate_hunks() {
7449        let diff = indoc! {"
7450            --- a/file.txt
7451            +++ b/file.txt
7452            @@ -1,2 +1,2 @@
7453             context
7454            -old1
7455            +new1
7456            @@ -5,2 +5,2 @@
7457             context 2
7458            -old2
7459            +new2
7460            @@ -10,2 +10,2 @@
7461             context 3
7462            -old3
7463            +new3
7464        "};
7465        let result = GitPanel::compress_commit_diff(diff, 100);
7466        let expected = indoc! {"
7467            --- a/file.txt
7468            +++ b/file.txt
7469            @@ -1,2 +1,2 @@
7470             context
7471            -old1
7472            +new1
7473            [...skipped 2 hunks...]
7474        "};
7475        assert_eq!(result, expected);
7476    }
7477
7478    #[gpui::test]
7479    async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7480        init_test(cx);
7481
7482        let fs = FakeFs::new(cx.background_executor.clone());
7483        fs.insert_tree(
7484            path!("/project"),
7485            json!({
7486                ".git": {},
7487                "tracked": "tracked\n",
7488                "untracked": "\n",
7489            }),
7490        )
7491        .await;
7492
7493        fs.set_head_and_index_for_repo(
7494            path!("/project/.git").as_ref(),
7495            &[("tracked", "old tracked\n".into())],
7496        );
7497
7498        let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7499        let window_handle =
7500            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7501        let workspace = window_handle
7502            .read_with(cx, |mw, _| mw.workspace().clone())
7503            .unwrap();
7504        let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7505        let panel = workspace.update_in(cx, GitPanel::new);
7506
7507        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7508            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7509        });
7510        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7511        handle.await;
7512
7513        let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7514
7515        // GitPanel
7516        // - Tracked:
7517        // - [] tracked
7518        // - Untracked
7519        // - [] untracked
7520        //
7521        // The commit message should now read:
7522        // "Update tracked"
7523        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7524        assert_eq!(message, Some("Update tracked".to_string()));
7525
7526        let first_status_entry = entries[1].clone();
7527        panel.update_in(cx, |panel, window, cx| {
7528            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7529        });
7530
7531        cx.read(|cx| {
7532            project
7533                .read(cx)
7534                .worktrees(cx)
7535                .next()
7536                .unwrap()
7537                .read(cx)
7538                .as_local()
7539                .unwrap()
7540                .scan_complete()
7541        })
7542        .await;
7543
7544        cx.executor().run_until_parked();
7545
7546        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7547            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7548        });
7549        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7550        handle.await;
7551
7552        // GitPanel
7553        // - Tracked:
7554        // - [x] tracked
7555        // - Untracked
7556        // - [] untracked
7557        //
7558        // The commit message should still read:
7559        // "Update tracked"
7560        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7561        assert_eq!(message, Some("Update tracked".to_string()));
7562
7563        let second_status_entry = entries[3].clone();
7564        panel.update_in(cx, |panel, window, cx| {
7565            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7566        });
7567
7568        cx.read(|cx| {
7569            project
7570                .read(cx)
7571                .worktrees(cx)
7572                .next()
7573                .unwrap()
7574                .read(cx)
7575                .as_local()
7576                .unwrap()
7577                .scan_complete()
7578        })
7579        .await;
7580
7581        cx.executor().run_until_parked();
7582
7583        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7584            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7585        });
7586        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7587        handle.await;
7588
7589        // GitPanel
7590        // - Tracked:
7591        // - [x] tracked
7592        // - Untracked
7593        // - [x] untracked
7594        //
7595        // The commit message should now read:
7596        // "Enter commit message"
7597        // (which means we should see None returned).
7598        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7599        assert!(message.is_none());
7600
7601        panel.update_in(cx, |panel, window, cx| {
7602            panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7603        });
7604
7605        cx.read(|cx| {
7606            project
7607                .read(cx)
7608                .worktrees(cx)
7609                .next()
7610                .unwrap()
7611                .read(cx)
7612                .as_local()
7613                .unwrap()
7614                .scan_complete()
7615        })
7616        .await;
7617
7618        cx.executor().run_until_parked();
7619
7620        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7621            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7622        });
7623        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7624        handle.await;
7625
7626        // GitPanel
7627        // - Tracked:
7628        // - [] tracked
7629        // - Untracked
7630        // - [x] untracked
7631        //
7632        // The commit message should now read:
7633        // "Update untracked"
7634        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7635        assert_eq!(message, Some("Create untracked".to_string()));
7636
7637        panel.update_in(cx, |panel, window, cx| {
7638            panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7639        });
7640
7641        cx.read(|cx| {
7642            project
7643                .read(cx)
7644                .worktrees(cx)
7645                .next()
7646                .unwrap()
7647                .read(cx)
7648                .as_local()
7649                .unwrap()
7650                .scan_complete()
7651        })
7652        .await;
7653
7654        cx.executor().run_until_parked();
7655
7656        let handle = cx.update_window_entity(&panel, |panel, _, _| {
7657            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7658        });
7659        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7660        handle.await;
7661
7662        // GitPanel
7663        // - Tracked:
7664        // - [] tracked
7665        // - Untracked
7666        // - [] untracked
7667        //
7668        // The commit message should now read:
7669        // "Update tracked"
7670        let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7671        assert_eq!(message, Some("Update tracked".to_string()));
7672    }
7673}