git_panel.rs

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