git_panel.rs

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