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