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