git_panel.rs

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