git_panel.rs

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