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