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