git_panel.rs

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