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