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