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