git_panel.rs

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